primessieve-of-eratosthenes

Better algorithm to find nth prime number?


Until now, I've been using sieve of Eratosthenes for generating all 'n' prime numbers.

However, I was wondering does there exist a better algorithm, or can we improve an existing one which performs better ??


Solution

  • For sufficiently large N (e.g. more than a million or so), the best algorithm is to use an approximation (e.g. Logarithmic Integral or Riemann's R function), then use a fast prime count method such as LMO, then sieve the small remainder. This is many orders of magnitude faster than sieving.

    See https://math.stackexchange.com/questions/507178/most-efficient-algorithm-for-nth-prime-deterministic-and-probabilistic

    There are at least two open source implementations.

    The latter has progressed past the first, and is also multithreaded.

    Add: Will Ness has also pointed out a nice post from Daniel Fischer that provides a walkthrough of different ways to solve this: Calculating and printing the nth prime number