Find the minimum number of steps to reach M from N in C++

C++Server Side ProgrammingProgramming

Suppose we have two integers N and M. We have to find minimum number of steps to reach M from N, by performing given operations −

  • Multiply the number x by 2, so x will be 2*x
  • Subtract one from the number x, so the number will be x – 1

If N = 4 and M = 6, then output will be 2. So if we perform operation number 2 on N, then N becomes 3, then perform operation number one on updated value of N, so it becomes 2 * 3 = 6. So the minimum number of steps will be 2.

To solve this problem, we will follow these rules −

  • We can reverse the problem, like we take the number N starting from M, so new two operations will be

    • Divide the number by 2, when it is even,
    • add 1 with the number
  • Now the minimum number of operations will be
    • if N > M, return the difference between them, so number of steps will be adding 1 to M, until it becomes equal to N
    • Otherwise when N < M, keep dividing M by 2, until it becomes less than N. If M is odd, then add 1 to it first, then divide by 2, Once M is less than N, add the difference between them to the count along with the count of above operations.

Example

 Live Demo

#include<iostream>
using namespace std;
int countMinimumSteps(int n, int m) {
   int count = 0;
   while(m > n) {
      if(m % 2 == 1) {
         m++;
         count++;
      }
      m /= 2;
      count++;
   }
   return count + n - m;
}
int main() {
   int n = 4, m = 6;
   cout << "Minimum number of operations required: " << countMinimumSteps(n, m);
}

Output

Minimum number of operations required: 2
raja
Published on 18-Dec-2019 12:44:30
Advertisements