计算素数的一个方法是埃氏筛法,
所有的奇数:
def _odd_iter(): n = 1 while True: n = n + 2 yield n
定义一个筛选函数:
def _not_divisible(n): return lambda x : x % n > 0
定义一个筛选器,不断返回下一个素数:
def primes(): yield 2 it = _odd_iter() while True: n = next(it) yield n it = filter(_not_divisible(n), it)
求1000以内的素数:
for n in primes(): if n < 100: print(n) else: break
结果如下:
1 2 2 3 3 5 4 7 5 11 6 13 7 17 8 19 9 23 10 29 11 31 12 37 13 41 14 43 15 47 16 53 17 59 18 61 19 67 20 71 21 73 22 79 23 83 24 89 25 97
--over--