Infinite prime number generator

John Posner jjposner at optimum.net
Tue Jun 29 14:31:40 EDT 2010


On 6/29/2010 12:51 PM, Thomas Jollans wrote:

> def rprimes():
>      def elim_mult(n):
>          yield n
>          for p in filter((lambda x:x%n != 0), elim_mult(n+1)): yield p
>      yield 1
>      for p in elim_mult(2): yield p
>

Thomas, take a look at the thread "Generators/iterators, Pythonicity, 
and primes" in the April 2009 archives of python-list. For example:

   from itertools import ifilter, count
   pgen = ifilter(
             lambda n, primes=[]:
                 all(n%p for p in primes) and not primes.append(n),
             count(2)
          )
   for _ in range(50): print pgen.next()

-John



More information about the Python-list mailing list