Discuss / Python / 说一下这个神奇的素数过滤其,有不对的地方请指出

说一下这个神奇的素数过滤其,有不对的地方请指出

Topic source

首先,列出从2开始的所有自然数,构造一个序列:

2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, ...

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

这里创建一个自然数生成器,3,5,7,9...... ;可以说是奇数生成器

之所以这样是为了省时间把,所有的偶数肯定不是素数

取新序列的第一个数3,它一定是素数,然后用3把序列的3的倍数筛掉:

5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, ...

it = _odd_iter()
n = next(it)
it = filter(_not_divisible(n), it)

第一次循环正对应如上这一句话

现在的 变量it = filter("**非3倍数 ** Iterator","奇数 Iterator")

取新序列的第一个数5,然后用5把序列的5的倍数筛掉:

7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, ...

 n = next(it)
        yield n
        it = filter(_not_divisible(n), it)

第二次循环

变量n =  所有自然数中 下一个 非3倍数 and 是奇数 = 5

变量it =  filter("非5倍数Iterator"  , "**非3倍数Iterator  **and 奇数Iterator") 

第....次循环

变量it =  .... **非5倍数Iterator **and **非3倍数Iterator  **and 奇数Iterator

不断筛下去,就可以得到所有的素数。

不断 嵌套 下去 ,就可以得到所有的素数

不断的 增加 and ,就可以得到所有的素数


  • 1

Reply