Check if a number is prime using recursion in JavaScript
Intermediate · 4 min read
A prime number is a whole number above 1 that only divides evenly by 1 and by itself: 2, 3, 5, 7, 11 and so on. Primes are behind the encryption that protects online banking, and checking for one is a favorite exercise for learning loops and, here, recursion.
In this tutorial you will write isPrime(n) as a recursive function, one that calls itself. You will also learn the square-root shortcut that lets it prove 9973 is prime with a few dozen divisions instead of nearly ten thousand. You need to know if, the % operator and what a function is.
Recursion from zero
A recursive function solves a problem by doing one small piece, then calling itself to do the rest. It always needs a base case: a situation where it stops and answers without calling itself again. Here is a countdown:
function countdown(n) {
if (n === 0) return 'liftoff';
return countdown(n - 1);
}
console.log(countdown(3)); // 'liftoff'
countdown(3) calls countdown(2), which calls countdown(1), then countdown(0), which hits the base case and returns.
For primes, the "one small piece" is: try one divisor. If it divides n, stop with false. If not, call yourself with the next divisor.
Why the square root is enough
Factors come in pairs. 36 is 2 × 18, 3 × 12, 4 × 9 and 6 × 6. In every pair, one number is at most 6, the square root of 36. So if a number has any divisor, it has one at or below its square root. Once the divisor squared is bigger than n, there is nothing left to find.
Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.
8 Check a prime number, recursively
fairDecide whether a number is prime, using recursion. A prime is a whole number above 1 with no divisors except 1 and itself.
Stuck? Three hints, smallest first
- 1. Only test divisors up to the square root: a factor above it has a partner below it.
- 2. Carry the current divisor as a parameter with a default, so the caller passes one argument.
- 3. 1 is not prime, 2 is, and every even number above 2 is not.
Step 1: rule out the easy cases
A prime must be a whole number of at least 2. Number.isInteger checks for a whole number:
function isPrimeStart(n) {
if (!Number.isInteger(n) || n < 2) return false;
if (n === 2) return true;
if (n % 2 === 0) return false;
return 'keep checking';
}
console.log(isPrimeStart(1)); // false
console.log(isPrimeStart(7.5)); // false
console.log(isPrimeStart(2)); // true
console.log(isPrimeStart(10)); // false
2 is the only even prime. Every other even number divides by 2, so one line deals with half of all numbers.
Step 2: carry the divisor as a parameter
The recursive call needs to know which divisor to try next. That is extra state, information carried from one call to the next. The neat way to carry it is a parameter with a default value: divisor = 2. The caller writes isPrime(29) and never sees it, while the function's own calls pass a new divisor each time.
function greet(name, greeting = 'Hello') {
return greeting + ', ' + name;
}
console.log(greet('Ada')); // 'Hello, Ada'
console.log(greet('Ada', 'Hi')); // 'Hi, Ada'
Step 3: the recursive check
Now put it together. After the easy cases, there are two base cases and one recursive call:
function isPrime(n, divisor = 2) {
if (!Number.isInteger(n) || n < 2) return false;
if (n === 2) return true;
if (n % 2 === 0) return false;
if (divisor * divisor > n) return true;
if (n % divisor === 0) return false;
return isPrime(n, divisor + (divisor === 2 ? 1 : 2));
}
console.log(isPrime(29)); // true
console.log(isPrime(9)); // false
console.log(isPrime(9973)); // true
Read the last three lines of the function:
divisor * divisor > n: we have passed the square root without finding a divisor, sonis prime.n % divisor === 0: this divisor fits, sonis not prime.- Otherwise, try the next divisor. After 2 it jumps to 3, then goes up by 2 each time (5, 7, 9...), because even divisors can't divide an odd number.
divisor * divisor > n is used instead of divisor > Math.sqrt(n) because it stays in whole numbers and avoids rounding questions with square roots.
Step 4: the numbers that catch people out
console.log(isPrime(25)); // false
console.log(isPrime(49)); // false
console.log(Array.from({ length: 30 }, (_, i) => i).filter((n) => isPrime(n)));
The last line builds the numbers 0 to 29 and keeps the primes: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]. 9, 25 and 49 are squares of odd primes. A version that stops one step too early, or forgets to test odd divisors, wrongly calls them prime. Always test them.
Step 5: a loop does the same job
Recursion is the exercise, but it doesn't make this faster. The same idea as a loop:
function isPrimeLoop(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) if (n % d === 0) return false;
return true;
}
console.log(isPrimeLoop(9973)); // true
Each recursive call takes a little memory until it finishes. For very large numbers that can add up, so the loop is the safer everyday choice.
The full solution
The panel has isPrime, isPrimeLoop and a counting version that records how many divisions it takes to prove 9973 prime. It prints the primes under 30, the results for 9973 and 9975, and that count. Press Run to see how small it is.
/* The divisor is a parameter with a default, which is how a recursive helper
stays a one-argument function to its caller. */
function isPrime(n, divisor = 2) {
if (!Number.isInteger(n) || n < 2) return false; // 0, 1, negatives, decimals
if (n === 2) return true;
if (n % 2 === 0) return false; // every other even number
if (divisor * divisor > n) return true; // no factor found below sqrt(n)
if (n % divisor === 0) return false;
return isPrime(n, divisor + (divisor === 2 ? 1 : 2)); // then only odd divisors
}
// A loop, to show recursion buys nothing here.
function isPrimeLoop(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) if (n % d === 0) return false;
return true;
}
// Count the divisions, to make the square-root limit concrete.
let checks = 0;
function counted(n, d = 3) {
if (n < 2) return false;
if (n % 2 === 0) return n === 2;
checks++;
if (d * d > n) return true;
if (n % d === 0) return false;
return counted(n, d + 2);
}
counted(9973);
const primesUnder30 = Array.from({ length: 30 }, (_, i) => i).filter((n) => isPrime(n));
console.log('primes under 30:', primesUnder30);
console.log('9973 is prime :', isPrime(9973));
console.log('9975 is prime :', isPrime(9975));
console.log('divisions to prove 9973 prime:', checks, '<- not 9971, because of the sqrt limit');
console.log('sqrt(9973) is about', Math.sqrt(9973).toFixed(1));
Output
16 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 16 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('2 is prime', isPrime(2), true);
test('3 is prime', isPrime(3), true);
test('4 is not', isPrime(4), false);
test('1 is not prime', isPrime(1), false);
test('0 is not', isPrime(0), false);
test('a negative number is not', isPrime(-7), false);
test('a decimal is not', isPrime(7.5), false);
test('the primes under 30', primesUnder30, [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]);
test('a large prime', isPrime(9973), true);
test('and a nearby composite', isPrime(9975), false);
test('9 is not prime, which a sloppy version gets wrong', isPrime(9), false);
test('nor is 25', isPrime(25), false);
test('nor 49', isPrime(49), false);
test('the loop version agrees for 0 to 100', Array.from({ length: 101 }, (_, i) => isPrime(i) === isPrimeLoop(i)).every(Boolean), true);
test('the square-root limit keeps the work small', checks < 60, true);
test('far below testing every number up to n', checks < 9973 / 100, true);
Two things make this efficient rather than merely correct. Stopping at divisor * divisor > n works because factors come in pairs: if n = a × b and a is above √n, then b is below it, so you would already have found b. The assertion shows proving 9973 prime takes under 60 divisions instead of nearly ten thousand. And divisor * divisor > n is preferred to divisor > Math.sqrt(n) because it avoids a floating-point square root and any rounding at the boundary.
Passing the divisor as a defaulted parameter is the pattern worth taking from this section: the recursion needs state, the caller should not have to know about it, so give it a default. Note also that recursion buys nothing here — the loop is the same algorithm without the stack frames. The assertions include 9, 25 and 49 because a version that forgets to test odd divisors gets all three wrong.
Common mistakes
- Calling 1 prime. A prime needs exactly two different divisors, and 1 has only one. The
n < 2check handles it. - Testing up to
ninstead of the square root. The answer is still right, but it does far more work than needed. - Using
<where<=belongs. The loop test must bed * d <= n, or 9, 25 and 49 slip through as "prime".
Try it yourself
- Use
isPrimeto list every prime between 100 and 150. - Write
nextPrime(n)that returns the smallest prime bigger thann. - Add a counter to
isPrimeand compare how many calls it makes for 97 and for 9973.