The Wayback Machine - https://web.archive.org/web/20230702230519/https://www.geeksforgeeks.org/python-program-for-sieve-of-eratosthenes/
Skip to content
Related Articles
Open In App

Related Articles

Python Program for Sieve of Eratosthenes

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

Sieve of Eratosthenes is a method for finding all primes up to (and possibly including) a given natural. This method works well when is relatively small, allowing us to determine whether any natural number less than or equal to is prime or composite. 

Implementation:

Given a number n, print all primes smaller than or equal to n. It is also given that n is a small number. For instance here if n is 10, the output should be “2, 3, 5, 7”. If n is 20, the output should be “2, 3, 5, 7, 11, 13, 17, 19”.

Example 

Python3




# Python program to print all Primes Smaller
# than or equal to N using Sieve of Eratosthenes
 
 
def SieveOfEratosthenes(num):
    prime = [True for i in range(num+1)]
# boolean array
    p = 2
    while (p * p <= num):
 
        # If prime[p] is not
        # changed, then it is a prime
        if (prime[p] == True):
 
            # Updating all multiples of p
            for i in range(p * p, num+1, p):
                prime[i] = False
        p += 1
 
    # Print all prime numbers
    for p in range(2, num+1):
        if prime[p]:
            print(p)
 
 
# Driver code
if __name__ == '__main__':
    num = 30
    print("Following are the prime numbers smaller"),
    print("than or equal to", num)
    SieveOfEratosthenes(num)

Output

Following are the prime numbers smaller
than or equal to 30
2
3
5
7
11
13
17
19
23
29

Time Complexity: O(n*log(log(n)))

Auxiliary Space: O(n)

Please refer complete article on Sieve of Eratosthenes for more details! 

Last Updated : 27 Feb, 2023
Like Article
Save Article
Similar Reads