產生無限素數級數的有效方法是使用埃拉托斯特尼篩法,它透過迭代標記非素數的倍數來消除非素數。雖然這種方法很有效,但它需要大量記憶體來儲存標記的數字。
erat2
這是Python 標準庫說明書中的erat2 函數,可以是用來產生無限級數的素數數字:
import itertools as it def erat2( ): D = { } yield 2 for q in it.islice(it.count(3), 0, None, 2): p = D.pop(q, None) if p is None: D[q*q] = q yield q else: # old code here: # x = p + q # while x in D or not (x&1): # x += p # changed into: x = q + 2*p while x in D: x += 2*p D[x] = p
erat2a
erat2函數可以透過避免不必要的檢查來進一步最佳化:
import itertools as it def erat2a( ): D = { } yield 2 for q in it.islice(it.count(3), 0, None, 2): p = D.pop(q, None) if p is None: D[q*q] = q yield q else: # old code here: # x = p + q # while x in D or not (x&1): # x += p # changed into: x = q + 2*p while x in D: x += 2*p D[x] = p
erat3
為了獲得更快的效能,erat3 函數需要優點是所有素數(2 、3 和5 除外)模30 只得出八個特定數字。這顯著減少了篩選過程中所需的檢查數量:
import itertools as it def erat3( ): D = { 9: 3, 25: 5 } yield 2 yield 3 yield 5 MASK= 1, 0, 1, 1, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, MODULOS= frozenset( (1, 7, 11, 13, 17, 19, 23, 29) ) for q in it.compress( it.islice(it.count(7), 0, None, 2), it.cycle(MASK)): p = D.pop(q, None) if p is None: D[q*q] = q yield q else: x = q + 2*p while x in D or (x%30) not in MODULOS: x += 2*p D[x] = p
這些最佳化可以顯著提高效能,尤其是在產生較大素數時。
以上是如何在Python中高效生成無限素數流?的詳細內容。更多資訊請關注PHP中文網其他相關文章!