Sieve of Eratosthenes


In mathematics, the sieve of Eratosthenes is an ancient algorithm for finding all prime numbers up to any given limit.

By iteratively marking as composite (i.e., not prime) the multiples of each prime, starting with the first prime number (2), the multiples of a given prime are generated as a sequence of numbers starting from that prime, with constant difference between them that is equal to that prime. This is the sieve's key distinction from using trial division to sequentially test each candidate number for divisibility by each prime. Once all the multiples of each discovered prime have been marked as composites, the remaining unmarked numbers are primes.

Wikipedia Sieve of Eratosthenes

Implementation

The implementation consists of using the :nth-child(n) pseudo-class to perform modulo-arithmetic of all items divisible by prime numbers 2, 3, 5 and 7 over an ordered list <ol> consisting of n list items <li> where each item has a numeric value, and where P is the prime number. :nth-child(Pn) can be applied to mark the list items as non-prime and :not(:nth-child(P)) can be applied to ignore the initial prime number, thus the remaining unmarked items are prime.

In order to show prime numbers only, the :checked pseudo-class can be used in conjuction with the subsequent-sibling combinator ~ to hide all list items <li> matching :nth-child(Pn) and :not(:nth-child(P)) respectively.

Given a range of 2-120, primes 2, 3, 5 and 7 are sufficient to implement the sieve. Larger ranges would require additional primes to be implemented in CSS with little effort.

Legend

Divisible by 2 Divisible by 3 Divisible by 5 Divisible by 7

Note that some values may be divisible by multiple primes, in which case they are coloured by the last prime in the implementation order (2, 3, 5, 7).