Check if a number is prime in JavaScript
Intermediate · 3 min read
A prime number is a whole number above 1 that can only be divided evenly by 1 and itself. 7 is prime. 8 is not, because 8 = 2 × 4. Primes are behind the encryption that keeps online banking safe, and checking for them is one of the best small exercises for learning how to make a loop do less work.
In this tutorial you will write isPrime(n), which returns true or false. You will start with a version that works but is slow, then cut the work down in two steps. You need to know what a function, an if statement and a for loop are, and how the remainder operator % works (10 % 3 is 1, the amount left over).
What "divides evenly" means in code
n % d === 0 asks "does d divide n with nothing left over?". If any number other than 1 and n does, n is not prime. Such a number is called a factor.
console.log(91 % 7); // 0, so 7 is a factor of 91
console.log(97 % 7); // 6, so 7 is not a factor of 97
Why the square root is enough
Factors come in pairs. 36 = 1 × 36 = 2 × 18 = 3 × 12 = 4 × 9 = 6 × 6. In each pair, one number is at or below 6, the square root of 36, and the other is at or above it. So if a number has any factor, it has one at or below its square root. You never need to search past that point.
For 97 that means checking up to about 9.8 instead of up to 96.
Here is the exercise. Try it yourself first if you like, or follow the steps below.
16 Is a number prime?
fairDecide whether a whole number is prime, without checking every number below it.
Stuck? Three hints, smallest first
- 1. You only need to test divisors up to the square root. A factor above it pairs with one below it.
- 2. Handle 0, 1 and 2 before the loop; 1 is not prime and 2 is the only even prime.
- 3. After 2, skip all the even numbers and step by 2.
Step 1: the slow but simple version
Try every number from 2 up to n - 1. If any divides evenly, it isn't prime.
function isPrime(n) {
for (let d = 2; d < n; d++) {
if (n % d === 0) return false;
}
return true;
}
console.log(isPrime(7)); // true
console.log(isPrime(91)); // false
console.log(isPrime(1)); // true, but 1 is NOT prime
The first two are right. 1 is wrong: the loop never runs, so the function falls through to true. 0 and negative numbers have the same problem.
Step 2: handle the small cases first
Deal with the edge cases before the loop. Numbers below 2 are never prime, and neither are decimals. Number.isInteger checks for a whole number.
function isPrime(n) {
if (!Number.isInteger(n) || n < 2) return false;
for (let d = 2; d < n; d++) {
if (n % d === 0) return false;
}
return true;
}
console.log(isPrime(1)); // false
console.log(isPrime(0)); // false
console.log(isPrime(-7)); // false
console.log(isPrime(2.5)); // false
Step 3: stop at the square root
Change the loop's limit from n to Math.sqrt(n). Note it is <=, not <, so that a perfect square like 49 still tests 7.
function isPrime(n) {
if (!Number.isInteger(n) || n < 2) return false;
const limit = Math.sqrt(n);
for (let d = 2; d <= limit; d++) {
if (n % d === 0) return false;
}
return true;
}
console.log(isPrime(49)); // false
console.log(isPrime(97)); // true
The limit is worked out once, before the loop, so it isn't recalculated on every pass.
Step 4: skip the even numbers
2 is the only even prime. Every other even number divides by 2. So check 2 on its own, rule out the other even numbers, and then the loop only needs odd divisors: start at 3 and step by 2.
function isPrime(n) {
if (!Number.isInteger(n) || n < 2) return false;
if (n === 2) return true;
if (n % 2 === 0) return false;
const limit = Math.sqrt(n);
for (let d = 3; d <= limit; d += 2) {
if (n % d === 0) return false;
}
return true;
}
d += 2 adds 2 each time, so d goes 3, 5, 7, 9 and so on. That halves the work again.
Step 5: test it
List every prime up to 30, and check the one that looks prime but isn't:
const upTo30 = [];
for (let n = 0; n <= 30; n++) if (isPrime(n)) upTo30.push(n);
console.log(upTo30.join(', ')); // 2, 3, 5, 7, 11, 13, 17, 19, 23, 29
console.log(isPrime(91)); // false
console.log(Math.sqrt(91).toFixed(2)); // 9.54
91 is 7 × 13. The square root is about 9.54, and 7 is below that, so the loop finds it at the third try (3, 5, then 7).
The full solution
The complete answer is the Step 4 function. It prints the primes up to 30, checks 97 and 91, and shows the square root of 91. Press Run to see it.
function isPrime(n) {
if (!Number.isInteger(n) || n < 2) return false; // 0, 1 and negatives are not prime
if (n === 2) return true;
if (n % 2 === 0) return false; // every other even number is out
// Only up to the square root: any factor above it has a partner below it.
const limit = Math.sqrt(n);
for (let d = 3; d <= limit; d += 2) {
if (n % d === 0) return false;
}
return true;
}
const upTo30 = [];
for (let n = 0; n <= 30; n++) if (isPrime(n)) upTo30.push(n);
console.log('primes to 30:', upTo30.join(', '));
console.log('97 prime?', isPrime(97));
console.log('91 prime?', isPrime(91), '(7 x 13)');
// Why the square root is enough: 91's factors are 7 and 13, and 7 < sqrt(91) < 13.
console.log('sqrt(91) is about', Math.sqrt(91).toFixed(2));
Output
8 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 8 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', upTo30, [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]);
test('1 is not prime', isPrime(1), false);
test('0 is not prime', isPrime(0), false);
test('2 is prime', isPrime(2), true);
test('a larger prime', isPrime(97), true);
test('91 is not, despite looking it', isPrime(91), false);
test('negatives are not prime', isPrime(-7), false);
test('fractions are not prime', isPrime(2.5), false);
Stopping at the square root is the whole optimisation, and the reason is worth internalising: if n = a * b then one of a and b is at or below √n. For 91 that is 7, comfortably below 9.54, so the loop finds it. Checking to n instead would do the same work for no benefit.
Common mistakes
- Saying 1 is prime. A prime needs exactly two different factors, and 1 has only one. Handle numbers below 2 before the loop.
- Using
d < limitinstead ofd <= limit. Square numbers like 9, 25 and 49 then slip through as "prime". - Starting the odd loop at 1. Every number divides by 1, so every odd number would be rejected.
Try it yourself
- Write
primesUpTo(max)that returns an array of all the primes up tomax. - Write
nextPrime(n)that returns the first prime greater thann. - Count how many times the loop runs for 97 in Step 1 and in Step 4. How much work did the changes save?