Emmanuel Akinfulubi

JavaScriptBasic

Sieve of Eratosthenes in JavaScript

Intermediate · 4 min read

A prime number is a whole number above 1 that only divides evenly by 1 and itself: 2, 3, 5, 7, 11 and so on. If you want every prime up to some limit, testing each number one by one repeats the same divisions over and over. More than two thousand years ago, the Greek mathematician Eratosthenes described a faster way: write all the numbers down, then cross out the ones that can't be prime.

In this tutorial you will write sieve(limit), which lists every prime up to a limit using that crossing-out method. You'll also see two small tricks that save a lot of wasted work. You need to know arrays and for loops, including loops that count up in steps other than 1.

The idea on paper

Write the numbers 2 to 30. Then:

  1. 2 isn't crossed out, so it's prime. Cross out every multiple of 2 after it: 4, 6, 8...
  2. The next number not crossed out is 3, so it's prime. Cross out its multiples: 6, 9, 12...
  3. 4 is already crossed out, so skip it. 5 is next: cross out 10, 15, 20...
  4. Keep going. Whatever is left uncrossed at the end is prime.

You never divide anything. You only count up in steps.

Flags in an array

In code, "crossed out" is a flag. Make an array with one slot per number, all true ("might be prime"), and set a slot to false to cross it out. The slot's index is the number:

JavaScript

const prime = new Array(11).fill(true);
prime[0] = false;
prime[1] = false;
console.log(prime.length); // 11: slots 0 to 10
console.log(prime[7]);     // true

0 and 1 aren't prime, so they're crossed out before we start.

Here is the exercise. Try it on your own first if you like, or read on and we will build it together.

136 Every prime up to a limit, by crossing out

fair

List all the primes up to a limit. Instead of testing each number on its own, keep a list of flags and cross out the multiples of each prime you find. Start crossing out at the square of the prime and stop when the prime's square passes the limit.

Stuck? Three hints, smallest first
  1. 1. An array of true, one slot per number, with 0 and 1 set false to begin.
  2. 2. When you reach a number still marked true, it is prime; walk its multiples and mark them false.
  3. 3. Its multiples below p squared were already crossed out by a smaller prime, so start at p * p.

Step 1: cross out multiples

Step 1

function sieve(limit) {
  const prime = new Array(limit + 1).fill(true);
  prime[0] = false;
  prime[1] = false;
  for (let p = 2; p <= limit; p++) {
    if (!prime[p]) continue;                      // already crossed out
    for (let m = 2 * p; m <= limit; m += p) prime[m] = false;
  }
  const out = [];
  for (let n = 2; n <= limit; n++) if (prime[n]) out.push(n);
  return out;
}
console.log(sieve(30).join(' ')); // 2 3 5 7 11 13 17 19 23 29

The outer loop visits each number. If it's still true, it's prime, and the inner loop crosses out 2p, 3p, 4p and so on by adding p each time. continue skips to the next number when the current one is already crossed out.

At the end we collect every index still marked true. This works. But it does more work than it needs to.

Step 2: start crossing out at p × p

When we reach 5, its multiples 10, 15 and 20 have already been crossed out by 2 and 3. In general, every multiple of p below p * p has a smaller factor, so it's already gone. The first new one is p * p, which is 25 for 5.

Let's count the crossings with each starting point:

Step 2

function crossings(limit, startAtSquare) {
  const prime = new Array(limit + 1).fill(true);
  let count = 0;
  for (let p = 2; p <= limit; p++) {
    if (!prime[p]) continue;
    for (let m = startAtSquare ? p * p : 2 * p; m <= limit; m += p) {
      prime[m] = false;
      count++;
    }
  }
  return count;
}
console.log(crossings(100, false)); // 146
console.log(crossings(100, true));  // 104

Starting at p * p cuts the crossings up to 100 from 146 to 104, and the list of primes doesn't change.

Step 3: stop at the square root

If p * p is already bigger than the limit, the inner loop has nothing to cross out. So the outer loop can stop as soon as p * p > limit. For a limit of 100, that's after 7, because 11 × 11 is 121.

Step 3

function sieve(limit) {
  if (limit < 2) return { primes: [], crossings: 0 };
  const prime = new Array(limit + 1).fill(true);
  prime[0] = false;
  prime[1] = false;
  let crossings = 0;
  for (let p = 2; p * p <= limit; p++) {
    if (!prime[p]) continue;
    for (let m = p * p; m <= limit; m += p) {
      prime[m] = false;
      crossings++;
    }
  }
  const out = [];
  for (let n = 2; n <= limit; n++) if (prime[n]) out.push(n);
  return { primes: out, crossings };
}
const hundred = sieve(100);
console.log(hundred.primes.length, hundred.primes[hundred.primes.length - 1]); // 25 97
console.log(hundred.crossings);           // 104
console.log(sieve(1000).primes.length);   // 168
console.log(sieve(1).primes, sieve(-5).primes); // [] []

