Skip to content

Commit 664b352

Browse files
committed
Added Sieve of Eratosthenes algorithm for finding primes
1 parent 3f505c5 commit 664b352

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed

other/FindingPrimes.py

+21
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
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=" ")
19+
20+
n = int(input("Enter a positive number\n"))
21+
SOE(n)

0 commit comments

Comments
 (0)