Skip to content

Algorithms

You don't need a faster computer — you need a better algorithm.

A few years ago I put a tiny experiment on GitHub: larsommen/primes — five different programs that all answer the same dull question, how many prime numbers are there below 100,000? (The answer is 9,592.)

The interesting part isn't the answer. It's how long each program takes to get there — and what actually moves the needle. Spoiler: it isn't threads, and it isn't a faster CPU.

Press the button. Every version below runs right here in your browser, on your machine, timed live.

JavaScript runs on one thread, so V4 (threaded) runs the same code as V3 here — which is exactly the lesson: threading parallelises a slow algorithm, it doesn't fix it. The benchmark runs in a Web Worker, so the page never freezes; any version still grinding after 10 seconds is stopped and marked "gave up" — at 1,000,000 the brute-force versions don't finish, and that's the whole point.

What each version does

The first four are variations on the same idea — take a number, try to divide it — each a little less wasteful than the last:

Check every divisor from 2 up to the number itself, and don't even stop when you've already found one. The simplest thing that works, and by far the slowest.

for (int devider = 2; devider < number; devider++)
    if (number % devider == 0) isPrime = false;   // keeps going anyway

The same loop, but break the moment a divisor is found. One word of code; roughly half the work.

if (number % devider == 0) { isPrime = false; break; }

Two real insights: even numbers above 2 are never prime (skip them), and a factor never exceeds √n (stop there). Now the work per number is tiny.

for (int devider = 3; devider <= Math.sqrt(number); devider += 2)
    if (number % devider == 0) { isPrime = false; break; }

V3, split across threads. It throws more of the machine at the problem — but the algorithm is unchanged, so the win is marginal. More hardware, same idea.

A different idea entirely. Don't test numbers at all. Assume everything is prime, then walk the primes and cross out their multiples. What survives is the set of primes. This is the leap.

for (int number = 2; number < limit; number++)
    if (!composite[number]) {
        totalPrimes++;
        for (int multiple = number * 2; multiple < limit; multiple += number)
            composite[multiple] = true;          // cross it out
    }

The point

V1 → V4 is a story of optimisation: shave a loop, add a break, add threads. Each helps a bit. V5 is a story of a better algorithm — and it leaves all the tuning in the dust on the very same computer.

That's the whole lesson, and it generalises far beyond counting primes:

You don't need a faster computer — you need a better algorithm.

Same sieve, two languages — a million, then ten

The widget stops at a million because brute force never finishes there. The sieve doesn't care. Here is the same sieve written twice — once in Python, once in Rust — counting every prime below 1,000,000, and then every prime below 10,000,000, timed natively (not in a browser).

N Count Median Spread across invocations
1,000,000 Python 3.14.7 78,498 0.873 ms1 0.844 – 0.908 ms (10 invocations)
Rust 1.99.1 (-O) 78,498 0.385 ms 0.369 – 0.453 ms (14)
10,000,000 Python 3.14.7 664,579 9.718 ms1 9.417 – 10.151 ms (6)
Rust 1.99.1 (-O) 664,579 4.654 ms 4.602 – 4.896 ms (6)

Both languages print 78,498 and 664,579, the known counts of primes below one million and below ten million, so the answer is checked, not assumed.

Ten times as many numbers costs about eleven to twelve times the time — 11.1× for Python, 12.1× for Rust. That is the shape you want from a sieve: near-linear, no cliff. And the absolute numbers stay unremarkable: ten million numbers, sieved in under a hundredth of a second — in both languages, interpreted one included, at a size where the brute force in the widget above would still be grinding.

Rust is 2.27× faster at a million and 2.09× at ten million, so the gap narrows as the problem grows. That is the opposite of the usual story about interpreted languages, and it falls out of where the work is: the sieve doing the crossing-out, not the language running the loop.

Why a range, and not five numbers

An earlier version of this table listed the five runs of one invocation. At a million that was false precision — a single invocation of the Rust build lands anywhere between 0.37 and 0.45 ms, so whichever one you quote sets the last digit, and the headline ratio with it. Every median above is taken across independent invocations of the program, with the first run of a freshly-compiled binary thrown away.2

These numbers moved since this page first went up

