Sieve of Eratosthenes


Note: This implementation is old, sub-optimal, and has a minor bug or two, I will try to update to the latest code soon.


The Sieve of Eratosthenes is an efficient way to compute all of the prime numbers between 2 and a specified upper limit.


As an exercise, I coded up a simple, informal implementation of this technique which took the form of a bit set data structure, backed by an array of 64-bit long integers.


As an example of this technique's and implementation's performance, it took my average laptop about 1 second to compute all the primes between 2 and 10M and store them in the bit set for fast access via the member method: isPrime( int n ).


The test output is listed below.  Note that only the first 200 primes are printed in the output.

run:


2 3 5 7 11 13 17 19 23 29

31 37 41 43 47 53 59 61 67 71

73 79 83 89 97 101 103 107 109 113

127 131 137 139 149 151 157 163 167 173

179 181 191 193 197 199 211 223 227 229

233 239 241 251 257 263 269 271 277 281

283 293 307 311 313 317 331 337 347 349

353 359 367 373 379 383 389 397 401 409

419 421 431 433 439 443 449 457 461 463

467 479 487 491 499 503 509 521 523 541

547 557 563 569 571 577 587 593 599 601

607 613 617 619 631 641 643 647 653 659

661 673 677 683 691 701 709 719 727 733

739 743 751 757 761 769 773 787 797 809

811 821 823 827 829 839 853 857 859 863

877 881 883 887 907 911 919 929 937 941

947 953 967 971 977 983 991 997 1,009 1,013

1,019 1,021 1,031 1,033 1,039 1,049 1,051 1,061 1,063 1,069

1,087 1,091 1,093 1,097 1,103 1,109 1,117 1,123 1,129 1,151

1,153 1,163 1,171 1,181 1,187 1,193 1,201 1,213 1,217 1,223


It took 944 ms to compute the primes between 2 to 10,000,000

max int: 10,000,000

max prime: 9,999,991

Number of primes found between 2 and 10,000,000 : 664,579

Fraction of integers which are prime in this range: 0.066457905


BUILD SUCCESSFUL (total time: 2 seconds)


Out of curiosity, I modified this program to count the number of primes in each range of 1M up to 1B; a sort of "prime number density" function.


For example, the number of primes in range [ 1 to 1,000,000 ], [ 1,000,001 to 2,000,000 ], etc.


Here is an Excel graph (click to enlarge) of the resulting 1,000 data points for this 'primes density' curve/experiment:

(The right-most data point is for the bin range 999,000,001 to 1,000,000,000.)