Find the Smallest number that divides X^X
Last Updated :
10 Aug, 2022
Given a number X, find the Smallest Number, which is greater than 1, that divides XX. In the given question, X is always presumed to be greater than 1.
Examples:
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.
Approach:
The main observation of this problem is that if a number P divides X, then it also divides XX, so we don’t need to calculate the value of XX. What we need to do is to find the smallest number that divides X which will always be a Prime Number.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int SmallestDiv( int n)
{
for ( int i = 2; i * i <= n; i++) {
if (n % i == 0) {
return i;
}
}
return n;
}
int main()
{
int X = 385;
int ans = SmallestDiv(X);
cout << ans << "\n" ;
return 0;
}
|
Java
class GFG{
static int SmallestDiv( int n)
{
for ( int i = 2 ; i * i <= n; i++)
{
if (n % i == 0 )
{
return i;
}
}
return n;
}
public static void main(String[] args)
{
int X = 385 ;
int ans = SmallestDiv(X);
System.out.print(ans + "\n" );
}
}
|
Python3
def SmallestDiv(n):
i = 2
while i * i < = n:
if (n % i = = 0 ):
return i
i + = 1
return n
if __name__ = = "__main__" :
X = 385
ans = SmallestDiv(X)
print (ans)
|
C#
using System;
class GFG {
static int SmallestDiv( int n)
{
for ( int i = 2; i * i <= n; i++)
{
if (n % i == 0)
{
return i;
}
}
return n;
}
public static void Main(String[] args)
{
int X = 385;
int ans = SmallestDiv(X);
Console.Write(ans + "\n" );
}
}
|
Javascript
<script>
function SmallestDiv(n)
{
for (let i = 2; i * i <= n; i++) {
if (n % i == 0) {
return i;
}
}
return n;
}
let X = 385;
let ans = SmallestDiv(X);
document.write(ans + "</br>" );
</script>
|
Output: 5
Time Complexity: O(sqrt(X))
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...