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

1
2
3
Input: n = 2
Output: false
**Explantion:** 2 has only two divisors: 1 and 2.

Example 2

1
2
3
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

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
#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;
    }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
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;
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
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
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
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
    }
}
1
2
3
4
5
6
7
8
9
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)