December 5, 2026

Sieve of Eratosthenes in Python: 5.76 Million Primes in 1.6 Seconds

A parchment grid with most squares crossed out in ink

Finding every prime below 20,000 by checking each number against every smaller number took a plain Python loop about 1.08 seconds. Finding every prime below 100 million, a range 5,000 times larger, took a sieve about 1.6 seconds. The sieve is more than 2,000 years old and does no division at all. It crosses out multiples, and what survives is prime. Timing four versions of the job, from the most naive to a vectorized sieve, shows where the speed comes from, and counting what the sieve finds puts a 230-year-old guess about prime numbers to a direct test.

Video: Khan Academy Labs on YouTube

The ancient method

Who it’s named for

The MacTutor History of Mathematics archive’s biography of Eratosthenes says he was born in Cyrene, in what is now Libya, and became the third librarian at Alexandria. He is also known for a surprisingly accurate measurement of the Earth’s circumference. The sieve bears his name; MacTutor notes that it appears in a later Greek text, the Introduction to Arithmetic, and that it remains useful in number theory today.

How it works

Write down every number from 2 to n. The first number, 2, is prime; cross out every multiple of 2 after it. The next number not crossed out, 3, is prime; cross out its multiples. Continue with 5, then 7, and so on. Every number still standing is prime, because if it had a smaller factor, it would have been crossed out as a multiple of that factor.

Two shortcuts

Crossing out for a prime p can start at p², because every smaller multiple of p has a smaller prime factor and has already been crossed out. And the process can stop once p passes the square root of n: any composite number up to n has a factor no larger than its square root.

Flour being sifted through a fine sieve

Four ways to find primes, timed

The contestants

The first method tests each number against every smaller number. The second, trial division, tests each number only against the primes found so far, and only up to its square root. The third is the sieve in pure Python, using a byte array. The fourth is the same sieve using NumPy, which crosses out each prime’s multiples in a single vectorized step instead of a Python loop.

Results on one cloud server

Limit Primes found Naive check Trial division Sieve, pure Python Sieve, NumPy
1,000 168 0.0028 s
20,000 2,262 1.08 s
10,000 1,229 0.0037 s 0.00040 s 0.000028 s
100,000 9,592 0.047 s 0.0030 s 0.00016 s
1,000,000 78,498 0.81 s 0.029 s 0.0018 s
10,000,000 664,579 0.38 s 0.046 s
100,000,000 5,761,455 1.6 s

How the gaps grow

The naive check is hopeless: going from 1,000 to 20,000, a 20-fold increase in range, took nearly 400 times as long. Trial division is far better but still slows down faster than the range grows. At one million, the pure Python sieve was 28 times faster than trial division, and the NumPy sieve another 16 times faster than that. Every method found the same primes in every range it covered, which serves as a check.

Why the sieve is fast

Counting the work

A script counted every cross-out the sieve makes. Up to 10,000 it crossed out 16,981 entries, about 1.7 per number. Up to one million, 2,122,048, about 2.1 per number. Up to ten million, 22,850,051, about 2.3 per number. The work per number creeps up very slowly.

The growth rate

That slow creep matches the standard result that the sieve’s total work grows like n times the logarithm of the logarithm of n, a function that barely moves: for n = 10 million, ln(ln n) is only about 2.8. In practice the sieve does a nearly constant amount of work per number, while trial division’s work per number keeps growing with the square root.

No division

The sieve never divides. Crossing out multiples of p means stepping through memory p places at a time, which a computer does far faster than computing remainders. That also explains why NumPy helps so much here: stepping through an array is exactly the operation vectorized code is built for.

A computer motherboard up close

Where the sieve hits a wall

Memory

The sieve has to hold the whole range at once. NumPy’s boolean array uses one byte per number, so the run to 100 million used about 100 megabytes. Going to 10 billion that way would take about 10 gigabytes.

The fixes

