Minimize the value of N by applying the given operations
Given an integer N, below operations can be performed any number of times on N:
- Multiply N by any positive integer X i.e. N = N * X.
- Replace N with square root of N (N must be an integer) i.e. N = sqrt(N).
The task is to find the minimum integer to which N can be reduced with the above operations.
Examples:
Input: N = 20
Output: 10
We can multiply 20 by 5, then take sqrt(20*5) = 10, this is the minimum number that 20 can be reduced to with the given operations.
Input: N = 36
Output: 6
Take sqrt(36). Number 6 can’t be reduced further.
Approach:
- First factorize the number N.
- Say, 12 has factors 2, 2 and 5. Only the factors that are repeating can be reduced with sqrt(n) i.e. sqrt(2*2) = 2.
- The numbers appearing only once in the factors cannot be further reduced.
- So, the final answer will be the product of all the distinct prime factors of number N
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
#define ll long long int
using namespace std;
ll minimum(ll n)
{
ll product = 1;
for ( int i = 2; i * i <= n; i++) {
if (n % i == 0) {
while (n % i == 0)
n = n / i;
product = product * i;
}
}
if (n >= 2)
product = product * n;
return product;
}
int main()
{
ll n = 20;
cout << minimum(n) << endl;
return 0;
}
|
Java
import java.util.*;
class solution
{
static int minimum( int n)
{
int product = 1 ;
for ( int i = 2 ; i * i <= n; i++) {
if (n % i == 0 ) {
while (n % i == 0 )
n = n / i;
product = product * i;
}
}
if (n >= 2 )
product = product * n;
return product;
}
public static void main(String arr[])
{
int n = 20 ;
System.out.println(minimum(n));
}
}
|
Python3
def minimum(n):
product = 1
i = 2
while i * i < = n:
if n % i = = 0 :
while n % i = = 0 :
n = n / i
product = product * i
i = i + 1
if n > = 2 :
product = product * n
return product
n = 20
print (minimum(n))
|
C#
class GFG
{
static int minimum( int n)
{
int product = 1;
for ( int i = 2; i * i <= n; i++)
{
if (n % i == 0)
{
while (n % i == 0)
n = n / i;
product = product * i;
}
}
if (n >= 2)
product = product * n;
return product;
}
static void Main()
{
int n = 20;
System.Console.WriteLine(minimum(n));
}
}
|
PHP
<?php
function minimum( $n )
{
$product = 1;
for ( $i = 2; $i * $i <= $n ; $i ++)
{
if ( $n % $i == 0)
{
while ( $n % $i == 0)
$n = $n / $i ;
$product = $product * $i ;
}
}
if ( $n >= 2)
$product = $product * $n ;
return $product ;
}
$n = 20;
echo minimum( $n ), "\n" ;
?>
|
Javascript
<script>
function minimum( n)
{
let product = 1;
for (let i = 2; i * i <= n; i++) {
if (n % i == 0) {
while (n % i == 0)
n = n / i;
product = product * i;
}
}
if (n >= 2)
product = product * n;
return product;
}
let n = 20;
document.write(minimum(n));
</script>
|
Time Complexity: O(sqrt(n))
Auxiliary Space: O(1)
Last Updated :
21 Sep, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...