Shortest prime number program
Tim Hochberg
tim.hochberg at ieee.org
Sun Feb 12 03:08:16 EST 2006
While not nearly the shortest proposed thus far, I'm fond of:
from itertools import count, ifilter
def sieve(s=count(2)):
while 1:p=s.next();s=ifilter(p.__rmod__,s);yield p
It will generate quite a large number of primes before blowing up (at
least 50,000 primes, p=611,957) and it's much faster than the other
submissions thus far that can generate a more or less arbitrary number
of primes. It's still much slower than Alex Martelli's version in the
cookbook though.
[And yes I know that you can shave off one character by importing
ifilter as i, but that's too much ick for too little gain. There may
well be other, more fruitful ways to compact it though]
-tim
More information about the Python-list
mailing list