1952. Three Divisors LeetCode Solution
In this guide, you will get 1952. Three Divisors LeetCode Solution with the best time and space complexity. The solution to Three Divisors problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.
Table of Contents
- Problem Statement
- Complexity Analysis
- Three Divisors solution in C++
- Three Divisors solution in Java
- Three Divisors solution in Python
- Additional Resources
Problem Statement of Three Divisors
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
Complexity Analysis
- Time Complexity: O(\sqrt[4]{n})
- Space Complexity: O(1)
1952. Three Divisors LeetCode Solution in C++
class Solution {
public:
bool isThree(int n) {
if (n == 1)
return false;
// The numbers with exactly three divisors are perfect squares of a prime
// number.
const int root = sqrt(n);
return root * root == n && isPrime(root);
}
private:
bool isPrime(int num) {
for (int i = 2; i <= sqrt(num); ++i)
if (num % i == 0)
return false;
return true;
}
};
/* code provided by PROGIEZ */
1952. Three Divisors LeetCode Solution in Java
class Solution {
public boolean isThree(int n) {
if (n == 1)
return false;
// The numbers with exactly three divisors are perfect squares of a prime
// number.
final int root = (int) Math.sqrt(n);
return root * root == n && isPrime(root);
}
private boolean isPrime(int num) {
for (int i = 2; i <= Math.sqrt(num); ++i)
if (num % i == 0)
return false;
return true;
}
}
// code provided by PROGIEZ
1952. Three Divisors LeetCode Solution in Python
class Solution:
def isThree(self, n: int) -> bool:
if n == 1:
return False
# The numbers with exactly three divisors are perfect squares of a prime
# number.
root = math.isqrt(n)
return (root**2 == n and
all(root % i != 0
for i in range(2, math.isqrt(root) + 1)))
# code by PROGIEZ
Additional Resources
- Explore all LeetCode problem solutions at Progiez here
- Explore all problems on LeetCode website here
Happy Coding! Keep following PROGIEZ for more updates and solutions.