Skip to content
Ayotl

← Algorithms · Lesson 11/11

The sieve of Eratosthenes

✕
1/12

Primes, and the slow way to find them

A number is prime if it divides evenly only by 1 and by itself: 2, 3, 5, 7, 11, 13… 1 doesn't count as prime. The others, like 4, 6, 9 or 91, are composite: they can be written as a product (91 = 7 × 13).

The direct way to tell whether k is prime is to try divisors: 2, 3, 4… Going up to √k is enough, because if k = a × b, one of the two is no bigger than √k (if both were, the product would be bigger than k). But to find all the primes up to n you have to run that test on every number, and every try is a division.

leccion.js

$ node leccion.js

Press RUN (or Ctrl+Enter).

What to look at

  • Up to 30 there are 10 primes, found with 45 divisions.
  • d * d <= k is a way of saying "up to √k" without taking square roots.
The whole lesson on one page

Primes, and the slow way to find them

A number is prime if it divides evenly only by 1 and by itself: 2, 3, 5, 7, 11, 13… 1 doesn't count as prime. The others, like 4, 6, 9 or 91, are composite: they can be written as a product (91 = 7 × 13).

The direct way to tell whether k is prime is to try divisors: 2, 3, 4… Going up to √k is enough, because if k = a × b, one of the two is no bigger than √k (if both were, the product would be bigger than k). But to find all the primes up to n you have to run that test on every number, and every try is a division.

let divisiones = 0;   // divisions

// is k prime? Try divisors up to √k
function esPrimo(k) {
  if (k < 2) return false;
  for (let d = 2; d * d <= k; d++) {
    divisiones++;
    if (k % d === 0) return false;
  }
  return true;
}

const primos = [];   // primes
for (let k = 1; k <= 30; k++) if (esPrimo(k)) primos.push(k);
console.log(primos.join(" "));
console.log("divisions:", divisiones);
console.log("is 91 prime?", esPrimo(91), "| 97?", esPrimo(97));
  • Up to 30 there are 10 primes, found with 45 divisions.
  • d * d <= k is a way of saying "up to √k" without taking square roots.

The sieve: crossing out the multiples

The sieve doesn't try divisors: it crosses out. Line up the numbers from 2 to n, none crossed out, and go through them in order:

  • If the number is already crossed out, it's composite: skip it (continue).
  • If not, no smaller prime divides it (otherwise it would have crossed it out): it's prime. Keep it and cross out its multiples, counting by p.

There isn't a single division: only additions (m += p). This is the code from the video; tachado means crossed out and primos, primes. tachado starts empty: tachado[p] is undefined until someone crosses it out, and in the if that counts as false.

It's credited to Eratosthenes of Cyrene, the Greek mathematician of the 3rd century BC who worked out the size of the Earth. The oldest description that survives is by Nicomachus of Gerasa, around the year 100, who credits it to him.

  • p the 25 primes up to 100, ten per row (1, at the top left, doesn't count)
  • x the crossed-out ones: the composites
function criba(n) {
  const tachado = [], primos = [];
  for (let p = 2; p <= n; p++) {
    if (tachado[p]) continue;
    primos.push(p);
    for (let m = p*p; m <= n; m += p)
      tachado[m] = true;
  }
  return primos;
}

const primos = criba(100);
console.log(primos.join(" "));
console.log(primos.length, "primes up to 100");
  • There are 25, from 2 to 97: the green ones in the drawing.
  • Change 100 to 1000: you get 168.

Why start at p²?

When 7's turn comes, 14, 21, 28, 35 and 42 are already crossed out: they're 7 × 2, 7 × 3, 7 × 4, 7 × 5 and 7 × 6, and each one has a factor smaller than 7 that already had its turn. The first one no smaller prime could cross out is 7 × 7 = 49. That's why the inner for starts at p*p.

A number can be crossed out more than once (12 gets crossed out by 2 and by 3), and that's fine: tachado[m] = true again. The program counts how many times something gets crossed out when you start at 2 * p and when you start at p * p.

// the sieve, counting; `desde(p)` says where each prime starts crossing out
function contar(n, desde) {
  const tachado = [];
  let primos = 0, tachadas = 0;
  for (let p = 2; p <= n; p++) {
    if (tachado[p]) continue;
    primos++;
    for (let m = desde(p); m <= n; m += p) {
      tachado[m] = true;
      tachadas++;
    }
  }
  return primos + " primes, " + tachadas + " crossed out";
}

for (const n of [100, 10000]) {
  console.log("up to", n, "| from 2p:", contar(n, (p) => 2 * p));
  console.log("up to", n, "| from p²:", contar(n, (p) => p * p));
}
  • Up to 100: 146 crossings against 104, and the same 25 primes.
  • Up to 10,000: 23,071 against 16,981. Starting at p² saves work without changing the result.

Going up to √n is enough

With n = 100, after 7 comes 11, and 11 × 11 = 121 is already past 100: the inner for doesn't run even once, not for 11 nor for any prime after it. Everything left uncrossed is prime.

The reason is the same as in the divisor test: a composite up to n has a factor no bigger than √n, and that factor has already had its turn. In the video's code the outer for goes all the way to n because it's also the one that collects the primes; if you only wanted to cross out, p * p <= n would be enough.

The program looks, among the composites up to n, for the one whose smallest prime factor is the biggest of all.

// the smallest prime that divides k
const menor = (k) => { for (let d = 2; ; d++) if (k % d === 0) return d; };

for (const n of [100, 1000]) {
  let mayor = 0, quien = 0;
  for (let k = 4; k <= n; k++) {
    const d = menor(k);
    if (d !== k && d > mayor) { mayor = d; quien = k; }   // d === k: k is prime
  }
  console.log("up to", n, "| biggest smallest factor:", mayor, "(in " + quien + ") | root:", Math.sqrt(n).toFixed(1));
}
  • Up to 100 it's 49 = 7 × 7: no composite needs a factor bigger than 10.
  • Up to 1000 it's 961 = 31 × 31, and √1000 ≈ 31.6. It's always the square of the last prime whose square doesn't go past n.

How much work? O(n log log n)

Each prime p crosses out about n / p numbers, so the total is around n/2 + n/3 + n/5 + n/7 + … That sum of the reciprocals of the primes grows very slowly, like log log n: up to a million, the sieve crosses out about 2 times per number. It's O(n log log n), almost linear: almost like just counting.

The divisor test, on the other hand, does more and more work per number. What the sieve spends is memory: one slot per number. To reach the billions it's done in chunks (the segmented sieve).

// how many times the sieve crosses out
function tachadas(n) {
  const tachado = [];
  let cuenta = 0;
  for (let p = 2; p <= n; p++) {
    if (tachado[p]) continue;
    for (let m = p * p; m <= n; m += p) { tachado[m] = true; cuenta++; }
  }
  return cuenta;
}

// how many divisions the divisor test makes on every number
function divisiones(n) {
  let cuenta = 0;
  for (let k = 2; k <= n; k++)
    for (let d = 2; d * d <= k; d++) { cuenta++; if (k % d === 0) break; }
  return cuenta;
}

for (const n of [100, 1000, 10000, 100000]) {
  const t = tachadas(n);
  console.log("n =", n, "| crossed out:", t, "(" + (t / n).toFixed(2) + " per number) | divisions:", divisiones(n));
}
  • Up to 100,000: 193,078 crossings (1.93 per number) against 2,745,694 divisions.
  • Crossings per number barely grow (1.04, 1.41, 1.70, 1.93); divisions per number go from 2 to 27.

Practice with a video challenge

Further reading