版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/w144215160044/article/details/79895936
把廖雪峰网站的描述稍微修改了一下:
计算素数的一个方法是埃式筛法,它的算法理解起来非常简单:
首先,构造出一个奇数序列:
3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25...
先返回2
取序列的第一个数3
,它一定是素数,返回3,然后用3
把序列的3
的倍数筛掉:
5, 7, 11, 13, 17, 19, 23, 25, ...
取新序列的第一个数5
,返回5,然后用5
把序列的5
的倍数筛掉:
7, 11, 13, 17, 19, 23, ...
不断筛下去,就可以得到所有的素数
......
def is_odd():
n = 1
while True:
n += 2
yield n
def not_divisible(n):
return lambda x: x % n > 0 #lambda相当于一个简洁的函数,其中x是参数
def is_prime():
yield 2
L = is_odd()
while True:
n = next(L)
yield n
L = filter(not_divisible(n), L) #n传进去的n相当于函数体内的x值
for x in is_prime():
if x < 100:
print(x)
else:
break