Rust used to read 0.34 ms at a million here, for 2.6×. Both programs now take N as a command-line argument instead of baking it in, and giving up that compile-time constant costs Rust about 14%: 0.339 ms with const LIMIT against 0.385 ms with a runtime limit, built from the same source and raced head-to-head in one session, with the two ranges not even overlapping. Python never had a compile-time constant to lose and is unchanged. The table above is one build throughout — the old 0.34 ms belongs to a different program, so it is not mixed in.

The algorithm

An odd-only sieve of Eratosthenes, the standard best choice at this size:

  1. Even numbers above 2 are never prime, so don't store them. One flag per odd number: index k stands for the number 2k + 3. That halves the memory and the work, and 2 is simply counted separately.
  2. For each odd i from 3 while i × i ≤ N: if i is still unmarked it is prime — cross out its multiples, starting at i × i (smaller multiples were already crossed out by smaller primes), stepping by 2i in value space, which is a step of i in index space.
  3. The count is 1 (for the prime 2) plus the flags still unmarked.

The bound in step 2 is ≤, not <. With N hardcoded at an even million you can write < and never notice, but the moment N comes from the command line the difference is reachable: at N = 25 a < bound never uses 5 as a marker, leaves 25 standing, and answers 10 instead of 9.

Python gets close to Rust here for a specific reason: the crossing-out is a single bytearray slice assignment, which runs in C. The interpreter issues one slice operation per odd prime up to √N — 167 of them at a million, 445 at ten million — instead of looping over each of the millions of individual flag writes itself. That is also the likely reason the gap narrows: Python's interpreted outer loop grows only as √N, while the crossing-out that comes to dominate at ten million is already running at full speed.

How it was run

Limits primes strictly below 1,000,000 (the default) and below 10,000,000
Machine Apple M4 Pro, macOS (arm64)
Python python3 sieve.py and python3 sieve.py 10000000 (3.14.7, no third-party packages)
Rust rustc -O sieve.rs -o sieve, then ./sieve and ./sieve 10000000 (1.99.1, optimised build — without -O the comparison would be meaningless)
What is timed only the mark-and-count, measured inside the program (time.perf_counter / Instant); interpreter start-up and allocating the flag array are outside the timer
Runs 5 in one process with the flags reset between them, repeated over several independent invocations; the table gives the median across all of them, plus the full spread
Memory one byte per odd number — 488 KiB at a million, 4.8 MiB at ten million
Measured 2026-10-26
Raw output — one invocation of each, verbatim

These are single invocations, so each median below differs a little from the pooled figure in the table. That difference is exactly why the table pools.

$ python3 sieve.py
count: 78498
run 1: 0.970 ms
run 2: 0.872 ms
run 3: 0.867 ms
run 4: 0.867 ms
run 5: 0.909 ms
median: 0.872 ms

$ ./sieve
count: 78498
run 1: 0.413 ms
run 2: 0.481 ms
run 3: 0.409 ms
run 4: 0.453 ms
run 5: 0.454 ms
median: 0.453 ms          # the slow end of the spread — see the note above

$ python3 sieve.py 10000000
count: 664579
run 1: 13.178 ms          # warm-up
run 2: 10.260 ms
run 3: 9.624 ms
run 4: 9.587 ms
run 5: 10.151 ms
median: 10.151 ms

$ ./sieve 10000000
count: 664579
run 1: 4.950 ms
run 2: 4.602 ms
run 3: 4.565 ms
run 4: 4.571 ms
run 5: 4.724 ms
median: 4.602 ms
import statistics
import sys
import time


def parse_limit(argv: list[str]) -> int:
    if len(argv) > 1:
        print("usage: sieve.py [LIMIT]", file=sys.stderr)
        sys.exit(2)
    if len(argv) == 0:
        return 1_000_000
    try:
        limit = int(argv[0])
    except ValueError:
        print(f"LIMIT must be an integer, got {argv[0]!r}", file=sys.stderr)
        sys.exit(2)
    if limit < 3:
        print(f"LIMIT must be >= 3, got {limit}", file=sys.stderr)
        sys.exit(2)
    return limit


LIMIT = parse_limit(sys.argv[1:])

