Three Divisors
EasyUpdated: Aug 2, 2025
Practice on:
Problem
Given an integer n, return true ifn _hasexactly three positive divisors. Otherwise, return _false.
An integer m is a divisor of n if there exists an integer k such that n = k * m.
Examples
Example 1
Input: n = 2
Output: false
**Explantion:** 2 has only two divisors: 1 and 2.
Example 2
Input: n = 4
Output: true
**Explantion:** 4 has three divisors: 1, 2, and 4.
Constraints
1 <= n <= 10^4
Solution
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.
Code
C++
#include <cmath>
using namespace std;
class Solution {
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;
}
};
Java
class Solution {
public boolean isThree(int n) {
int r = (int)Math.sqrt(n);
if (r * r != n) return false;
if (r < 2) return false;
for (int i = 2; i * i <= r; ++i)
if (r % i == 0) return false;
return true;
}
}
Python
import math
class Solution:
def isThree(self, n: int) -> bool:
r = int(math.isqrt(n))
if r * r != n:
return False
if r < 2:
return False
for i in range(2, int(r ** 0.5) + 1):
if r % i == 0:
return False
return True
Rust
impl Solution {
pub fn is_three(n: i32) -> bool {
let r = (n as f64).sqrt() as i32;
if r * r != n { return false; }
if r < 2 { return false; }
for i in 2..=((r as f64).sqrt() as i32) {
if r % i == 0 { return false; }
}
true
}
}
TypeScript
function isThree(n: number): boolean {
const r = Math.floor(Math.sqrt(n));
if (r * r !== n) return false;
if (r < 2) return false;
for (let i = 2; i * i <= r; ++i) {
if (r % i === 0) return false;
}
return true;
}
Complexity
- ⏰ Time complexity:
O(√n) - 🧺 Space complexity:
O(1)