Min operations to reduce N by multiplying by any number or taking square root
Given a number N, the task is to find the minimum value of N by applying below operations any number of times:
- Multiply N by any positive integer
- Replace N with sqrt(N), only if N is a perfect square.
Attention reader! All those who say programming isn't for kids, just haven't met the right mentors yet. Join the Demo Class for First Step to Coding Course, specifically designed for students of class 8 to 12.
The students will get to learn more about the world of programming in these free classes which will definitely help them in making a wise career choice in the future.
Input: N = 20
Multiply -> 20 * 5 = 100
sqrt(100) = 10, which is the minimum value obtainable.
Input: N = 5184
sqrt(5184) = 72.
Multiply -> 72*18 = 1296
sqrt(1296) = 6, which is the minimum value obtainable.
Approach: This problem can be solved using Greedy Approach. Below are the steps:
- Keep replacing N to sqrt(N) until N is a perfect square.
- After the above step, iterate from sqrt(N) to 2, and for every, i keep replacing N with N / i if N is divisible by i2.
- The value of N after the above step will be the minimum possible value.
Below is the implementation of the above approach:
Time Complexity: O(N)
Auxiliary Space: O(1)