Minimum steps to change N to 1 by changing it to 2*N or N/10 at any step
Given an integer N, find the minimum number of operations to change N to 1. If not possible, print -1. One operation is defined as either converting N to the number 2*N or converting N to the number N/10(only if N is divisible by 10).
Attention reader! Don’t stop learning now. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
Input: N = 50
Explanation: N can be converted to 1 in 3 steps as follows:
-> Firstly, multiply N by 2 and change N from 50 to 100 (2*N)
-> Then, divide N by 10 and change N from 100 to 10 (N/10)
-> And then, divide N by 10 and change N from 10 to 1 (N/10)
Input: N = 120
Explanation: There is no possible way for Geek to get to position 1.
Approach: N can be converted to 1 only if N is reducible to 1 either by multiplying by 2 or dividing by 10 at each step. Now N can’t be reduced to 1 following these steps if N has a prime factor other than 2 and 5. Moreover, if the number of 2s is more than 5s in the prime factorization of N, N can’t reduce it to 1 because it will not be possible to neutralize all the 2s. Equal numbers of 2s and 5s can be neutralized by dividing the number by 10. The extra 5s can be neutralized by multiplying with extra 2s and then dividing by 10. Follow the steps below to solve the problem:
- Initialize the variables twos and fives as 0 to count the number of 2 and the number of 5 in the prime factorisation of the number N.
- Iterate in a while loop till N%2 is equal to 0 and perform the following steps:
- Divide the number N by 2.
- Increase the value of twos by 1.
- Iterate in a while loop till N%5 is equal to 0 and perform the following steps:
- Divide the number N by 5.
- Increase the value of fives by 1.
- If N is equal to 1 and the number of twos is less than equal to the number of fives, then, print 2*fives-twos as the answer.
- Else, print -1.
Below is the implementation of the above approach.
Time Complexity: O(log N)
Auxiliary Space: O(1)