Minimum division by 10 and multiplication by 2 required to reduce given number to 1
Given an integer N, the task is to reduce N to 1 by a minimum number of operations involving multiplication by 2 and division by 10. If 1 cannot be obtained, then print “-1”.
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 = 5
Below are the operations performed:
1st operation: Multiply N by 2. Therefore, N = 5 * 2 = 10.
2nd operation: Divide N by 10. Therefore, N = 10/10 = 1.
Therefore, minimum number of operations required is 2.
Input: N = 4
Approach: The idea is to check prime factors of the given number M. If the given number has prime factors other than 2 and 5, then it is not possible to reduce the given number to 1 by the given operations. If the count of 2 exceeds that of 5 in its prime factors, then it is not possible to reduce N to 1 as all powers of 2 can’t be reduced.
Follow the steps below to solve the problem:
- Count the number of 2s present in prime factors of N and store it in a variable, say cnt2, and update N to N / 2cnt2.
- Count the number of 5s present in prime factors of N and store it in a variable, say cnt5, and update N to N / 5cnt5.
- After completing the above steps, if N is 1 and cnt2 ≤ cnt5, then the minimum number of steps required is 2 * cnt5 – cnt2.
- Otherwise, print “-1” as N can’t be reduced to 1 with the given operations.
Below is the implementation of the above approach:
Time Complexity: O(log N)
Auxiliary Space: O(1)