# Allocate flags for odd numbers 3, 5, 7, ..., LIMIT-1.
# Index k represents the number 2*k+3, so index 0 → 3.
# (1 is excluded entirely; 2 is counted separately.)
size = (LIMIT - 3) // 2 + 1
flags = bytearray(size)  # 0 = prime candidate, 1 = composite


def sieve() -> int:
    # Times only the mark-and-count; allocation is outside.
    flags[:] = bytes(size)  # reset
    i = 3
    while i * i <= LIMIT:
        k = (i - 3) // 2
        if flags[k] == 0:
            start = (i * i - 3) // 2
            n = len(flags[start::i])
            flags[start::i] = b"\x01" * n
        i += 2
    return 1 + flags.count(0)  # 1 for the prime 2


timings = []
count = None
for _ in range(5):
    t0 = time.perf_counter()
    count = sieve()
    t1 = time.perf_counter()
    timings.append((t1 - t0) * 1000)

print(f"count: {count}")
for n, ms in enumerate(timings, 1):
    print(f"run {n}: {ms:.3f} ms")
print(f"median: {statistics.median(timings):.3f} ms")
fn parse_limit(args: &[String]) -> usize {
    if args.len() > 1 {
        eprintln!("usage: sieve [LIMIT]");
        std::process::exit(2);
    }
    if args.is_empty() {
        return 1_000_000;
    }
    let limit: usize = match args[0].parse() {
        Ok(n) => n,
        Err(_) => {
            eprintln!("LIMIT must be an integer, got {:?}", args[0]);
            std::process::exit(2);
        }
    };
    if limit < 3 {
        eprintln!("LIMIT must be >= 3, got {}", limit);
        std::process::exit(2);
    }
    limit
}

fn sieve(flags: &mut [u8], limit: usize) -> usize {
    // Times only the mark-and-count; allocation is outside.
    flags.fill(0); // reset
    let mut i = 3;
    while i * i <= limit {
        let k = (i - 3) / 2;
        if flags[k] == 0 {
            let start = (i * i - 3) / 2;
            let mut j = start;
            while j < flags.len() {
                flags[j] = 1;
                j += i; // step i in index space == 2*i in value space
            }
        }
        i += 2;
    }
    1 + flags.iter().filter(|&&f| f == 0).count() // 1 for the prime 2
}

fn main() {
    let args: Vec<String> = std::env::args().skip(1).collect();
    let limit = parse_limit(&args);

    // Allocate flags for odd numbers 3, 5, 7, ..., limit-1.
    // Index k represents the number 2*k+3, so index 0 → 3.
    // (1 is excluded entirely; 2 is counted separately.)
    let size = (limit - 3) / 2 + 1;
    let mut flags = vec![0u8; size];

    let mut timings = [0.0f64; 5];
    let mut count = 0usize;
    for ms in timings.iter_mut() {
        let t0 = std::time::Instant::now();
        count = sieve(&mut flags, limit);
        *ms = t0.elapsed().as_secs_f64() * 1000.0;
    }

    println!("count: {count}");
    for (n, ms) in timings.iter().enumerate() {
        println!("run {}: {:.3} ms", n + 1, ms);
    }
    let mut sorted = timings;
    sorted.sort_by(|a, b| a.partial_cmp(b).unwrap());
    println!("median: {:.3} ms", sorted[2]);
}

Not a browser measurement

The live widget above runs JavaScript on your machine. The rows in the table were run on the author's machine, so compare them with each other, not with your widget numbers.

Code: github.com/larsommen/primes.


  1. One asymmetry, disclosed rather than hidden: Python's reset between runs (flags[:] = bytes(size)) allocates a fresh buffer inside the timed region, where Rust's fill(0) writes in place. Measured on its own it costs 0.018 ms at a million and 0.155 ms at ten million — 2.1% and 1.6% of Python's time, so it grows in absolute terms but shrinks as a share. Removing it entirely would move the ten-million ratio from 2.09× to 2.06×. ↩↩

  2. The first execution of a newly compiled binary reads badly high on this machine — 17.997 ms at ten million, against a true ~4.65 ms. It settles from the second run onwards. One measurement of a fresh binary would have put a number nearly four times too slow on this page. ↩