How to Find Prime Numbers with Sieve of Eratosthenes in Python


In this example we will show how to find prime numbers through the Eratosthenes filter.

Source Code

#! /usr/bin/env python3
# -*- coding: utf-8 -*-

n = int(input("Enter upper limit of range: "))
isPrimes = [True] * (n + 1)                 
for p in range(2, int(n ** 0.5) + 1):          
    if isPrimes[p]:                       
        for i in range(p * p, n + 1, p): 
            isPrimes[i] = False
for element in range(2, n+1):          
    if isPrimes[element]:
        print(element, sep=" ", end=" ")

print()

Output:

Enter upper limit of range: 20
2 3 5 7 11 13 17 19

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments