Last active
June 6, 2021 18:29
-
-
Save realeroberto/41d787b2a80068d29cff to your computer and use it in GitHub Desktop.
A simple Python iterator that returns the sequence of prime numbers on successive calls to its next() method...
This file contains hidden or 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
class PrimeGenerator: | |
def __init__(self): | |
self.primes = [] | |
self.current_prime = 1 | |
def __iter__(self): | |
return self | |
def __next__(self) -> int: | |
candidate = self.current_prime + 1 | |
while True: | |
is_prime = True | |
for prime in self.primes: | |
if candidate % prime == 0: | |
is_prime = False | |
break | |
if is_prime: | |
self.primes.append(candidate) | |
self.current_prime = candidate | |
break | |
else: | |
candidate += 1 | |
return self.current_prime |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
My suggestion: