Sub topic 9
How Common Are Primes? The Prime Number Theorem
This chapter assumes you can write and run the sieve of Eratosthenes from the earlier chapters, read simple Python, and know that math.log is the natural logarithm. Earlier chapters showed that primes never run out. This chapter asks how many primes there are below a given number. The answer matters in practice. It tells you how big an output array to allocate and how many primes a sieve will produce. In the next chapter it also explains why the sieve's running time has a log log n factor.
Counting Primes: the Function π(n)
Mathematicians write π(n) for the number of primes less than or equal to n. This π is a function name and has nothing to do with 3.14159. Some values:
| n | π(n) | Fraction of numbers up to n that are prime |
|---|---|---|
| 10 | 4 | 40% |
| 100 | 25 | 25% |
| 1,000 | 168 | 16.8% |
| 10,000 | 1,229 | 12.3% |
| 100,000 | 9,592 | 9.6% |
| 1,000,000 | 78,498 | 7.8% |
| 10,000,000 | 664,579 | 6.6% |
The fraction keeps falling, but slowly. Multiplying n by 10 removes only a small, almost constant amount from the percentage. That pattern suggests a logarithm.
The Prime Number Theorem
The prime number theorem (PNT) states that
π(n) ~ n / ln n
The symbol ~ means asymptotically equivalent: the ratio π(n) / (n / ln n) tends to 1 as n grows. Hadamard and de la Vallée Poussin proved it independently in 1896, about a century after Gauss and Legendre guessed it from tables like the one above.
There is a more intuitive way to say the same thing. Near a large number x, roughly one number in every ln x is prime. Equivalently, the average gap between consecutive primes near x is about ln x.
| Near x | ln x | Typical gap between primes |
|---|---|---|
| 1,000 | 6.9 | about 7 |
| 1,000,000 | 13.8 | about 14 |
| 10^9 | 20.7 | about 21 |
| 10^18 | 41.4 | about 41 |
Multiplying x by a million only triples the typical gap. This is why primes stay easy to find even among very large numbers. Cryptographic key generation depends on it. To find a 1024-bit prime you test random odd candidates, and since ln(2^1024) ≈ 710, about one odd candidate in 355 is prime.
Better Approximations
n / ln n is the simplest form of the theorem, but its estimates are poor. At n = 10^6 it gives 72,382, which is about 8% below the true 78,498. Two refinements do much better.
| Approximation | Formula | Estimate at n = 10^6 | Error |
|---|---|---|---|
| Simple PNT | n / ln n | 72,382 | −7.8% |
| Legendre-style correction | n / (ln n − 1) | 78,030 | −0.6% |
| Logarithmic integral | li(n) = ∫₀ⁿ dt / ln t | 78,628 | +0.17% |
The logarithmic integral li(n) is the most accurate of the three. It follows directly from the density idea. If the chance that t is prime is about 1 / ln t, then adding up those chances from 2 to n gives the expected count, and the integral is the continuous form of that sum. All three formulas are asymptotically equivalent to π(n), but they approach it at very different speeds.
Seeing the Convergence
The ratio π(n) / (n / ln n) climbs above 1 and then sinks back toward 1 very slowly.
At this pace the ratio is still about 1.05 at 10^10. The theorem holds, but n / ln n only becomes accurate at sizes far beyond anything you will sieve.
Checking It Yourself
The program below sieves once up to 10^7, counts primes at each power of ten, and prints the count next to all three approximations. It computes li(x) with the series li(x) = γ + ln ln x + Σ (ln x)^k / (k · k!), where γ ≈ 0.5772 is the Euler–Mascheroni constant. This sieve uses a bytearray and slice assignment, so it is a faster form of the list-based sieve from earlier chapters. It runs in about a second and uses about 10 MB of memory.
import math
def prime_flags(n):
"""Return a bytearray where flags[i] == 1 exactly when i is prime."""
flags = bytearray([1]) * (n + 1)
flags[0] = flags[1] = 0
p = 2
while p * p <= n:
if flags[p]:
flags[p * p :: p] = bytes(len(range(p * p, n + 1, p)))
p += 1
return flags
def li(x, terms=100):
"""Logarithmic integral via its convergent series."""
gamma = 0.5772156649015329
L = math.log(x)
total = gamma + math.log(L)
term = 1.0
for k in range(1, terms + 1):
term *= L / k # term is now L**k / k!
total += term / k
return total
LIMIT = 10**7
flags = prime_flags(LIMIT)
print(f"{'n':>10} {'pi(n)':>9} {'n/ln n':>10} {'n/(ln n-1)':>11} {'li(n)':>10} {'ratio':>6}")
for e in range(1, 8):
n = 10**e
count = sum(flags[: n + 1])
simple = n / math.log(n)
better = n / (math.log(n) - 1)
print(f"{n:>10} {count:>9} {simple:>10.0f} {better:>11.0f} {li(n):>10.0f} {count / simple:>6.3f}")You should see the exact counts from the first table. The n / ln n column stays several percent low. The n / (ln n − 1) column is within about 1% from 10^3 upward. The li(n) column runs slightly high, by about 0.05% at 10^7.
Using Density Estimates in Code
The theorem gives estimates, and code usually needs guarantees. Number theorists have proved explicit bounds that hold for every n, not only in the limit. Two of them, both due to Rosser and Schoenfeld, are useful in programs:
- π(x) < 1.25506 · x / ln x for all x > 1. Use this to size an output array of primes up to x.
- pk < k (ln k + ln ln k) for k ≥ 6, where pk is the k-th prime. Use this to choose how far to sieve when you need the first k primes.
The second bound solves a common task: "return the 10,000th prime." Without it you would have to guess a sieve limit and retry if the guess was too small.
import math
def prime_flags(n):
flags = bytearray([1]) * (n + 1)
flags[0] = flags[1] = 0
p = 2
while p * p <= n:
if flags[p]:
flags[p * p :: p] = bytes(len(range(p * p, n + 1, p)))
p += 1
return flags
def nth_prime(k):
"""Return the k-th prime (1-indexed), sieving only as far as needed."""
if k < 1:
raise ValueError("k must be at least 1")
if k < 6:
return [2, 3, 5, 7, 11][k - 1]
limit = int(k * (math.log(k) + math.log(math.log(k)))) + 1
flags = prime_flags(limit)
seen = 0
for i, flag in enumerate(flags):
if flag:
seen += 1
if seen == k:
return i
raise AssertionError("bound was too small; this should never happen")
print(nth_prime(1)) # 2
print(nth_prime(6)) # 13
print(nth_prime(10000)) # 104729For k = 10,000 the bound is about 114,307. The 10,000th prime is 104,729, so the sieve does under 10% extra work, and the code never needs a retry loop.
A Preview: Density and Sieve Cost
The sieve crosses out multiples of each prime p, which costs about n / p operations per prime. The total work is therefore n times the sum of 1/p over primes p ≤ √n. Because primes thin out at the rate 1 / ln x, that sum grows like ln ln n. This result is Mertens' second theorem: Σ 1/p ≈ ln ln n + 0.2615. The next chapter turns this into the O(n log log n) running time. For now, note that the sum is small only because the primes are sparse. If the primes had positive density, the sum would grow like ln n.
Common Errors
- Using log base 10 or base 2. The theorem uses the natural logarithm. In Python that is
math.log(x)with one argument.math.log10(10**6)gives 6, not 13.8, and the estimate comes out more than twice too large. - Sizing arrays with n / ln n. For every x ≥ 17, π(x) > x / ln x. An array sized by the simple estimate will always be too small. Use the 1.25506 bound, or a Python list that grows as needed.
- Treating ratio convergence as small error. As the callout above explains, the absolute error grows without bound. An estimate within 1% of 10^9 is still off by hundreds of thousands of primes.
- Assuming li(n) always overestimates. li(n) > π(n) holds for every n anyone has checked. Littlewood proved in 1914 that the inequality reverses infinitely often, but the first reversal is somewhere far beyond 10^19. Never rely on li(n) as a proven upper bound.
- Expecting regular gaps. ln x is the average gap. Real gaps vary widely. Twin primes such as 1,000,037 and 1,000,039 differ by 2. Near 10^6 there are also gaps of more than 100, roughly ten times the average.
Exercise
Estimate π(10^9) with n / ln n and with n / (ln n − 1), given ln(10^9) ≈ 20.723. The true value is 50,847,534. Compute the percentage error of each estimate.
Show answer
n / ln n = 10^9 / 20.723 ≈ 48,255,000, which is about 5.1% low. n / (ln n − 1) = 10^9 / 19.723 ≈ 50,702,000, which is about 0.29% low. The corrected formula is roughly 18 times more accurate at this size.
Exercise
About how many primes would you expect between 1,000,000 and 1,001,000? Write code that uses prime_flags to check your estimate.
Show answer
The density near 10^6 is about 1 / ln(10^6) ≈ 1 / 13.8, so expect about 1000 / 13.8 ≈ 72 primes. To check, run flags = primeflags(1001000) and print(sum(flags[1000001:1001_001])). The real count will be close to 72 but not exactly 72, because the density is only an average and the count varies from one window to the next.
Exercise
A colleague allocates an array of length int(n / math.log(n)) to hold every prime up to n and fills it as the sieve finds primes. Why does this fail for every n ≥ 17, and what length should they use?
Show answer
For every x ≥ 17, π(x) > x / ln x, so the array is always too short and the code will overflow it or raise an IndexError. Use the proven bound int(1.25506 * n / math.log(n)) + 1, which holds for all n > 1. Alternatively, append to a Python list and let it grow.