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 <= 104
When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
To find if a number has exactly three divisors, we will check all the numbers smaller than it to see if they divide it evenly. We simply count how many divisors we find using this method.
Here's how the algorithm would work step-by-step:
def has_three_divisors_brute_force(number):
divisor_count = 0
for possible_divisor in range(1, number + 1):
# Check divisibility for each number
if number % possible_divisor == 0:
divisor_count += 1
# Exactly three divisors indicate a square of a prime
if divisor_count == 3:
return True
else:
return False
The key insight is that a number has exactly three divisors if and only if it's the square of a prime number. Instead of checking all divisors, we'll focus on identifying if the given number is a perfect square of a prime.
Here's how the algorithm would work step-by-step:
def three_divisors(number_to_check):
square_root = number_to_check**0.5
# If not a perfect square, it can't be square of an int.
if square_root != int(square_root):
return False
square_root = int(square_root)
# Need to verify if the square root is a prime number
for i in range(2, int(square_root**0.5) + 1):
if square_root % i == 0:
return False
# 2 is a prime number, ensure it handles edge case
if square_root <= 1:
return False
return True
Case | How to Handle |
---|---|
n is less than 1 | Return false because numbers less than 1 cannot have divisors in the positive domain. |
n is 1 | Return false because 1 only has one divisor (itself). |
n is a prime number | Return false because a prime number has exactly two divisors: 1 and itself. |
n is a perfect square of a prime number (e.g., 4, 9, 25) | Return true since a perfect square of a prime number has exactly three divisors (1, the prime number, and the number itself). |
n is a large number (e.g., close to the maximum integer value) | Ensure that the loop calculating divisors doesn't cause integer overflow; consider using long or long long if necessary. |
n is a composite number that is not a perfect square of a prime (e.g., 6, 8, 10) | Return false since these numbers will have more than three divisors. |
Integer overflow during divisor calculation for very large n | Use appropriate data types (long or long long) to prevent overflow when calculating divisors. |
Efficiency for very large n - can we optimize? | Optimize by only iterating up to the square root of n when finding divisors. |