From a06995a686c0509f50a481e7d7d41bb35ffe8f19 Mon Sep 17 00:00:00 2001 From: Shubham Lad <30789414+ShuLaPy@users.noreply.github.com> Date: Mon, 21 Oct 2019 23:40:19 +0530 Subject: [PATCH] add simple improved Sieve Of Eratosthenes Algorithm (#1412) * add simple improved Sieve Of Eratosthenes Algorithm * added doctests * name changed --- maths/prime_sieve_eratosthenes.py | 41 +++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 maths/prime_sieve_eratosthenes.py diff --git a/maths/prime_sieve_eratosthenes.py b/maths/prime_sieve_eratosthenes.py new file mode 100644 index 000000000..7d039aaad --- /dev/null +++ b/maths/prime_sieve_eratosthenes.py @@ -0,0 +1,41 @@ +''' +Sieve of Eratosthenes + +Input : n =10 +Output : 2 3 5 7 + +Input : n = 20 +Output: 2 3 5 7 11 13 17 19 + +you can read in detail about this at +https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes +''' + +def prime_sieve_eratosthenes(num): + """ + print the prime numbers upto n + + >>> prime_sieve_eratosthenes(10) + 2 3 5 7 + >>> prime_sieve_eratosthenes(20) + 2 3 5 7 11 13 17 19 + """ + + + primes = [True for i in range(num + 1)] + p = 2 + + while p * p <= num: + if primes[p] == True: + for i in range(p*p, num+1, p): + primes[i] = False + p+=1 + + for prime in range(2, num+1): + if primes[prime]: + print(prime, end=" ") + +if __name__ == "__main__": + num = int(input()) + + prime_sieve_eratosthenes(num)