Convert a number m to n with minimum operations. The operations allowed are :
- Multiply by 2, i.e., do m = 2 * m
- Subtract 1, i.e., do m = m – 1
Print -1 if it is not possible to convert.
Input : m = 3, n = 11 Output : 3 1st operation: *2 = 3*2 = 6 2nd operation: *2 = 6*2 = 12 3rd operation: -1 = 12-1 = 11 Input : m = 15, n = 20 Output : 6 1st operation: -1 '5' times = 15 + (-1*5) = 10 2nd operation: *2 = 10*2 = 20 Input : m = 0, n = 8 Output : -1 Using the given set of operations 'm' cannot be converted to 'n' Input : m = 12, n = 8 Output : 4
The idea is based on below facts.
1) If m is less than 0 and n is greater than 0, then not possible.
2) If m is greater than n, then we can reach n using subtractions only.
3) Else (m is less than n), we must do m*2 operations. Following two cases arise.
……a) If n is odd, we must do a -1 operation to reach it.
……b) If n is even, we must do a *2 operation to reach it.
int convert(m,n) if (m == n) return 0; // not possible if (m <= 0 && n > 0) return -1; // m is greater than n if (m > n) return m-n; // n is odd if (n % 2 == 1) // perform '-1' return 1 + convert(m, n+1); // n is even else // perform '*2' return 1 + convert(m, n/2);
Note: The list of operations so generated should be applied in reverse order.
m = 3, n = 11 convert(3,11) | --> n is odd: operation '-1' convert(3,12) | --> n is even: operation '*2' convert(3,6) | --> n is even: operation '*2' convert(3,3) | --> m == n return Therefore, the sequence of operations is '*2', '*2', '-1'.
Minimum number of operations : 3
This article is contributed by Ayush Jauhari. 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 write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Write a program to reverse digits of a number
- Write an Efficient Method to Check if a Number is Multiple of 3
- Write an Efficient C Program to Reverse Bits of a Number
- Minimum number of jumps to reach end
- Find minimum number to be divided to make a number a perfect square
- Find whether a given number is a power of 4 or not
- Print all combinations of points that can compose a given number
- Check if a number is multiple of 5 without using / and % operators
- Given a number, find the next smallest palindrome
- Count the number of possible triangles
- Select a random number from stream, with O(1) space
- Program to convert a given number to words
- Efficient program to print all prime factors of a given number
- Check if a number is Palindrome
- Random number generator in arbitrary probability distribution fashion