From 664b35252ed08751bd7789070f98c7b8131ab470 Mon Sep 17 00:00:00 2001 From: Rian Gallagher Date: Sun, 20 Nov 2016 21:44:21 +0000 Subject: [PATCH 1/2] Added Sieve of Eratosthenes algorithm for finding primes --- other/FindingPrimes.py | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 other/FindingPrimes.py diff --git a/other/FindingPrimes.py b/other/FindingPrimes.py new file mode 100644 index 000000000000..aa6dfabb2014 --- /dev/null +++ b/other/FindingPrimes.py @@ -0,0 +1,21 @@ +''' +-The sieve of Eratosthenes is an algorithm used to find prime numbers, less than or equal to a given value. +-Illustration: https://upload.wikimedia.org/wikipedia/commons/b/b9/Sieve_of_Eratosthenes_animation.gif +''' +from math import sqrt +def SOE(n): + check = round(sqrt(n)) #Need not check for multiples past the square root of n + + sieve = [False if i <2 else True for i in range(n+1)] #Set every index to False except for index 0 and 1 + + for i in range(2, check): + if(sieve[i] == True): #If i is a prime + for j in range(i+i, n+1, i): #Step through the list in increments of i(the multiples of the prime) + sieve[j] = False #Sets every multiple of i to False + + for i in range(n+1): + if(sieve[i] == True): + print(i, end=" ") + +n = int(input("Enter a positive number\n")) +SOE(n) \ No newline at end of file From 4a6894c1fa1b048aa7231561f6b6e6a5de62702c Mon Sep 17 00:00:00 2001 From: Rian Gallagher Date: Sun, 20 Nov 2016 22:11:50 +0000 Subject: [PATCH 2/2] Added Sieve of Eratosthenes for finding primes --- other/FindingPrimes.py | 3 --- 1 file changed, 3 deletions(-) diff --git a/other/FindingPrimes.py b/other/FindingPrimes.py index aa6dfabb2014..3cb10f701ab3 100644 --- a/other/FindingPrimes.py +++ b/other/FindingPrimes.py @@ -16,6 +16,3 @@ def SOE(n): for i in range(n+1): if(sieve[i] == True): print(i, end=" ") - -n = int(input("Enter a positive number\n")) -SOE(n) \ No newline at end of file