Concurrent Sieve of Eratosthenes in Go
play.golang.org
play.golang.org
The gist of the problem is this: in the true sieve, each number is touched once for each of its prime factors. In this sieve, each number is touched once by each prime smaller than it (until a factor is found.)
There are a lot more primes that aren't factors of a given number than primes that are.
[1] http://www.thelowlyprogrammer.com/2010/03/writing-efficient-... [2] http://www.thelowlyprogrammer.com/2012/08/primes-part-2-segm...
For comparison, I've used Go to implement a segmented version of the true Sieve of Eratosthenes. It's a standard array-based sieve, chunked up. It takes advantage of goroutines for parallelism, and implements an efficient algorithm at the same time. The code is a lot longer than this one because it tries to do a lot more (memory efficiency, large number support, etc), but it should give you an idea what a full implementation might look like. http://www.thelowlyprogrammer.com/2012/08/primes-part-2-segm...
https://gist.github.com/4105864
Even with extensive documentation it is only 3 lines longer than the Go version ;)
// By default, Go keeps only one kernel thread (m) running user code
// at a single time; other threads may be blocked in the operating system.
// Setting the environment variable $GOMAXPROCS or calling
// runtime.GOMAXPROCS() will change the number of user threads
// allowed to execute simultaneously. $GOMAXPROCS is thus an
// approximation of the maximum number of cores to use.
From http://golang.org/src/pkg/runtime/proc.cFor comparison C++ based implementations range from 13.5 seconds to 0.65 seconds when iterating over 1,000,000,000 elements on an Intel Core i7 860, quad-core, hyperthreading, 2.8Ghz cpu. (http://create.stephan-brumme.com/eratosthenes/)
Someone ported djb's primegen (uses the Sieve of Atkin) to Go, and got comparable performance-- .7s for primes up to a trillion. https://groups.google.com/forum/m/?fromgroups#!topic/golang-...
I wonder how it compares to pypy.