Prime test by trial division in JavaScript
Intermediate · 4 min read
A prime number is a whole number greater than 1 that only divides evenly by 1 and by itself. 7 is prime. 9 isn't, because 3 times 3 is 9. Primes are the building blocks of every whole number, and they sit underneath the encryption that protects online payments, hash tables and many puzzle questions.
In this tutorial you will write isPrime(n) using trial division: try dividing n by smaller numbers and see if any of them fit. The clever part is knowing when to stop. You will see why testing up to the square root of n is enough, and count how much work that saves for 9973. You need to know %, for loops and Number.isInteger.
Why the square root is far enough
Divisors come in pairs. If 36 divides by 4, then it also divides by 9, because 4 times 9 is 36. In every pair, one number is at most the square root and the other is at least the square root. For 36 the root is 6, and the pairs are 1 and 36, 2 and 18, 3 and 12, 4 and 9, and 6 and 6.
So if nothing up to the square root divides n, nothing above it can either, because its partner would have been found already. That turns a long search into a short one.
Here is the exercise. Try it yourself first if you like, then read on and we will build it together.
31 Primality by trial division, and why the root is far enough
fairWrite isPrime(n) that stops testing divisors at the square root of n. Then count the divisions it performs for 9973, and compare that with testing every divisor up to n - 1.
Stuck? Three hints, smallest first
- 1. Deal with
n < 2and with2itself first, then test only odd divisors. - 2. If
n = a * bwitha <= b, thenacannot be larger than the root — so a divisor above the root always has a partner below it. - 3. Write the loop condition as
d * d <= n, notd <= Math.sqrt(n): it stays in integers and computes no roots.
Step 1: the slow version
The first idea most people have: try every divisor from 2 up to n - 1. This counter records how many divisions it takes:
const workIfNaive = (n) => {
let c = 0;
for (let d = 2; d < n; d++) {
c++;
if (n % d === 0) break;
}
return c;
};
console.log(workIfNaive(9973)); // 9971
9973 is prime, so the loop never finds a divisor and runs all the way to the end: 9971 divisions to say "yes".
Step 2: the small cases
Before any loop, deal with the inputs that don't need one:
function isPrimeStart(n) {
if (!Number.isInteger(n) || n < 2) return false;
if (n % 2 === 0) return n === 2;
return true; // the loop goes here next
}
console.log(isPrimeStart(1), isPrimeStart(2), isPrimeStart(4), isPrimeStart(2.5)); // false true false false
Numbers below 2 aren't prime, and nor is a fraction. The Number.isInteger guard matters: without it, a loop on 2.5 would never find an exact divisor and would call 2.5 prime. Then evens: 2 is prime, and every other even number divides by 2, so it isn't. That leaves only odd numbers for the loop.
Step 3: odd divisors up to the root
Start at 3 and step by 2, so only odd divisors are tried. Stop when d * d passes n:
let divisions = 0;
function isPrime(n) {
if (!Number.isInteger(n) || n < 2) return false;
if (n % 2 === 0) return n === 2;
for (let d = 3; d * d <= n; d += 2) {
divisions++;
if (n % d === 0) return false;
}
return true;
}
d * d <= n means the same as "d is at most the square root of n", but it never computes a root. It stays in whole numbers, so there is no rounding to worry about. The divisions counter is only there so we can measure the work.
Step 4: test it
const primesBelow30 = [];
for (let n = 0; n < 30; n++) if (isPrime(n)) primesBelow30.push(n);
console.log(primesBelow30); // [ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29 ]
console.log(isPrime(7919)); // true
Those are the ten primes below 30, and 7919 is the thousandth prime.
Step 5: measure the saving
Reset the counter, then test 9973:
divisions = 0;
console.log(isPrime(9973)); // true
console.log(divisions); // 49
The square root of 9973 is about 99.9, and there are 49 odd numbers from 3 to 99. So the loop did 49 divisions where the slow version did 9971. That is more than 200 times less work, and the gap grows with every extra digit.
Step 6: the square that tests the bound
9409 is 97 times 97. Its only divisor (apart from 1 and itself) sits exactly on the square root:
divisions = 0;
console.log(isPrime(9409)); // false
console.log(divisions); // 48
The loop reaches 97 after 48 tries and finds it. This is why the condition is <= and not <: with d * d < n, the loop would stop before trying 97 and wrongly call 9409 prime.
The full solution
The answer panel builds isPrime with its counter, lists the primes below 30, and measures 9973 and 9409 against the slow version. The checks underneath confirm the edge cases and the counts: 49 divisions for 9973, 48 for 9409, and 9971 the slow way. Press Run to see the output.
let divisions = 0; // a counter, so the saving is measurable
function isPrime(n) {
if (!Number.isInteger(n) || n < 2) return false;
if (n % 2 === 0) return n === 2; // 2 is prime, other evens are not
for (let d = 3; d * d <= n; d += 2) {
divisions++;
if (n % d === 0) return false;
}
return true;
}
// The same question answered without the shortcut: every divisor up to n - 1.
const workIfNaive = (n) => {
let c = 0;
for (let d = 2; d < n; d++) {
c++;
if (n % d === 0) break;
}
return c;
};
const primesBelow30 = [];
for (let n = 0; n < 30; n++) if (isPrime(n)) primesBelow30.push(n);
divisions = 0;
const prime9973 = isPrime(9973);
const workToRoot = divisions;
divisions = 0;
const composite9409 = isPrime(9409); // 97 * 97, so the only divisor sits on the root
const workTo9409 = divisions;
const oddsBelowRoot = (Math.floor(Math.sqrt(9973)) - 3) / 2 + 1;
console.log('primes below 30 :', primesBelow30);
console.log('9973 is prime :', prime9973, 'after', workToRoot, 'divisions');
console.log('sqrt(9973) :', Math.sqrt(9973));
console.log('9409 is prime :', composite9409, 'settled after', workTo9409, 'divisions');
console.log('to n - 1 instead:', workIfNaive(9973), 'divisions');
Output
9 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 9 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('the primes below 30', primesBelow30, [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]);
test('0, 1, a negative and a fraction are not prime', [0, 1, -7, 2.5].map(isPrime), [false, false, false, false]);
test('2 is, and it is the only even one', [isPrime(2), isPrime(4)], [true, false]);
test('7919, the thousandth prime', isPrime(7919), true);
test('9409 is 97 squared, so it is composite', [composite9409, 9409 % 97], [false, 0]);
test('and it took 48 divisions to notice, one per odd number up to 97', workTo9409, 48);
test('a prime uses the whole range: one per odd number below its root', [workToRoot, oddsBelowRoot], [49, 49]);
test('testing every divisor up to n - 1 costs 9971 instead', workIfNaive(9973), 9971);
test('so stopping at the root cut the work by more than 200 times', workIfNaive(9973) / workToRoot > 200, true);
The root bound is not a heuristic, it is a proof. Divisors come in pairs whose product is n, and in every pair one member is at most sqrt(n). So if nothing at or below the root divides n, nothing above it can either. That turns a linear scan into a sqrt(n) one: 49 divisions instead of 9971 for a five-figure number, and the gap widens with every digit.
Two details worth copying. d * d <= n beats d <= Math.sqrt(n) because it never leaves the integers, so there is no rounding to reason about — and 9409 is the case that would catch you, since its only divisor is the root and a root computed slightly low would skip it. And the Number.isInteger guard matters: without it isPrime(2.5) would run a loop that never divides evenly and confidently report a fractional prime.
Common mistakes
- Looping all the way to
n - 1. It works, but a five-digit prime takes thousands of divisions instead of dozens. - Writing
d * d < n. Perfect squares of a prime, like 9409 or 25, slip through as "prime". Use<=. - Forgetting the small cases. 0, 1, negatives and fractions aren't prime, and 2 is the only even prime.
Try it yourself
- Use
isPrimeto list all the primes between 100 and 150. - Count the divisions for 104729, the ten-thousandth prime. Compare it with its square root.
- Find the first number above 1000 that is prime.