Only 2, 3, 5 and 7 ever run the inner loop for a limit of 100. Numbers like 11 and 13 are still found, because the final collecting loop goes all the way to the limit.

The guard at the top handles limits below 2. Without it, new Array(-5 + 1) would throw an error, because an array can't have a negative length.

There are 74 non-primes from 2 to 100, but 104 crossings. That's because a number like 12 gets crossed out by both 2 and 3. That's fine: crossing out twice is harmless.

Step 4: check it against the slow way

A good habit with a clever algorithm is to compare it with a simple one:

Step 4

const isPrime = (n) => {
  if (n < 2) return false;
  for (let d = 2; d * d <= n; d++) if (n % d === 0) return false;
  return true;
};
const slow = Array.from({ length: 101 }, (_, n) => n).filter(isPrime);
console.log(slow.length); // 25

isPrime tests one number by trying divisors. Filtering 0 to 100 with it gives the same 25 primes. The sieve wins when you want all the primes in a range. Its cost is memory: one slot for every number up to the limit. For a single number, isPrime is the better tool.

The full solution

The answer panel has the finished sieve, which returns the primes and the crossing count, and the one-at-a-time isPrime for comparison. It prints the primes up to 100 and the crossings used. Press Run to see the output.

The answer

function sieve(limit) {
  if (limit < 2) return { primes: [], crossings: 0 };
  const prime = new Array(limit + 1).fill(true);
  prime[0] = false;
  prime[1] = false;

  let crossings = 0;
  for (let p = 2; p * p <= limit; p++) {
    if (!prime[p]) continue;                       // already crossed out, so not prime
    for (let m = p * p; m <= limit; m += p) {      // p*2 .. p*(p-1) are already gone
      prime[m] = false;
      crossings++;
    }
  }

  const out = [];
  for (let n = 2; n <= limit; n++) if (prime[n]) out.push(n);
  return { primes: out, crossings };
}

// The one-at-a-time version, for comparison.
const isPrime = (n) => {
  if (n < 2) return false;
  for (let d = 2; d * d <= n; d++) if (n % d === 0) return false;
  return true;
};

const hundred = sieve(100);
console.log('primes to 100:', hundred.primes.join(' '));
console.log('crossings used:', hundred.crossings);

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.

9 checks

test('the primes under thirty', sieve(30).primes, [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]);
test('there are 25 up to a hundred, and 97 is the last', [hundred.primes.length, hundred.primes[hundred.primes.length - 1]], [25, 97]);
test('and 168 up to a thousand', sieve(1000).primes.length, 168);
test('1 is not prime and 2 is', [sieve(1).primes, sieve(2).primes], [[], [2]]);
test('a limit below two has no primes at all rather than throwing', [sieve(0).primes, sieve(-5).primes], [[], []]);
test('it agrees with testing every number one at a time', sieve(100).primes, Array.from({ length: 101 }, (_, n) => n).filter(isPrime));
test('crossing out from p squared still catches every composite', hundred.primes.filter((n) => n % 2 === 0), [2]);
test('74 composites took 104 crossings, so 30 were crossed twice', [99 - hundred.primes.length, hundred.crossings], [74, 104]);
test('and only four primes ever ran the inner loop, because 11 squared is past 100', [Math.floor(Math.sqrt(100)), sieve(100).primes.filter((p) => p * p <= 100)], [10, [2, 3, 5, 7]]);

The sieve inverts the question. Trial division asks "is this number prime" once per number and redoes the same divisions over and over; the sieve asks "what is definitely not prime" and crosses composites off in one pass. For a range, that is much less work — and the crossings count makes it concrete.

Two bounds are doing the optimising, and both are easy to get wrong. The outer loop runs while p * p <= limit, because any composite up to the limit has a factor at or below its square root, so nothing above that can cross out anything new — for a limit of 100 only 2, 3, 5 and 7 ever run the inner loop. The inner loop starts at p * p rather than 2 * p, because every multiple of p below p² has a smaller prime factor and was already crossed out; starting at 2 * p still gives the right answer, just with more wasted writes. Wasted writes do not disappear either way: 74 composites take 104 crossings here, because a number with several prime factors gets crossed out once per factor.

The cost is memory: an array the size of the limit. That is fine for a hundred thousand and wrong for a trillion, which is the honest trade — trial division is O(1) space and answers about one number, the sieve is O(n) space and answers about a range. Pick by the question you are actually asking.

Common mistakes

  • Making the array limit long instead of limit + 1. The index is the number, so you need a slot for the limit itself.
  • Forgetting to cross out 0 and 1. They'd be collected as primes.
  • Stopping the outer loop early and the collecting loop too. Only the crossing-out stops at the square root. Collecting must go to the limit.

Try it yourself

  1. Change sieve to return just the count of primes up to a limit, and find how many there are up to 10,000.
  2. Use the sieve to find all twin primes up to 100: pairs like 11 and 13 that differ by 2.
  3. Store the smallest prime factor in each slot instead of true/false, then use it to break 360 into primes.

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.