Given a number N and two integers A and B, the task is to check if it is possible to convert the number to 1 by the following two operations:
Multiply it by A
Divide it by B
If it is possible to reduce N to 1 then print the minimum number of operations required to achieve it otherwise print “-1”.
Input: N = 48, A = 3, B = 12 Output: 3 Explanation: Below are the 3 operations: 1. Divide 48 by 12 to get 4. 2. Multiply 4 by 3 to get 12. 3.Divide 12 by 12 to get 1. Hence the total number of operation is 3.
Input: N = 26, A = 3, B = 9 Output: -1 Explanation: It is not possible to convert 26 to 1.
Approach: The problem can be solved using Greedy Approach. The idea is to check if B is divisible by A or not and on the basis of that we have the below observations:
If B%A!= 0, then it is only possible to convert N to 1 if N is completely divisible by B and it would require N/B steps to do so. whereas if N = 1 then it would require 0 steps, otherwise it’s impossible and prints “-1”.
If B%A == 0, then consider a variable C whose value is B/A. Divide N by B, using the second operation until it cannot be divided any further, let’s call the number of division as x.
Again divide the remaining N by C until it cannot be divided any further, let’s call the number of divisions in this operation be y.
If N does not equal 1 after the above operations then it is impossible to convert N to 1 using the above-mentioned operations and the answer will be “-1”, but if it is equal to 1 then we can use the formula total_steps = x + (2 * y) to calculate the total minimum steps required.
Below is the implementation of the above approach:
Please Login to comment...