1. 程式人生 > >python程式設計找出對應範圍內的所有素數(質數)

python程式設計找出對應範圍內的所有素數(質數)

#找出所有的素數


#先構造一個從3開始的奇數序列
def odd_iter():
    n = 1
    while True:
        n = n+2
        yield n  #返回一個Iterator


#定義一個篩選函式,用來刪除相應素數對應倍數的數
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) #構造新序列


#由於prines()也是一個無限序列,所以呼叫時需要設定資料範圍


#列印1000以內的素數:
for n in primes():
    if n < 1000:
        print(n)
    else:
        break