Permalink
Browse files

cache primes for subsequent use in when generator is called again

  • Loading branch information...
1 parent 5a3e3bf commit d15f8ecc4cf8525a9e7971bc5eb0100773067123 @glyphobet committed Apr 5, 2012
Showing with 5 additions and 4 deletions.
  1. +5 −4 sieve.py
View
@@ -1,11 +1,12 @@
#!/usr/bin/env python
import sys
-def generate_primes():
- """A generator that yields primes forever."""
- n = 1
- primes = []
+def generate_primes(primes=[(2, 4)]):
+ """A generator that yields primes forever. Also caches primes for use in subsequent calls."""
+ for p in primes:
+ yield p
+ n, _ = primes[-1]
while True:
n += 1
if n == next(factor(n, primes)): # if n is its own (first) factor, it's prime

0 comments on commit d15f8ec

Please sign in to comment.