Fast Algorithm to find number of primes between two numbers

前端 未结 5 2016
后悔当初
后悔当初 2021-02-04 14:57

My problem reduces to finding the number of primes between two given numbers.I could have a range as big as 1 to (1000)! and hence I am need of some mathematical op

5条回答
  •  不知归路
    2021-02-04 15:33

    The prime counting algorithm developed by Lagarias and others, quoted by others, runs very roughly in O (n^(2/3)). Since a sieve for the primes from k1 to k2 takes roughly O (max (sqrt (k2), k2 - k1), you'd check how far your lower and upper bounds are apart and either do a sieve or use the prime counting algorithm, whichever will be faster.

    BTW. The prime counting algorithm can be tuned to count the primes from 1 to n for various values n that are reasonably close together quicker than counting them individually. (Basically, it chooses a number N, creates a sieve of size n / N, and looks up N^2 values in that sieve. The O (n^(2/3)) comes from the fact that for N = n^(1/3) both operations take N^(2/3) steps. That sieve can be reused for different n, but different values need to be looked up. So for k different values of n, you make N a bit smaller, increasing the cost of the sieve (once only) but reducing the cost of the lookup (k times)).

    For n around 1000!, there's no chance. You can't even count the number of primes in [n, n] for values of that size if n has no small(ish) factors.

提交回复
热议问题