Karl Knechtel's answer is correct, but sluggish; the problem is that to_use is moving too far and too early.
Here is my modified version - I removed the comments.
class prime_list(): def __init__(self): self.primes = [2] self.to_use = 0 def test(self, candidate): next = self.primes[self.to_use] if candidate >= next * next: self.to_use += 1 print candidate, next return all(candidate % p != 0 for p in self.primes[:self.to_use]) def __iter__(self): import itertools for candidate in itertools.count(3,2): if self.test(candidate): self.primes.append(candidate) yield candidate if __name__ == "__main__": my_primes = prime_list() # print my_primes.primes[0] for p in my_primes: print "Generated:", p if p > 1000000: break sum += p print "Number of primes generated:", len(my_primes.primes)
source share