Skip to the workspace
Pebellslearn by building
Number Theory for Algorithms  ›  Lesson

Eratosthenes and the Linear Sieve

Sieves 26 minStrike multiples instead of testing numbers, and give every composite exactly one owner

dsa / Eratosthenes and the Linear Sieve

Explore each scene at your own pace.

01 · Picking a bucket count that resists clustering

Picking a bucket count that resists clustering

Eratosthenes and the Linear Sieve

Definition
A sieve finds every prime up to n by crossing out the multiples of each prime found so far, so whatever is never crossed out must be prime. The linear sieve crosses out each composite number exactly once, giving O(n) time.
In plain words
Write the numbers in a grid, circle 2 and rub out every second number after it, then circle 3 and rub out every third, and so on. The numbers still standing at the end are the primes, and nobody had to test them one by one.

In short: to find every prime up to n, don't test each number on its own — strike out multiples instead. Starting from each prime p, cross off p·p, p·p+p, p·p+2p, … up to n; anything never crossed off is prime. That's the Sieve of Eratosthenes, and it costs O(n log log n). A sharper version, the linear sieve, strikes every composite exactly once — each composite is crossed off only by its smallest prime factor — and costs O(n). Quarry's hash kernel needs this: prime bucket counts, prime moduli and quick factorisation all start with "which numbers up to n are prime".

A hand-drawn 12-wide grid of numbers with three colours of crossed-out multiples fanning out from 2, 3 and 5, and the surviving primes circled

Picking a bucket count that resists clustering

Quarry's hash table spreads keys across capacity buckets with hash(key) % capacity. Pick capacity = 100 and every key that's a multiple of 10 — user ids 10, 20, 30, … — lands in buckets 0, 20, 40, …: a fifth of the buckets, used by everything. A prime capacity breaks that pattern, because a prime shares no common factor with any key except 1.

python

97 keys hashed into a 97-bucket table land in 97 different buckets, no matter what the key pattern is — because 97 has no factor in common with 10. Pick table sizes from a prime list, not round numbers.

Scene 1 of 9
Project context and further resources
You're building a piece ofQuarry — the hash kernel
This piece — primes_up_to(): Every prime up to n, fast enough to pick a bucket count or a modulus at startup.
Scenario Quarry's hash kernel needs a table of small primes to pick bucket counts from, and it needs to build that table fast enough to run at startup, not just once offline.
primes_up_to.py
Call the function you wrote — just like your app's frontend would. Edit the inputs and hit Call.
primes_up_to(n) → listEvery prime <= n, in increasing order.
try:
returned
Press Run to execute your code.
Press Check to run the tests for this lesson.
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.