Skip to content

Commit e76dc66

Browse files
authored
Merge pull request TheAlgorithms#48 from RianGallagher/master
Added Sieve of Eratosthenes algorithm for finding primes
2 parents 3f505c5 + 4a6894c commit e76dc66

File tree

1 file changed

+18
-0
lines changed

1 file changed

+18
-0
lines changed

other/FindingPrimes.py

+18
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
'''
2+
-The sieve of Eratosthenes is an algorithm used to find prime numbers, less than or equal to a given value.
3+
-Illustration: https://upload.wikimedia.org/wikipedia/commons/b/b9/Sieve_of_Eratosthenes_animation.gif
4+
'''
5+
from math import sqrt
6+
def SOE(n):
7+
check = round(sqrt(n)) #Need not check for multiples past the square root of n
8+
9+
sieve = [False if i <2 else True for i in range(n+1)] #Set every index to False except for index 0 and 1
10+
11+
for i in range(2, check):
12+
if(sieve[i] == True): #If i is a prime
13+
for j in range(i+i, n+1, i): #Step through the list in increments of i(the multiples of the prime)
14+
sieve[j] = False #Sets every multiple of i to False
15+
16+
for i in range(n+1):
17+
if(sieve[i] == True):
18+
print(i, end=" ")

0 commit comments

Comments
 (0)