Speedup calculating prime numbers with Sieve of Eratosthenes Algorithm

Mashiur Rahman
1 min readJul 7, 2023
algorithm Sieve of Eratosthenes
input: an integer n > 1.
output: all prime numbers from 2 through n.

let A be an array of Boolean values, indexed by integers 2 to n,
initially all set to true.

for i = 2, 3, 4, ..., not exceeding √n do
if A[i] is true
for j = i2, i2+i, i2+2i, i2+3i, ..., not exceeding n do
set A[j] := false

return all i such that A[i] is true.

Python Code

def sieve_of_eratosthenes(limit):
primes = [True] * (limit + 1)
primes[0] = primes[1] = False

for num in range(2, limit + 1):
if primes[num]:
for multiple in range(num * num, limit + 1, num):
primes[multiple] = False

prime_numbers = [num for num, is_prime in enumerate(primes) if is_prime]
print(prime_numbers)

sieve_of_eratosthenes(5000)

Algorithm Overview:

  1. Create a list of numbers from 2 to the desired upper limit.
  2. Mark 2 as prime.
  3. Cross out all multiples of 2 from the list.
  4. Move to the next unmarked number, which will be the next prime.
  5. Cross out all multiples of this prime number from the list.

Repeat steps 4 and 5 until there are no unmarked numbers left.

Find Out Prime numbers in different programming language with Sieve of Eratosthenes

--

--