Two standard improvements reduce that. Storing one bit per number instead of one byte cuts memory by a factor of eight, and skipping even numbers halves it again. A segmented sieve goes further by processing the range in blocks that fit in the processor’s cache, keeping only the primes up to the square root of n in memory between blocks. Those versions are how large prime tables are actually built.

Both fixes, measured

Two of those improvements were added to the NumPy script and timed. Storing only odd numbers cut the array for 100 million to 50 megabytes and the run time from 1.6 seconds to 0.35, since half the work, crossing out even numbers, simply vanished. A segmented version then sieved the odd numbers in blocks of about 4.2 million at a time, keeping only the primes up to the square root of the limit between blocks. It counted the primes below 100 million in 0.27 seconds and the primes below one billion, all 50,847,534 of them, in 3.3 seconds, never holding more than a few megabytes of sieve in memory at once. The plain version would have needed a gigabyte for the same job. Ten times the range took about twelve times as long, close to the near-linear growth the cross-out count predicted.

When not to sieve

To test whether a single large number is prime, a sieve is the wrong tool; it would have to build a table of every number below it. Probabilistic tests check one number quickly without listing anything. The sieve is for finding all the primes in a range.

Testing the prime number theorem

The prediction

Wolfram MathWorld’s entry on the prime number theorem states that the number of primes up to n, written π(n), is asymptotically n/ln n. It says Carl Friedrich Gauss proposed this in 1792, at age 15, and that Jacques Hadamard and Charles-Jean de la Vallée Poussin independently proved it in 1896. MathWorld also notes that the logarithmic integral, Li(n), is a better approximation.

The count

n Primes up to n (sieve) n / ln n Ratio Li(n) Li error
1,000 168 145 1.161
1,000,000 78,498 72,382 1.085 78,627 +129
10,000,000 664,579 620,421 1.071 664,918 +339
100,000,000 5,761,455 5,428,681 1.061 5,762,209 +754

What the table shows

The ratio of the true count to n/ln n shrinks from 1.16 at a thousand to 1.06 at 100 million, closing in on 1 as the theorem promises, but very slowly. Li(n) is far closer: off by 754 out of nearly 5.8 million at the top of the range, an error of about 0.013 percent. Throughout this range, n/ln n undercounts the primes and Li(n) slightly overcounts them, so the true count sits between the two, much closer to Li.

Ancient ruins with stone columns

Running it yourself

The core

The NumPy version is short. Make a boolean array of length n + 1, all true. Set positions 0 and 1 to false. For every i from 2 up to the square root of n, if position i is still true, set every position from i² onward in steps of i to false. The indices still true are the primes.

The classic bug

One small slip trips up many first attempts. Writing the outer loop as range(2, int(n ** 0.5)) stops one short of the square root, so when the limit is itself a prime squared, that square never gets crossed out. With n = 49, the loop stops at 6, the multiples of 7 are never marked, and 49 is reported as prime. Adding 1 to the upper bound fixes it.

A reasonable next step

From there, small changes make it faster or bigger: skip the even numbers, pack eight numbers into a byte, or process blocks at a time. Each is a few more lines. The method stays the same one Eratosthenes is credited with, crossing out multiples until only primes are left, and on modern hardware it gets through millions of numbers per second in a language not known for speed.

Sources

  • MacTutor History of Mathematics, University of St Andrews, “Eratosthenes of Cyrene”: https://mathshistory.st-andrews.ac.uk/Biographies/Eratosthenes/
  • Wolfram MathWorld, “Prime Number Theorem”: https://mathworld.wolfram.com/PrimeNumberTheorem.html

719 Posts

Peter Kalafatis writes and edits X9M8. He holds a bachelor's degree from LIU Post and a master's in Media Studies from The New School, with academic work in the philosophy of science, human behavior, AI, and memetics.

View All Posts

Leave a Reply

Your email address will not be published. Required fields are marked *