SBN

Python Prime Number Generator

Here’s an interesting prime number generator that I created. It avoids multiplication and modulo arithmetic. It does not sieve a preallocated set of integers (ex. find all primes up to N). You can serialize it and then resume generating (no need to specify an upper bound).

Its internal state consists of 2 lists and an integer representing the current candidate. The lists are a list of primes and a corresponding list of prime multiples. For a given candidate, the algorithm compares the candidate to current prime multiples. If the candidate is less than a multiple, the prime multiple is increased additively to its next multiple (p + p + … + p) where p is the prime root. If the multiple is equal to the candidate, the candidate is not prime. If there’s no match, the candidate is prime and added to the list (p**2 added to the list of multiples).


class PrimeGen:
p = [ ] # primes found
m = [ ] # current multiple of each prime

def prime(self, i):
for j in xrange(0, len(self.p)):
if (i + i) < self.m[j]: break
if i > self.m[j]: self.m[j] += self.p[j] if i == self.m[j]: return 0
self.p.append(i)
self.m.append(i ** 2)
return 1

def gen(self):
"""A prime generator"""
i = 2
while 1:
if self.prime(i): yield(i)
i += 1

The drawback is running time. Sieves (ex. Eratosthenes) are faster. This one generates the first million primes (<= 15,485,863) in about 10 minutes on modest hardware.

*** This is a Security Bloggers Network syndicated blog from Armchair Stratosphere authored by Jason. Read the original post at: http://maliciousattacker.blogspot.com/2010/12/python-prime-number-generator.html