Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fast Algorithm to find number of primes between two numbers

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 optimizations.

Clearly the sieve method would be too slow in this case. Is there any mathematical optimization that can be applied - like for instance, taking a smaller subset of this large space and making inferences about the rest of the numbers.

P.S: It definitely looks like I might have reached a dead end - but all that I am looking for are some optimizations that could possibly help solve this. And also, I am only looking for a single-threaded approach.

EDIT: One approach I have been thinking and can solve a lot of large prime number related problems - is for someone to maintain a global table of primes and make it available for lookup. Folks at the PrimeGrid project can contribute usefully towards this.

like image 284
Hari Avatar asked Jan 20 '12 03:01

Hari


4 Answers

Since you want to go as high as 1000! (factorial). You will not be able to get exact results with currently known methods on current technology.

The Prime Counting Function has only been evaluated exactly for a handful of values up to 10^24. So no way you'll be able to hit 1000!.


But since you mention than an approximation may be fine, you can use the Logarithmic Integral as an approximation to the Prime Counting Function.

This is based on the Prime Number Theorem which says that the Prime Counting Function is asymptotic to the Logarithmic Integral.

like image 180
Mysticial Avatar answered Oct 28 '22 18:10

Mysticial


There is a fast, simple approximation to the number of primes below a given bound. If you do not need exact values, then a difference of two evaluations of this formula will get you close.

like image 39
phs Avatar answered Oct 28 '22 18:10

phs


The fastest method that I know would be to eliminate all of the known non-primes (even numbers, all the numbers with divisers lower than the start number in the range, etc) as fast as you can, then iterate over the rest and use something like the Euclidean algorithm to determine if that number is a prime.

like image 45
joe_coolish Avatar answered Oct 28 '22 19:10

joe_coolish


You can survey your options here: http://en.wikipedia.org/wiki/Prime_counting_function

This also looks helpful: http://mathworld.wolfram.com/PrimeCountingFunction.html

May I inquire why you need it up to 1000! ? Looks like no one has ever counted that many before. There are 1,925,320,391,606,803,968,923 primes from 1-10^23. 1000! = 10^120. I'm curious now.

like image 40
bweaver Avatar answered Oct 28 '22 18:10

bweaver