您的位置:首页 > 其它

筛选法求全体素数

2016-03-24 19:16 686 查看

计算素数的一个方法是埃氏筛法,它的算法理解起来非常简单,参考《廖雪峰的python教程》:

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) # 构造新序列

def print_prime(num):
# 打印num以内的素数:
for n in primes():
if n < num:
print(n)
else:
break

if __name__ == '__main__':
n=int(input("please input an integer:"))
print_prime(n)


注意到Iterator是惰性计算的序列,所以我们可以用Python表示“全体自然数”,“全体素数”这样的序列,而代码非常简洁。

埃氏筛选法算法描述

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: