Method 1 - Only Squares of Primes Have Exactly 3 Divisors#
An integer has exactly three positive divisors if and only if it is the square of a prime (since its divisors are 1, p, p^2). So, we check if n is a perfect square and its square root is prime.
#include<cmath>usingnamespace std;
classSolution {
public:bool isThree(int n) {
int r = sqrt(n);
if (r * r != n) return false;
for (int i =2; i * i <= r; ++i)
if (r % i ==0) return false;
return r >1;
}
};
1
2
3
4
5
6
7
8
9
10
classSolution {
publicbooleanisThree(int n) {
int r = (int)Math.sqrt(n);
if (r * r != n) returnfalse;
if (r < 2) returnfalse;
for (int i = 2; i * i <= r; ++i)
if (r % i == 0) returnfalse;
returntrue;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
import math
classSolution:
defisThree(self, n: int) -> bool:
r = int(math.isqrt(n))
if r * r != n:
returnFalseif r <2:
returnFalsefor i in range(2, int(r **0.5) +1):
if r % i ==0:
returnFalsereturnTrue
1
2
3
4
5
6
7
8
9
10
11
impl Solution {
pubfnis_three(n: i32) -> bool {
let r = (n asf64).sqrt() asi32;
if r * r != n { returnfalse; }
if r <2 { returnfalse; }
for i in2..=((r asf64).sqrt() asi32) {
if r % i ==0 { returnfalse; }
}
true }
}
1
2
3
4
5
6
7
8
9
functionisThree(n: number):boolean {
constr= Math.floor(Math.sqrt(n));
if (r*r!==n) returnfalse;
if (r<2) returnfalse;
for (leti=2; i*i<=r; ++i) {
if (r%i===0) returnfalse;
}
returntrue;
}