Min operations to reduce N by multiplying by any number or taking square root
Last Updated :
22 Apr, 2021
Given a number N, the task is to find the minimum value of N by applying below operations any number of times:
Examples:
Input: N = 20
Output: 10
Explanation:
Multiply -> 20 * 5 = 100
sqrt(100) = 10, which is the minimum value obtainable.
Input: N = 5184
Output: 6
Explanation:
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:
C++
#include <bits/stdc++.h>
using namespace std;
void minValue( int n)
{
while ( int ( sqrt (n)) == sqrt (n)
&& n > 1) {
n = sqrt (n);
}
for ( int i = sqrt (n);
i > 1; i--) {
while (n % (i * i) == 0)
n /= i;
}
cout << n;
}
int main()
{
int N = 20;
minValue(N);
}
|
Java
import java.lang.Math;
class GFG{
static void minValue( int n)
{
while (( int )Math.sqrt(n) ==
Math.sqrt(n) && n > 1 )
{
n = ( int )(Math.sqrt(n));
}
for ( int i = ( int )(Math.sqrt(n));
i > 1 ; i--)
{
while (n % (i * i) == 0 )
n /= i;
}
System.out.println(n);
}
public static void main(String args[])
{
int N = 20 ;
minValue(N);
}
}
|
Python3
import math
def MinValue(n):
while ( int (math.sqrt(n)) = =
math.sqrt(n) and n > 1 ):
n = math.sqrt(n)
for i in range ( int (math.sqrt(n)), 1 , - 1 ):
while (n % (i * i) = = 0 ):
n / = i
print (n)
n = 20
MinValue(n)
|
C#
using System;
class GFG{
static void minValue( int n)
{
while (( int )Math.Sqrt(n) ==
Math.Sqrt(n) && n > 1)
{
n = ( int )(Math.Sqrt(n));
}
for ( int i = ( int )(Math.Sqrt(n));
i > 1; i--)
{
while (n % (i * i) == 0)
n /= i;
}
Console.Write(n);
}
public static void Main()
{
int N = 20;
minValue(N);
}
}
|
Javascript
<script>
function minValue(n)
{
while (parseInt(Math.sqrt(n)) == Math.sqrt(n)
&& n > 1)
{
n = parseInt(Math.sqrt(n));
}
for ( var i = parseInt(Math.sqrt(n));
i > 1; i--) {
while (n % (i * i) == 0)
n /= i;
}
document.write(n);
}
var N = 20;
minValue(N);
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...