Created
April 4, 2012 21:49
-
-
Save owainlewis/2305953 to your computer and use it in GitHub Desktop.
Sieve of Erastothenes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from math import sqrt | |
# Sieve of Erastothenes | |
def sieve(n): | |
candidates = list(range(n)) | |
# We only need to check up to the square root of n | |
upto = int(sqrt(n)) + 1 | |
# Loop over the candidates, marking out each multiple as None. | |
for i in list(range(2, upto)): | |
if not candidates[i]: | |
continue | |
# mark out each multiple of i | |
for x in range(2 * i, n, i): | |
candidates[x] = None | |
# Filter out non-primes and return the list. | |
return list(filter(lambda x : x != None, candidates))[2:] | |
print(sieve(30)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment