Minimum steps to convert X to Y by repeated division and multiplication
Given two integers X and Y, the task is to find the minimum number of steps to convert integer X to Y using any of the operations in each step:
- Divide the number by any natural number
- Multiply the number with any natural number
Input: X = 8, Y = 12
First divide 8 by 2: 8/2 = 4
Then multiply by 3: 4*3 = 12
Input: X = 4, Y = 8
To convert 4 to 8 multiply 4 by 2: 4 * 2 = 8
Approach: To solve the problem mentioned above:
- Make sure X contains the smaller value among X and Y. Now, if X is greater than Y then we know that it is always easier to change a smaller number to a larger number. Hence, we just swap the values of X and Y and then follow the steps mentioned below.
- If both the integers are the same then the answer will be zero as no conversion takes place.
If X = 4, Y = 4 Here 4 = 4 Therefore, answer = 0 (as they both are already same)
- However, if X is less than Y then:
- we have to check that Y % X gives 0 or not.
- If yes, then Y can be represented as X * (Y / X) and we get the desired output in single-step.
If X = 4, Y = 12 Here 12 % 4 = 0 Therefore, answer = 1 (4 * 3 = 12)
- Otherwise, the answer will be 2 as it takes two steps, one for division (X = X/X) and the other for multiplication (X = X * Y).
If X = 8, Y = 13 Here 13 % 8 != 0 Therefore, 1. X = X/X = 8/8 = 1 2. X = X*Y = 1*13 = 13 Hence, answer = 2
Below is the implementation of the above approach:
Time Complexity: O(1), as we are using only constant-time operations.
Auxiliary Space: O(1), as we are not using any extra space.