Three Divisors Problem
#1952
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 1952.
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.
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
Approach: Enumerate Divisors
Every n > 1 has the divisors 1 and n. It has exactly three divisors precisely when there is exactly one more, so we count the divisors i in 2..n-1 and check that the count is 1.
A faster variant scans only i up to sqrt(n) and counts each divisor pair (i, n / i) as two divisors, or as one when i * i == n; the total must be 3.
Complexity: O(n) time for the first version (O(sqrt(n)) for the second) and O(1) space.
class Solution:
def isThree(self, n: int) -> bool:
return sum(n % i == 0 for i in range(2, n)) == 1