Primality test by trial division
Easy TimeO(√n) SpaceO(1)
A prime is a whole number above 1 whose only divisors are 1 and itself, so 97 is prime and 91 is not — 91 = 7 × 13. Given an integer n, return true when n is prime and false when it is not. 1 and everything below it are not prime, and 2 is the only even number that is.
Examples
Example 1
- Input
- n = 97
- Output
- Nothing between 2 and 96 divides 97 exactly.
true
Example 2
- Input
- n = 91
- Output
false7 × 13 = 91, so 7 divides it and the answer isfalse.
The Code
function isPrime(n) {
if (n < 2) return false;
if (n % 2 === 0) return n === 2;
for (let d = 3; d * d <= n; d += 2) {
if (n % d === 0) return false;
}
return true;
}
isPrime(97);Done
More like this
All math & numbers examples (8) →- Prime sieve Cross out every multiple; whatever survives is prime.
- Happy number Sum the squared digits until you reach 1 — or start repeating.
- Roman → integer Subtract when a smaller symbol sits before a bigger one.
- Integer → Roman Greedily take the largest symbol that still fits.
- Collatz Halve it if even, triple-plus-one if odd — always reaches 1.
- Newton’s sqrt Average your guess with n over your guess; it converges fast.