When it comes to efficiently finding all prime numbers less than a given limit ๐, the Sieve of Eratosthenes stands out as one of the most elegant and efficient algorithms.
Developed by the ancient Greek mathematician Eratosthenes, this algorithm systematically eliminates non-prime numbers, significantly reducing computation time compared to naive methods. In this article, we'll explore how the Sieve of Eratosthenes works, analyze its time complexity, and implement it in code.
Let's dive in! ๐
Understanding the Concept
To find all prime numbers less than ๐ using the Sieve of Eratosthenes, follow these steps:
List all numbers from 0 to ๐-1.
Assume all numbers are prime initially (except 0 and 1, which are not primes).
Start at 2, the smallest prime number.
Mark all multiples of 2 as non-prime (false), except 2 itself.
Move to the next number that is true and mark all its multiples, except itself as non-prime.
Repeat this process until you reach
โN
orsqrt(N)
.
Why stop at ๐?
If we are finding primes less than 100, we stop at 10 because โ100 = 10
. Any composite number greater than ๐ must have a factor already marked earlier in the process. The numbers that remain unmarked are all prime.
Visualizing the Algorithm
We start by marking 0 and 1 as not prime
Mark 2 as prime while all its multiples as not prime
Go to the next unvisited tile, which is 3
Mark it as prime and its multiples as not prime
Go to the next unvisited tile, but it is greater than the square root of 24, so we stop
Mark all the unvisited tiles as prime
The Pseudocode
Find all primes less than N
if N <= 2:
return an empty list
create a list is_prime of size N, initialized to true
set is_prime[0] and is_prime[1] to false (since 0 and 1 are not prime)
for i from 2 to โN+1:
if is_prime[i] is true:
for x from iยฒ to N, incrementing by i:
set is_prime[x] to false
return all indices where is_prime[index] is true
Implementing the Algorithm
from math import isqrt
def primes_less_than(N: int) -> list[int]:
if N <= 2:
return []
is_prime = [True] * N
is_prime[0] = False
is_prime[1] = False
for i in range(2, isqrt(N)+1):
if is_prime[i]:
for x in range(i*i, N, i):
is_prime[x] = False
return [i for i in range(N) if is_prime[i]]
If you found this article helpful, feel free to share your thoughts or experiment with optimizations to make it even faster. Happy coding! ๐