Write a generator, genPrimes
, that returns the sequence of prime numbers on successive calls to its next()
method: 2, 3, 5, 7, 11, ...
def genPrimes():
primes = [] # primes generated so farlast = 1 # last number tried
while True:
last += 1
for p in primes:
if last % p == 0:
break
else:
primes.append(last)
yield last
今天学到 Python 编程导论 第12讲。
用 Generator 编写质数组。
可用一个质数集合将之前的识别的质数收集起来 方便之后的质数判断。