Three Divisors - Problem

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.

Input & Output

Example 1 — Perfect Square of Prime
$ Input: n = 4
Output: true
💡 Note: 4 = 2², and 2 is prime. The divisors of 4 are: 1, 2, 4 (exactly 3 divisors)
Example 2 — Not a Square of Prime
$ Input: n = 6
Output: false
💡 Note: The divisors of 6 are: 1, 2, 3, 6 (4 divisors, not 3)
Example 3 — Another Square of Prime
$ Input: n = 9
Output: true
💡 Note: 9 = 3², and 3 is prime. The divisors of 9 are: 1, 3, 9 (exactly 3 divisors)

Constraints

  • 1 ≤ n ≤ 104

Visualization

Tap to expand
Three Divisors Problem INPUT n = 4 Integer to check Divisors of 4: 1 2 4 Count = 3 divisors 4 = 2 x 2 = 2^2 Perfect square of prime Input: n = 4 ALGORITHM STEPS 1 Calculate sqrt(n) sqrt(4) = 2 2 Check perfect square 2 * 2 = 4 [OK] 3 Check if sqrt is prime Is 2 prime? [OK] 4 Return result Both true --> true Prime Check for 2: Check i from 2 to sqrt(2) sqrt(2) ~ 1.4, so i=2 > 1.4 No divisors found: PRIME FINAL RESULT true n = 4 has exactly 3 divisors Divisors: 1 2 4 1, sqrt(n), n Output: true Key Insight: A number has exactly 3 divisors if and only if it is the square of a prime number. For p^2: divisors are 1, p, and p^2. Check: sqrt(n) must be integer AND prime. O(sqrt(sqrt(n))) time. TutorialsPoint - Three Divisors | Optimized - Check Up to sqrt(n)
Asked in
Google 15 Amazon 12 Microsoft 8
25.0K Views
Medium Frequency
~15 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen