Sieve of Eratosthenes
- Sean Robinson
- May 28, 2014
- 2 min read
I was rummaging around in some old directories and found an implementation of the Sieve of Eratosthenes that I’d thought I’d share. I thought I’d share it because of the simplicity of the algorithm, it represented a very enjoyable programming exercise and one that I now use as a standard kata when learning a new language. The Sieve of Eratosthenes is an algorithm used to identify prime numbers.
In it’s simplest form, the algorithm states:
Basically, it trawls an array of “on” bits and “turns off” any index that is cleanly divisible by any number less than the square root of it’s size.
Breaking down the class, the entry point is here. Simple enough, get a list of primes and print it out.
Next up, we initialise our array, remove the non primes (sieving) and return the result.
Initialisation is simply setting all of the array indices to 1. We will switch off any index that isn’t prime further in.
Here’s the meat of the algorithm. For each number less than the square root of the size, we turn off any index that is cleanly divisible by that number. There’s a lot of repetition here, so it isn’t the quickest way of performing this, I’ll put some links for further reading at the end.
And we’re done! Just aggregate the remaining bits into a list…
…and print it out.
Full Source:
Now this isn’t the fastest way to search for primes, there are a number of other algorithms that can be used to arrive at the result quicker. The Sieve of Sundaram and Sieve of Atkin both offer increased performance.
Ashraff Ali Wahab has done an excellent comparison of benchmarks here.
Comentarios