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.
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)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.