The Sum Of The First Billion Primes

September 11, 2012

Your task is to write a program that calculates the sum of the first billion primes. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.

public class AddPrimes {
public static void main(String[] args) {
//Initialize number as 2, the first possible prime number larger than one
number = 2;
//Main Loop; loop until 1 billion prime numbers have been discovered
while(primeCounter < 1000000){
//Initialize fields for Calculation Loop.
m = Math.sqrt(number);
divisor = 2;
//Calculation Loop
while(divisor <= m){
//Initialize quotient
quotient = number /divisor;
//Initialize isInteger
isInteger = checkIsInteger(quotient);
//If the quotient is an integer, add it to the list of factors. Increase divisor by 1.
if(isInteger == true ){
factors.add(quotient);
divisor++;
//If the quotient is not an integer, increase the divisor by 1.
}else{
divisor++;
}
}
//Once all quotients are analyzed, if the list of factors is empty, then the number is prime.
//Add the number to the sum of primes. Increase primeCounter by 1. Increase number by 1.
if(factors.isEmpty() == true){
sum += number;
primeCounter ++;
number++;
//If the list of factors is not empty, then the number is not prime. Clear the list of factors.
//Increase number by 1.
}else{
factors.clear();
number++;
}
}
//Display the sum of the total number of primes discovered.
System.out.println(sum);
}
/**
* Determines whether or not the given double is an integer.
* @param d - double
* @return true if d is an integer or false if d is not an integer
*/
public static boolean checkIsInteger(double d){
boolean intCheck;
String doubleText = Double.toString(d);
if(doubleText.endsWith("0")){
intCheck = true;
}else{
intCheck = false;
}
return intCheck;
}
//Necessary fields
/**
* The current number being tested for primality.
*/
static double number;
/**
* The sum of all numbers determined to be prime.
*/
static int sum;
/**
* The square root of the current number.
*/
static double m;
/**
* The current divisor.
*/
static int divisor;
/**
* The quotient of number / divisor.
*/
static double quotient;
/**
* A counter that records the total number of discovered prime numbers.
*/
static int primeCounter;
/**
* Boolean placeholder for the result of the checkInteger method.
*/
static boolean isInteger;
/**
* List of any factors discovered for number.
*/
static ArrayList factors = new ArrayList();
}

Done in SwiftForth with a bitset library I wrote a long time ago. Took 40 minutes or 410K primes per second. (While also watching web video, etc. on the computer.) It uses the compressed 33K file from previous exercise to store primes < 1 million, which is used as the sieving primes, and the segmented sieve from another previous exercise to sieve blocks after 1 million, in increments of 100,000.

Done in SwiftForth with a bitset library I wrote a long time ago. Took 40 minutes or 410K primes per second. (While also watching web video, etc. on the computer.) It uses the compressed 33K file from previous exercise to store primes < 1 million, which is used as the sieving primes, and the segmented sieve from another previous exercise to sieve blocks after 1 million, in increments of 100,000.

[…] This problem from Programming Praxis came about in the comments to my last post and intrigued me. So today, we are trying to sum the first one billion primes. Summing the first hundred, thousand, even million primes isn’t actually that bad. But it takes a bit more effort when you scale it up to a billion. And why’s that? […]

I know it’s an older, but after your comments on my solution to the Pythagorean Triples hinting at this one, I had to try it. I ended up working on it way more than I probably should have with quals coming up, but what I ended up with is 5 different ways (including all three sieves mentioned on Wikipedia) of summing the first n primes with different data structure variants on the two fastest ones.

It still ends up taking an hour and a half on the quickest run, but it was really interesting to work out all of the ways to do it. Perhaps I’ll see if I can optimize even more at some point. Although 10 seconds? Likely not. :)

The first is calling Math::Prime::Util::next_prime in a dumb loop. Not very fast since it’s doing trial division and/or MR tests. 400k-500k / second.

We can speed that up by having MPU precalculate all the primes, obviously at the expense of memory (about 760MB for sieving 22.8B numbers). Using nth_prime_upper() to get an upper bound (0.01% larger than the real value, but obtained in microseconds) we can do this pretty fast. A reasonably fast solution at over 3M primes/s.

Next is using Math::Prime::Util to do it more efficiently — get primes in segments until we’ve reached our limit. Not bad — 66s on my machine to sum the first 1 billion. Over 15M/s.

Now we move to pure Perl. First let’s use an unsegmented sieve. This one is a modification of one from c2.com’s wiki, which is a very simple SoE, and much faster than most Perl sieves found on the web (I have a collection of 17 of them — some shockingly bad, some quite decent). It runs at about 260k/s. But the biggest problem is that it isn’t segmented, nor is it storing the numbers efficiently. My 32GB machine started swapping when calculating 10^8.

Lastly is a segmented sieve in pure Perl using strings. A bit wacky and too verbose, but it can be faster than the obvious solutions depending on memory speed. As a basic unsegmented sieve, it’s about 2x faster than any of the other Perl solutions on my workstation. On my old Atom netbook it’s a bit slower than the above sieve. I wrote it earlier this year so Math::Prime::Util could have something reasonable as a fallback if the XS failed to compile on a platform. Since it’s segmented it will work for our task without going crazy with memory. Over 500k/s.

None of them compare to primesieve of course (the serial version of Kim’s program takes all of 7 seconds on my machine, the parallel version runs in 1.1s). The callback is spiffy also. I thought about adding something like it to Math::Prime::Util (e.g. prime_foreach 2 100 { …sub… }) and still might, but calling Perl subroutines is far slower than C — it’s over a minute just to make 1B empty subroutine calls so it seems of limited use for this example.

Dang. After some comments over on my original post, I decided to go back and add a the segmented version of the Sieve of Eratosthenes into the mix. I’m glad I did.

While my previous times were 2 hr 42 min for Eratosthenes and 1 hr 28 min for Atkin, the new segmented sieve blows both out of the water at only 25 min 12 sec. It’s still nowhere near as quick as some people’s, but it’s at least a good example of what being conscious of what memory/caching behavior can do to runtimes.

On my Intel Core i7 2.3 ghz machine, it completes in 495 milliseconds and uses about 800,000 bytes of RAM (but if I used a larger wheel that would go up rapidly).

One interesting side note: the actual algorithm I’m using doesn’t use any memory during run time aside from the pre-allocated memory of the wheels and the stack space of the function calls (which will never be deeper than log n/log 2), so it would be relatively trivially to make this algorithm multi-threaded or even distributed. My 495 ms time is single-threaded. With that said, this algorithm runs in something worse than O(n^4/5) time, so there are faster solutions.

That’s not *too* far off primesieve’s 7 seconds. Both work by generating primes with a segmented sieve and doing something with the results. Someday I may add one of the fast sums, but memory and code size (standard C) are important.