给定数字X ,找到大于1的最小数字,该最小数字除以X X。在给定的问题中,始终假定X大于1。
例子:
Input: X = 6
Output: 2
Explanation: As, 66 is equal to 46656, which is divisible by 2 and it’s the smallest among all its divisors.
Input: X = 3
Output: 3
Explanation: As, 33 is equal to 27, which is divisible by 3 and it’s the smallest among all its divisors.
方法:
这个问题的主要观察结果是,如果数字P除以X ,那么它也除以X X ,因此我们不需要计算X X的值。我们需要做的是找到除以X的最小数字,该数字将始终是素数。
下面是上述方法的实现:
C++
// C++ implementation of above approach
#include
using namespace std;
// Function to find the required smallest number
int SmallestDiv(int n)
{
for (int i = 2; i * i <= n; i++) {
// Finding smallest number that divides n
if (n % i == 0) {
// i divides n and return this
// value immediately
return i;
}
}
// If n is a prime number then answer should be n,
// As we can't take 1 as our answer.
return n;
}
// Driver Code
int main()
{
int X = 385;
int ans = SmallestDiv(X);
cout << ans << "\n";
return 0;
}
Java
// Java implementation of above approach
class GFG{
// Function to find the
// required smallest number
static int SmallestDiv(int n)
{
for(int i = 2; i * i <= n; i++)
{
// Finding smallest number
// that divides n
if (n % i == 0)
{
// i divides n and return this
// value immediately
return i;
}
}
// If n is a prime number then
// answer should be n, as we
// can't take 1 as our answer.
return n;
}
// Driver Code
public static void main(String[] args)
{
int X = 385;
int ans = SmallestDiv(X);
System.out.print(ans + "\n");
}
}
// This code is contributed by gauravrajput1
Python3
# Python3 implementation of above approach
# Function to find the required smallest number
def SmallestDiv(n):
i = 2
while i * i <= n:
# Finding smallest number that divides n
if (n % i == 0):
# i divides n and return this
# value immediately
return i
i += 1
# If n is a prime number then answer should be n,
# As we can't take 1 as our answer.
return n
# Driver Code
if __name__=="__main__":
X = 385
ans = SmallestDiv(X)
print(ans)
# This code is contributed by Yash_R
C#
// C# implementation of above approach
using System;
class GFG {
// Function to find the
// required smallest number
static int SmallestDiv(int n)
{
for(int i = 2; i * i <= n; i++)
{
// Finding smallest number
// that divides n
if (n % i == 0)
{
// i divides n and return this
// value immediately
return i;
}
}
// If n is a prime number then
// answer should be n, as we
// can't take 1 as our answer.
return n;
}
// Driver code
public static void Main(String[] args)
{
int X = 385;
int ans = SmallestDiv(X);
Console.Write(ans + "\n");
}
}
// This code is contributed by shivanisinghss2110
Javascript
Output: 5
时间复杂度: O(sqrt(X))