Этот простой генератор не использует много памяти.Это тоже не очень быстро.
def gcd(a, b):
rem = a % b
while rem != 0:
a = b
b = rem
rem = a % b
return b
def primegen():
yield 2
yield 3
yield 5
yield 7
yield 11
accum = 2*3*5*7
out = file('tmp_primes.txt', 'w')
inp = file('tmp_primes.txt', 'r+')
out.write('0x2\n0x3\n0x5\n0x7\n0xb\n')
inp.read(20)
inpos = inp.tell()
next_accum = 11
next_square = 121
testprime = 13
while True:
if gcd(accum, testprime) == 1:
accum *= testprime # It's actually prime!
out.writelines((hex(testprime), '\n'))
yield testprime
testprime += 2
if testprime >= next_square:
accum *= next_accum
nextline = inp.readline()
if (len(nextline) < 1) or (nextline[-1] != '\n'):
out.flush()
inp.seek(inpos)
nextline = inp.readline()
inpos = inp.tell()
next_accum = int(nextline, 16)
next_square = next_accum * next_accum
def next_n(iterator, n):
"""Returns the next n elements from an iterator.
>>> list(next_n(iter([1,2,3,4,5,6]), 3))
[1, 2, 3]
>>> list(next_n(primegen(), 10))
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
"""
while n > 0:
yield iterator.next()
n -= 1