Last active
January 17, 2022 05:47
-
-
Save wjandrea/6322ed8906ef3780311a39b5bcc88825 to your computer and use it in GitHub Desktop.
"sieve" iterative, not recursive, based on https://www.youtube.com/watch?v=5jwV3zxXc8E
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(s): | |
seen = [] | |
for i in s: | |
if any(i%n == 0 for n in seen): # If "i" is divisible by any previous numbers | |
continue | |
yield i | |
seen.append(i) | |
from itertools import count # Don't reinvent the wheel ("nats") | |
s = sieve(count(2)) | |
for i, x in zip(range(15), s): # Get first 15 results | |
print(i, x) | |
""" | |
Output: | |
0 2 | |
1 3 | |
2 5 | |
3 7 | |
4 11 | |
5 13 | |
6 17 | |
7 19 | |
8 23 | |
9 29 | |
10 31 | |
11 37 | |
12 41 | |
13 43 | |
14 47 | |
""" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment