C

C

Return to Notes

Sieve of Eratosthenes

Determines all primes in a bounded range.

The Algorithm

Let S=(2,3,,C)S = (2, 3, \ldots, \lfloor C \rfloor). For each i(2,3,,C)i \in (2, 3, \ldots, \lfloor \sqrt{C} \rfloor), if iSi \in S, remove all multiples 2i,3i,4i,2i, 3i, 4i, \ldots in the list. The numbers left in SS are all the primes less than the bound CC.

Sage Implementation

bound = 1000
space = [2..bound]

sieve = lambda k: k % i != 0 or k == i

for i in [2..floor(sqrt(bound))]:
    if i in space:
        space = list(filter(sieve, space))

# We can check our work:
# primes = list(filter(is_prime, [2..bound]))
# print(len(primes), len(space))
# Both lists contain 168 values!

print(space)