Mathematical trolling: the Willans prime formula
It has long been of interest to study any regularity in the prime numbers, a question which can be phrased as: “Is there a formula for the
This ridiculous expression, which we’ll understand better below, is indeed a “formula” for the
-
What is an Answer? by Herbert S. Wilf (May 1982):
sometimes […] we may feel that the disease was preferable to the cure. […] is unacceptable in polite society as an answer, despite its elegant appearance, because it is just a restatement of the question, and it does not give us a tool for calculating f(n) that we didn’t have before.
-
Formulas for Primes by Underwood Dudley (January 1983):
The conclusion to be drawn from all this, I think, is that formulas for formulas' sake do not advance the mathematical enterprise. Formulas should be useful. If not, they should be astounding, elegant, enlightening, simple, or have some other redeeming value. […] Even as in business and marriage, in mathematics not all that is true needs to be published.
Nevertheless, the formula is surprising at first glance and can be interesting to understand: it is mentioned on Wikipedia and there’s an excellent YouTube video about it.
It is based on a bunch of tricks, and the video does a good job of explaining them from the bottom up, so as a complement, let’s do it top-down.
The nth prime in terms of the prime-counting function
Let
Then, we can write an expression (circular definition) for
With the additional knowledge that
Next, we can write
Putting these together (and
The prime-counting function
We can represent “is an integer” with this trick:
And with that, we’re done!
Summary
Thus, Willans’s formula is “merely” a clever putting together of these tricks:
- The
th prime number is guaranteed to be at most - it is the smallest number with
primes less than it - Wilson’s theorem
In programming terms, it is like starting with the following naive and inefficient function for returning the
def nth_prime(n):
num_primes_seen = 0
for i in range(1, 2**n):
# TODO: implement is_prime, returning 0 or 1
num_primes_seen += is_prime(i)
if num_primes_seen >= n:
return i
and making it less efficient, by recomputing num_primes_seen
(the number of primes is_prime(i)
:
def nth_prime(n):
for i in range(1, 2**n):
# count = 1 + pi(n) = 1 + (number of primes <= i)
count = sum((math.factorial(j - 1) + 1) % j == 0
for j in range(1, i + 1))
if count > n:
return i
and making it even worse by always running the loop up to
def nth_prime(n):
p = 1
for i in range(1, 2**n):
count = sum((math.factorial(j - 1) + 1) % j == 0
for j in range(1, i + 1))
p += (count <= n)
return p
This (absurdly inefficient) program is now in a form amenable to “encoding” using formula tricks, and that is precisely what the Willans formula does.