Skip to main content
Back to problems
#1952
Easy Algorithms

Three divisors

Math Enumeration Number Theory
63.9% acceptance
Feb 25, 2026
633
37
Given an integer n, return true if n has exactly 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.

Solution

Rust
Time O(n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn is_three(n: i32) -> bool {
    // n has exactly 3 divisors iff n is the square of a prime
    let sq = (n as f64).sqrt() as i32;
    if sq * sq != n {
      return false;
    }
    if sq < 2 {
      return false;
    }
    for i in 2..=((sq as f64).sqrt() as i32) {
      if sq % i == 0 {
        return false;
      }
    }
    true
  }
}