The Sieve of Eratosthenes is a classical algorithm used to find all prime numbers up to a specified integer. It is one of the most efficient ways to identify small prime numbers and has a time complexity of
Given an integer
-
Initialization:
- Create a list of odd integers from 3 to
$n$ . - Assume all numbers are prime.
- Create a list of odd integers from 3 to
-
Marking Multiples:
- Start with the first prime number, 3, and mark all of its multiples.
- Move to the next number in the list that is still considered prime.
- Repeat the process until you've processed each number up to
$\sqrt{n}$ .
-
Collect Primes:
- The numbers that remain unmarked are primes.
Why repeating the process until
Another optimization we can do is marking the multiples of a prime p starting from p². That happens because all other multiples of p less than p² were already covered by smaller primes.
Let's find all prime numbers up to
-
Initialization:
is_prime = [True] * 31
p = 2
-
Marking Multiples:
- Mark multiples of 2:
4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
. - Move to
p = 3
and mark multiples of 3:9, 12, 15, 18, 21, 24, 27, 30
. - Skip even numbers and move to
p = 5
. - Mark multiples of 5:
25, 30
.
- Mark multiples of 2:
-
Collect Primes:
- The numbers that remain unmarked are
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
.
- The numbers that remain unmarked are
Thus, the prime numbers up to 30 are 2, 3, 5, 7, 11, 13, 17, 19, 23, 29
.
The main program implementing the Sieve of Eratosthenes takes an integer
-
Input: An integer
$n$ . -
Output: A list of all prime numbers less than or equal to
$n$ .
For example, given the input [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
.
The Sieve of Eratosthenes is particularly efficient for generating a list of small primes. However, it requires
- Wikipedia: Sieve of Eratosthenes
- Números Inteiros e Criptografia RSA.
- Other books and research papers on prime number generation and number theory.