Given two integers N and M. The task is to find the minimum number of steps to reach M from N by performing given operations.
- Multiply a number x by 2. So, x becomes 2*x.
- Subtract one from the number x. So, x becomes x-1.
Input : N = 4, M = 6 Output : 2 Explanation : Perform operation number 2 on N. So, N becomes 3 and then perform operation number 1. Then, N becomes 6. So, the minimum number of steps is 2. Input : N = 10, M = 1 Output : 9 Explanation : Perform operation number two 9 times on N. Then N becomes 1.
The idea is to reverse the problem as follows: We should get the number N starting from M using the operations:
- Divide the number by 2 if it is even.
- Add 1 to the number.
Now, the minimum number of operations would be:
- If N > M, return the difference between them, that is, number of steps will be adding 1 to M until it becomes equal to N.
- Else if N < M.
- Keep dividing M by 2 until it becomes less than N. If M is odd, add 1 to it first and 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.
Below is the implementation of the above approach:
- Number of steps required to reach point (x,y) from (0,0) using zig-zag way
- Minimize the number of steps required to reach the end of the array | Set 2
- Minimum number of jumps to reach end
- Find minimum moves to reach target on an infinite line
- Find the minimum of maximum length of a jump required to reach the last island in exactly k jumps
- Minimum number of moves required to reach the destination by the king in a chess board
- Find the number of stair steps
- Find the number of jumps to reach X in the number line from zero
- Minimum steps to color the tree with given colors
- Generate array with minimum sum which can be deleted in P steps
- Count minimum steps to get the given desired array
- Minimum step to reach one
- Make array elements equal in Minimum Steps
- Minimum steps to make the product of the array equal to 1
- Find minimum number to be divided to make a number a perfect square
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.