给定整数N ,以下操作可以对N执行任意次:
- 将N乘以任何正整数X,即N = N * X。
- 随N平方根替换N(N必须是一个整数),即N = SQRT(N)。
任务是找到可以通过上述操作将N减少为的最小整数。
例子:
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.
方法:
- 首先分解数字N。
- 假设12具有因子2、2和5 。使用sqrt(n)只能减少重复的因子,即sqrt(2 * 2)= 2 。
- 在这些因素中仅出现一次的数字无法进一步减少。
- 因此,最终答案将是数字N的所有不同素数的乘积
下面是上述方法的实现:
C++
// C++ implementation of the above approach
#include
#define ll long long int
using namespace std;
// function to return the product of
// distinct prime factors of a number
ll minimum(ll n)
{
ll product = 1;
// find distinct prime
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;
}
// Driver code
int main()
{
ll n = 20;
cout << minimum(n) << endl;
return 0;
}
Java
// Java implementation of the above approach
import java.util.*;
class solution
{
// function to return the product of
// distinct prime factors of a number
static int minimum(int n)
{
int product = 1;
// find distinct prime
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;
}
// Driver code
public static void main(String arr[])
{
int n = 20;
System.out.println(minimum(n));
}
}
//This code is contributed by
//Surendra_Gangwar
Python3
# Python3 implementation of above approach
# function to return the product
# of distinct prime factors of a
# numberdef minSteps(str):
def minimum(n):
product = 1
# find distinct prime
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
# Driver code
# Get the binary string
n = 20
print(minimum(n))
# This code is contributed
# by Shashank_Sharma
C#
// C# implementation of the above approach
class GFG
{
// function to return the product of
// distinct prime factors of a number
static int minimum(int n)
{
int product = 1;
// find distinct prime
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;
}
// Driver code
static void Main()
{
int n = 20;
System.Console.WriteLine(minimum(n));
}
}
// This code is contributed by mits
PHP
= 2)
$product = $product * $n;
return $product;
}
// Driver code
$n = 20;
echo minimum($n),"\n";
// This code is contributed by ANKITRAI1
?>
输出:
10