Prime number sieve used by a few of my Euler c++ solutions.
Jan 21, 2015 6 minute read
Introduction
The sieve of Eratosthenes is a simple algorithm for finding all prime numbers up to a given limit.
It does so by iteratively marking as composite (i.e. not prime) the multiples of each prime,
starting with the multiples of 2.
Source
PDL
Let A be an array of Boolean values, indexed by integers 2 to n,
initially all set to true.
for i = 2, 3, 4, ..., not exceeding √n:
if A[i] is true:
for j = i2, i2+i, i2+2i, ..., not exceeding n :
A[j] := false
Output: all i such that A[i] is true.
The implementation below was quickly put together to support a couple of my Euler c++ solutions. I include it here for completeness.
THERE HAS BEEN NO ATTEMPT TO OPTIMIZE THE CODE BELOW