Given two integers n and m and a and b, in a single operation n can be multiplied by either a or b. The task is to convert n to m with a minimum number of given operation. If it is impossible to convert n to m with the given operation then print -1.
Input: n = 120, m = 51840, a = 2, b = 3 Output: 7 120 * 2 * 2 * 2 * 2 * 3 * 3 * 3 = 51840 Input: n = 10, m = 50, a = 5, b = 7 Output: 1 10 * 5 = 50
In the previous post, we discussed an approach using division.
In this post, we will use an approach which finds the minimum number of operations using recursion. The recursion will consist of two states, the number being multiplied by a or by b, and counting the steps. The minimum of both the steps will be the answer.
Below is the implementation of the above approach:
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Divide two integers without using multiplication, division and mod operator | Set2
- Minimum operations required to convert X to Y by multiplying X with the given co-primes
- Minimum operations required to convert all characters of a String to a given Character
- Convert a number m to n using minimum number of given operations
- Find the minimum number of operations required to make all array elements equal
- Minimum number of given operations required to reduce the array to 0 element
- Minimum number of operations required to obtain a given Binary String
- Minimum number of steps required to obtain the given Array by the given operations
- Minimum number of operations required to reduce N to 0
- Minimum number of operations required to reduce N to 1
- Minimum number of given operation required to convert n to m
- Minimum splits required to convert a number into prime segments
- Minimum prime number operations to convert A to B
- Minimum number of operations to convert array A to array B by adding an integer into a subarray
- Minimum number of operations to convert a given sequence into a Geometric Progression | Set 2
- Count of minimum reductions required to get the required sum K
- Count the number of operations required to reduce the given number
- Minimum operations required to make all the elements distinct in an array
- Minimum operations required to make all Array elements divisible by K
- Minimum operations of the given type required to make a complete graph
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.