Leandro Junes

Prime Counting Function

Compute π(x), the number of primes less than or equal to x.

Inputs

Any integer.

π(x) = #{p ≤ x : p prime}, and π(x) = 0 for x < 2. The count is exact: it is computed by Lehmer's method without listing the primes up to x. Computation runs locally in your browser.

Try

Result

—

π(x) = —

—

To list the primes themselves rather than only count them, use Primes in a Range.

How it works

The prime-counting function π(x) counts the primes p ≤ x. For small x the calculator builds a prime table up to x and reads the answer off it. For larger x it uses Lehmer's algorithm, which combines a partial sieve function φ(x, a) with recursive prime counts, so π(x) is obtained without generating every prime below x. Only what the algorithm needs is generated: the primes up to √x, and a bit-packed π lookup table (up to about x^(2/3), at most 2 × 10⁸) that answers small π(y) instantly.

Write p₁ = 2, p₂ = 3, … and let

a = π(⌊x^(1/4)⌋), b = π(⌊√x⌋), c = π(⌊x^(1/3)⌋), φ(x, a) = #{ m ≤ x : none of p₁, …, p_a divides m }.

Then Lehmer's formula is

π(x) = φ(x, a) + (b + a − 2)(b − a + 1)/2 − Σ_{i=a+1..b} π(x / p_i) − Σ_{i=a+1..c} Σ_{j=i..π(√(x/p_i))} ( π(x / (p_i p_j)) − (j − 1) ),

with every quotient rounded down. φ is evaluated with a lookup table for the first seven primes and the recurrence φ(x, a) = φ(x, a−1) − φ(⌊x/p_a⌋, a−1) beyond that. Everything is exact integer arithmetic. The values π(x/p_i) that fall above the lookup table are counted for i > c in one pass of a segmented sieve up to about x^(2/3), and recursively by the same formula otherwise. Long computations are shared between several background workers, whose partial sums are added at the end. Requests whose predicted work or memory exceeds the calculator's browser limits (currently roughly x ≳ 7 × 10¹⁴) are refused rather than started.