What is the Sieve of Eratosthenes?
The Sieve of Eratosthenes is an algorithm for finding all prime numbers up to any given limit. The algorithm is simple and can be implemented with the following steps:
- Create an array of boolean values with N elements, and initialize all elements to true.
- Set the 0th and 1st elements of the array to false (because 0 and 1 are not prime numbers).
- If the 2nd element of the array is true, output 2 as a prime number.
- Set all multiples of 2 from $2^2$ onwards in the array to false.*
- If the 3rd element of the array is true, output 3 as a prime number.
- Set all multiples of 3 from $3^2$ onwards in the array to false.
- Repeat the same process for the 4th, 5th, …, Nth elements.
*The reason for targeting elements from the square of the number onwards to become false is because the numbers smaller than the square have already been processed (enumeration is complete).

Implementation in Rust
| |
Slightly Faster Version
Considering the following points, we implement a slightly faster version:
- Instead of initializing the array with true, initialize it with false (this is faster).
- Since multiples of 2 are not prime numbers, omit the process of setting the elements of multiples of 2 to false.
- There is no need to loop up to n; by enumerating primes up to the square root of n, you can enumerate primes up to n.
| |
