From f4fccdce40d5a84f97618e84dafd8239c7e6a4e2 Mon Sep 17 00:00:00 2001 From: Aniket Sharma Date: Thu, 1 Oct 2020 22:31:30 +0530 Subject: [PATCH] Added 'Sieve of Eratosthenes' Added 'Sieve of Eratosthenes' in 'Prime Numbers' directory. --- Prime Numbers/sieve_of_eratosthenes.py | 28 ++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 Prime Numbers/sieve_of_eratosthenes.py diff --git a/Prime Numbers/sieve_of_eratosthenes.py b/Prime Numbers/sieve_of_eratosthenes.py new file mode 100644 index 0000000..247abc4 --- /dev/null +++ b/Prime Numbers/sieve_of_eratosthenes.py @@ -0,0 +1,28 @@ +""" +Python program to print all prime number smaller than or equal +to the given input using Sieve of Eratosthenes. +""" + + +def sieve_of_eratosthenes(num): + # List to store whether a number is prime or not + prime = [True for i in range(num+1)] + p = 2 + while (p*p <= num): + # If prime[p] is True, then p is a prime number + if (prime[p] == True): + # Update all multiples of Prime 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), + + +if __name__ == '__main__': + num = int(input()) + print("Following are the prime numbers smaller than or equal to {}".format(num)) + sieve_of_eratosthenes(num)