nth prime
A few days ago I posted a basic implementation of the Sieve of Eratosthenes.
The Sieve is great for finding all the numbers under n
that are prime. For example, what are all the prime numbers under 1,000,000?
But what about if I want to find the n
th prime? For example, what is the 10,001st prime number?
Since we need to pass the Sieve algorithm an “upper bound” number to use when creating the prime collection, it stands to reason that if we could somehow make an educated guess about the neighborhood of the n
th prime number, then we could create a Sieve using that guess as the upper bound and extract our target prime from the resulting list.
Turns out the Prime number theorem can be used for this purpose. The details are way over my head, but there is a formula based on this theorem which can help in approximating the n
th prime:
Approximations for the nth prime number
The first, more basic expression states that the n
th prime is approximately n * log(n)
I struggled with this expression for a bit, as I thought the base of the log
was the “natural” log. Turns out that the formula actually works when the base is 2. (if you can help to explain this please contact me)
So here’s a way to use the Sieve method from the other day to extract the n
th prime number.
Test Suite: