The Meissel–Lehmer algorithm (after Ernst Meissel and Derrick Henry Lehmer) is an algorithm that computes the prime-counting function.[1][2]
Description
The key identity
Given
, one may define the following functions: Firstly,
![{\displaystyle \varphi (x,a):=\left|\left([1,x]\cap \mathbb {N} \right)\setminus \bigcup _{j=1}^{a}p_{j}\mathbb {Z} \right|;}](/media/api/rest_v1/media/math/render/svg/7a18372065f5c4395c53d435012552624e938b62)
this function measures the set
(closed interval) when one has sieved out multiples of the first
primes
(including these primes themselves); that is,
is the sequence of prime numbers in increasing order.
We may further split that up with the functions
![{\displaystyle P_{k}(x,a):=\left|\left[\left([1,x]\cap \mathbb {N} \right)\setminus \bigcup _{j=1}^{a}p_{j}\mathbb {Z} \right]\cap \{n\mid n{\text{ has exactly }}k{\text{ prime factors}}\}\right|,}](/media/api/rest_v1/media/math/render/svg/9a0fefb3f39250a6bf252ec1a2cc96b2f92448ff)
these measure the set
but considers only the numbers that have exactly
prime factors (this is well-defined by the fundamental theorem of arithmetic). With these, we have

the sum on the right is finite, since numbers
have, for instance,
prime factors.
The identities

prove that one may compute
by computing
and
,
. And this is what the Meissel–Lehmer algorithm does.
For
, we get the following formula for
:

For
, there is a similar expansion.[2]
Expanding ϕ(x, a)
Using the formula

may be expanded. Each summand, in turn, may be expanded in the same way, so that a very large alternating sum arises.
Combining the terms
The only thing that remains to be done is evaluating
and
for certain values of
and
. This can be done by direct sieving and using the above formulas.
A modern variant
Jeffrey Lagarias, Victor Miller and Andrew Odlyzko crafted a realisation of this algorithm which computes
in time
and space
for any
.[1] Upon setting
, the tree of
has
leaf nodes.[1]
References