Skip to content

Instantly share code, notes, and snippets.

@fbidu
Created November 24, 2019 14:20
Show Gist options
  • Save fbidu/accaa5a6b313961efe23f6618d6bb5f7 to your computer and use it in GitHub Desktop.
Save fbidu/accaa5a6b313961efe23f6618d6bb5f7 to your computer and use it in GitHub Desktop.
A simple iterator that generates all the prime numbers
"""
primes provide a very simple iterator that's able
to generate all the prime numbers!
This is for teaching purposes only.
"""
class Primes:
"""
Primes is an iterator that generates all the prime numbers.
Its usage is simple:
>>> for prime in Primes():
... print(prime)
2
3
5
7
11
13
This is for teaching purposes only and implements the most
basic algorithm for primality testing. If you need to use
this in a more formal setting, please revisit this code.
For starters, I'd suggest using AKS primality testing.
"""
def __init__(self, start=1):
"""
init accepts a start values from where the iterator will begin.
It does not need to be a prime number itself.
"""
self.current = start
def __iter__(self):
return self
@staticmethod
def is_prime(n):
"""
is_prime does a trial-and-error primality check.
It basically loops through all the numbers from 0 up to n-1 checking
for divisors.
"""
# Note: we could loop up until sqrt(n).
for i in range(2, n):
# If n is divisible by any number other than
# 1 and itself, its not a prime
if n % i == 0:
return False
return True
def __next__(self):
"""
computes the next prime number by trial and error
"""
# The first candidate is the next number in line
next_prime = self.current + 1
# While it is NOT a prime...
while not self.is_prime(next_prime):
# We try the next number
next_prime += 1
self.current = next_prime
return self.current
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment