Counting primes
How many primes are there up to a trillion? Listing them would take 37 billion numbers. Counting them without listing them takes about a second.
Legendre's formula
Let be the number of not divisible by any of the first primes. Removing the multiples of the -th prime from the numbers counted by gives the recurrence
which is inclusion and exclusion, organised. If , the numbers counted are 1 and the primes between and , so .
import { legendrePhi, primePi, meissel } from "@ratmath/numtheory";
legendrePhi(100, 3); // 26n: the n ≤ 100 coprime to 30
legendrePhi(100, 4); // 22n: 1 and the 21 primes from 11 to 97
22n + 4n - 1n; // 25n = π(100)
Meissel's improvement
The recurrence has too many terms when is as large as . Meissel took instead. Then counts 1, the primes between and , and the products of exactly two such primes; no product of three fits below . Hence
The sum needs only up to , which a sieve provides.
meissel(1000);
// { pi: 168n, y: 10n, a: 4n, phi: 228n, P2: 63n }: 228 + 4 − 1 − 63 = 168
meissel(10n ** 6n);
// { pi: 78498n, y: 100n, a: 25n, phi: 120760n, P2: 42286n }
primePi(10n ** 9n); // 50847534n
primePi(10n ** 12n); // 37607912018n, in about a second
primePi sieves below and uses this formula above, up to .
What makes it fast
- A table for the first primes. is periodic in with period , so it is a table lookup, and the recurrence starts at the seventh prime.
- Stopping early. When , the numbers counted by are 1 and primes, so , another lookup.
- A compact sieve. The sieve up to keeps one bit for each odd number and a running count for every 32 bits, so at any costs one addition and one bit count. At that is 6 megabytes.
Lehmer, and later Lagarias, Miller and Odlyzko, pushed the same idea further (more correction terms, and a sieve in place of the recurrence); the record computations of and beyond descend from it. Compare the result with the estimates: , while gives and the logarithmic integral gives , off by 38263.
@ratmath/numtheory and Core's Rational in scope. The last line's value is shown; PRINT(…) adds lines, TEX(…) typesets math.