Convert a number m to n using minimum number of given 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

 Live Demo

#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

Updated on: 06-Jan-2020

561 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements