Leetcode Problem 1952: Three Divisors
Given an integer n, return true if n has exactly three positive divisors. Otherwise, return false.
Q: What is the range of the input integer n?
A: You can assume that n is a positive integer within the range [1, 10^4].
Q: Can n be a composite number?
A: Yes, n can be any number within the given range, including prime and composite numbers.
Q: Should we handle negative numbers or zero?
A: No, n is assumed to be a positive integer.
To determine if a number n has exactly three divisors, we can make use of the following mathematical insight:
A number n has exactly three divisors if and only if it is the square of a prime number.
n = p^2 where p is a prime number, the divisors of n will be: 1, p, and p^2.Given this, we can follow these steps:
n. Let’s call it sqrtN.sqrtN * sqrtN equals n. If not, n cannot have exactly three divisors.sqrtN is a prime number. If sqrtN is prime, then n has exactly three divisors.Here is the C++ implementation:
#include <cmath>
class Solution {
public:
bool isThree(int n) {
// Step 1: Calculate the integer square root of n
int sqrtN = static_cast<int>(sqrt(n));
// Step 2: Check if square of sqrtN equals n
if (sqrtN * sqrtN != n) {
return false;
}
// Step 3: Check if sqrtN is a prime number
return isPrime(sqrtN);
}
private:
bool isPrime(int num) {
if (num <= 1) return false;
if (num == 2 || num == 3) return true;
if (num % 2 == 0 || num % 3 == 0) return false;
for (int i = 5; i * i <= num; i += 6) {
if (num % i == 0 || num % (i + 2) == 0) {
return false;
}
}
return true;
}
};
O(1) because sqrt is a mathematical function that operates in constant time.n): This is also a constant time operation, O(1).O(sqrt(n)) because the loop runs up to sqrt(n).So the overall time complexity is O(sqrt(n)). Given the constraints (n up to 10,000), this is efficient and should perform well within the given limits.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?