
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Convert Number M to N Using Minimum Operations in C++
In this tutorial, we will be discussing a program to convert a number m to n using minimum number of given operations.
For this we will be provided with two integers m and n. Our task is to convert the integer m to n using the given operations least times.
Allowed operations −
Multiply the given number by 2
Subtract one from the given number
Example
#include <bits/stdc++.h> using namespace std; //finding minimum number of operations required int convert(int m, int n){ if (m == n) return 0; if (m > n) return m - n; //can't convert in this situation if (m <= 0 && n > 0) return -1; //when n is greater and n is odd if (n % 2 == 1) //performing '-1' on m return 1 + convert(m, n + 1); //when n is even else //performing '*2' on m return 1 + convert(m, n / 2); } int main(){ int m = 5, n = 11; cout << "Minimum number of operations : " << convert(m, n); return 0; }
Output
Minimum number of operations : 5
Advertisements