Is there a library function that can enumerate the prime numbers (in sequence) in Python?
I found this question Fastest way to list all primes below N but I\'d rathe
There is no constant time algorithm to generate the next prime number; this is why most libraries require an upper bound. This is actually a huge problem that needed to be solved for digital cryptography. RSA chooses sufficiently large primes by selecting a random number and testing for primality until it finds a prime.
Given an arbitrary integer N, the only way to find the next prime after N is to iterate through N+1 to the unknown prime P testing for primality.
Testing for primality is very cheap, and there are python libraries that do so: AKS Primes algorithm in Python
Given a function test_prime, than an infinite primes iterator will look something like:
class IterPrimes(object):
def __init__(self,n=1):
self.n=n
def __iter__(self):
return self
def next(self):
n = self.n
while not test_prime(n):
n += 1
self.n = n+1
return n
There are a lot of heuristics you could use to speed up the process. For instance, skip even numbers, or numbers divisible by 2,3,5,7,11,13,etc..