-
-
Save mthpower/d607258bca540b75afc9534f52eae282 to your computer and use it in GitHub Desktop.
Python 3 Sieve of Eratosthenes - https://upload.wikimedia.org/wikipedia/commons/b/b9/Sieve_of_Eratosthenes_animation.gif
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
def sieve(limit): | |
candidates = set(range(2, limit + 1)) | |
for i in candidates: | |
sieved = set(filter(lambda x: not x % i, candidates - {i})) | |
candidates = candidates - sieved | |
return sorted(candidates) | |
print(sieve(997)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It turns out you're looping over all the original candidate set.
Some different approaches to avoid this https://gist.github.com/tomviner/ddb9474f96f8d0366f5f39bf53208a16 plus an even more concise version.