求埃拉託斯特尼篩法的 Python 程式


在本文中,我們將瞭解下面給出的問題陳述的解決方案。

問題陳述 − 給定一個數字 n,我們需要打印出所有小於或等於 n 的質數。約束:n 是一個較小的數字。

現在,讓我們在下面的實現中觀察解決方案 −

示例

def SieveOfEratosthenes(n):
   # array of type boolean with True values in it
   prime = [True for i in range(n + 1)]
   p = 2
   while (p * p <= n):
      # If it remain unchanged it is prime
      if (prime[p] == True):
         # updating all the multiples
         for i in range(p * 2, n + 1, p):
            prime[i] = False
      p += 1
   prime[0]= False
   prime[1]= False
   # Print
   for p in range(n + 1):
      if prime[p]:
         print (p,end=" ")
# main
if __name__=='__main__':
   n = 33
   print ("The prime numbers smaller than or equal to", n,"is")
   SieveOfEratosthenes(n)

輸出

The prime numbers smaller than or equal to 33 is
2 3 5 7 11 13 17 19 23 29 31

所有變數都在區域性範圍內宣告,上圖中可以看到它們的引用。

結論

在本文中,我們學習瞭如何編寫一個用於埃拉託斯特尼篩法的 Python 程式

更新日期: 20-Dec-2019

2K+ 閱讀

啟動你的 事業

完成課程獲得認證

開始
廣告
© . All rights reserved.