给定一个数字N ,任务是通过应用以下操作任意次数来找到N的最小值:
- 将N乘以任意正整数
- 将N替换为sqrt(N) ,仅当 N 是一个完美的平方时。
例子:
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.
方法:这个问题可以使用贪心方法解决。以下是步骤:
- 继续将N替换为sqrt(N)直到N是一个完美的平方。
- 在上述步骤之后,从sqrt(N)迭代到2 ,对于每一个,如果N 可以被 i 2整除,我会继续用N / i替换N 。
- 上述步骤后的N值将是可能的最小值。
下面是上述方法的实现:
C++
// C++ program for above approach
#include
using namespace std;
// Function to reduce N to its minimum
// possible value by the given operations
void minValue(int n)
{
// Keep replacing n until is
// an integer
while (int(sqrt(n)) == sqrt(n)
&& n > 1) {
n = sqrt(n);
}
// Keep replacing n until n
// is divisible by i * i
for (int i = sqrt(n);
i > 1; i--) {
while (n % (i * i) == 0)
n /= i;
}
// Print the answer
cout << n;
}
// Driver Code
int main()
{
// Given N
int N = 20;
// Function Call
minValue(N);
}
Java
// Java implementation of the above approach
import java.lang.Math;
class GFG{
// Function to reduce N to its minimum
// possible value by the given operations
static void minValue(int n)
{
// Keep replacing n until is
// an integer
while ((int)Math.sqrt(n) ==
Math.sqrt(n) && n > 1)
{
n = (int)(Math.sqrt(n));
}
// Keep replacing n until n
// is divisible by i * i
for(int i = (int)(Math.sqrt(n));
i > 1; i--)
{
while (n % (i * i) == 0)
n /= i;
}
// Print the answer
System.out.println(n);
}
// Driver code
public static void main(String args[])
{
// Given N
int N = 20;
// Function call
minValue(N);
}
}
// This code is contributed by vikas_g
Python3
# Python3 program for the above approach
import math
# Function to reduce N to its minimum
# possible value by the given operations
def MinValue(n):
# Keep replacing n until is
# an integer
while(int(math.sqrt(n)) ==
math.sqrt(n) and n > 1):
n = math.sqrt(n)
# Keep replacing n until n
# is divisible by i * i
for i in range(int(math.sqrt(n)), 1, -1):
while (n % (i * i) == 0):
n /= i
# Print the answer
print(n)
# Driver code
n = 20
# Function call
MinValue(n)
# This code is contributed by virusbuddah_
C#
// C# implementation of the approach
using System;
class GFG{
// Function to reduce N to its minimum
// possible value by the given operations
static void minValue(int n)
{
// Keep replacing n until is
// an integer
while ((int)Math.Sqrt(n) ==
Math.Sqrt(n) && n > 1)
{
n = (int)(Math.Sqrt(n));
}
// Keep replacing n until n
// is divisible by i * i
for (int i = (int)(Math.Sqrt(n));
i > 1; i--)
{
while (n % (i * i) == 0)
n /= i;
}
// Print the answer
Console.Write(n);
}
// Driver code
public static void Main()
{
// Given N
int N = 20;
// Function call
minValue(N);
}
}
// This code is contributed by vikas_g
Javascript
输出:
10
时间复杂度: O(N)
辅助空间: O(1)