📜  埃拉托色尼筛法的Python程序

📅  最后修改于: 2022-05-13 01:56:56.327000             🧑  作者: Mango

埃拉托色尼筛法的Python程序

埃拉托色尼筛法是一种查找所有素数的方法,直到(可能包括)给定的自然数。这种方法在相对较小的情况下效果很好,允许我们确定任何小于或等于的自然数是素数还是合数。

给定一个数 n,打印所有小于或等于 n 的素数。还假设n是一个小数。
例如,如果 n 为 10,则输出应为“2, 3, 5, 7”。如果 n 为 20,则输出应为“2, 3, 5, 7, 11, 13, 17, 19”。

Python3
''' Python program to print all primes smaller than or equal to
 n using Sieve of Eratosthenes'''
 
def SieveOfEratosthenes(n):
     
    '''Create a boolean array "prime[0..n]" and initialize
     all entries it as true. A value in prime[i] will
     finally be false if i is Not a prime, else true.'''
    prime = [True for i in range(n + 1)]
    p = 2
    while (p * p <= n):
         
        # If prime[p] is not changed, then it is a prime
        if (prime[p] == True):
             
            # Update all multiples of p
            for i in range(p ** 2, n + 1, p):
                prime[i] = False
        p += 1
    prime[0]= False
    prime[1]= False
    # Print all prime numbers
    for p in range(n + 1):
        if prime[p]:
            print (p,end=' ') #Use print(p) for python 3
 
# driver program
if __name__=='__main__':
    n = 30
    print ("Following are the prime numbers smaller", end=' ')
    #Use print("Following are the prime numbers smaller") for Python 3
    print ("than or equal to", n)
    #Use print("than or equal to", n) for Python 3
    SieveOfEratosthenes(n)


输出:

Following are the prime numbers below 30
2 3 5 7 11 13 17 19 23 29

有关更多详细信息,请参阅有关 Eratosthenes 筛的完整文章!