用filter求素数

 

计算素数的一个方法是埃氏筛法,函数

 

全部的奇数:spa

def _odd_iter():
    n = 1
    while True:
        n = n + 2
        yield n

定义一个筛选函数:code

def _not_divisible(n):
    return lambda x : x % n > 0

定义一个筛选器,不断返回下一个素数:blog

def primes():
    yield 2
    it = _odd_iter()
    while True:
        n = next(it)
        yield n
        it = filter(_not_divisible(n), it)

求1000之内的素数:it

for n in primes():
    if n < 100:
        print(n)
    else:
        break

结果以下:class

 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--lambda

相关文章
相关标签/搜索