1. 程式人生 > >Python 求素數

Python 求素數

#先構造一個從3開始的奇數序列
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)#構造新的序列
for n in primes():
    if n<100:
        print(n)
    else:
        break