20. Check Whether a Number Is Prime
Determine whether a given integer is a prime number.
How It Works & Algorithmic Design
A prime number greater than 1 has exactly two positive divisors: 1 and itself.
- Numbers less than
2are not prime. - Try dividing the number by integers starting from
2. - Only test divisors up to the square root of the number.
- If any divisor divides evenly, the number is not prime.
- Otherwise, it is prime.
Why This Approach Works Best
If a number has a factor larger than its square root, the corresponding paired factor must be smaller than the square root. Therefore checking up to sqrt(n) is sufficient. The time complexity is $O(\sqrt n)$ and space is $O(1)$.
Example Walkthrough
29
29 is greater than 1 and needs to be tested for divisors.
29 % 2 != 0 | 29 % 3 != 0 | 29 % 4 != 0 | 29 % 5 != 0
Testing only up to sqrt(29), approximately 5.38, is sufficient.
true
No divisor was found, so 29 is prime.
Answer: Check for prime number
function isPrime(n) {
if (n < 2) return false;
for (let i = 2; i * i <= n; i++) {
if (n % i === 0) return false;
}
return true;
}Test possible divisors only up to the square root of the number.
Numbers below 2 are not prime.
Checking divisors only up to the square root is sufficient.
The optimized trial-division approach runs in O(√n) time and O(1) space.