DEV Community

Onaolapo-11
Onaolapo-11

Posted on

The Sieve of Eratosthenes obtains the primes in a given range by eliminating the multiples of primes beginning from 2

[Reset] Day 6 [April 10th, 2026]

Goals:
"Day 3-4: Control structures (if-else, loops)" (Meta AI, personal communication, August 8, 2025)

Notes:
Python for Software Development' textbook by Halvorsen (n.d.):

  • To solve, the current task: "Create a Python Script where you find all prime numbers between 1 and 200", I learnt that an efficient method that can be used is the Sieve of Eratosthenes (Geeksforgeeks, 2025; Loucka, 2023).
  • The Sieve of Eratosthenes obtains the primes in a given range by eliminating the multiples of primes beginning from 2 (Geeksforgeeks, 2025; Loucka, 2023). AS you progress, you will discover some multiples are eliminated.

SIEVE OF ERATOSTENES ALGORITHM (Geeksforgeeks, 2025) [With my additional notes]:

def sieve(num): #num is the extent for which we want to check for primes

#we have to monitor if the numbers are prime
prime = [True] * (num + 1) #we have + 1 because the number in focus has to be captured
p = 2 #2 is the lowest prime number

Sieve of Erastostenes algorithm

while p * p <= num: #the product of the prime less than or equal to num. Why? The Sieve of Eratosthenes obtains the primes in a given range by eliminating the multiples of primes beginning from 2.
if prime[p]: #from the prime list at index p #showing us p = True at that particular prime

    #Mark all multiples of p as non-prime
    for i in range (p * p, num + 1, p):   #this range starts from the square of p and increases as multiples in p steps
        prime[i] = False
p += 1
Enter fullscreen mode Exit fullscreen mode

creating the list of all prime numbers

res = []
for p in range(2, n + 1):
if prime[p]:
res.append(p)
return res

Enter fullscreen mode Exit fullscreen mode




Evaluating the code below outputs the prime numbers between 1 and 200:

if name == "main":
n = 200
res = sieve(n)
for ele in res:
print(ele, end=' ')

Output:

2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 101 103 107 109 113 127 131 137 139 149 151 157 163 167 173 179 181 191 193 197 199

Summary:
The Sieve of Eratosthenes obtains the primes in a given range by eliminating the multiples of primes beginning from 2.

References:

  1. Geeksforgeeks. (2025, July 23). Sieve of Eratosthenes. https://www.geeksforgeeks.org/dsa/sieve-of-eratosthenes/

  2. Loucka, T. (2023, October 30). What are prime numbers? Doodlelearning. https://doodlelearning.com/maths/skills/numbers/prime-number-guide

  3. Halvorsen, H. (n.d.). Python. https://halvorsen.blog/documents/programming/python/python.php#python4

Top comments (0)