Python 找質數 ( Python: Prime Numbers Finding )

若您覺得文章寫得不錯,請點選文章上的廣告,來支持小編,謝謝。

維基百科上質數的定義為:
「指在大於1的自然數中,除了1和該數自身外,無法被其他自然數整除的數(也可定義為只有1與該數本身兩個因數的數)」

一個著名且有效率的方法:Sieve of Eratosthenes

用 Python 來實現 Sieve of Eratosthenes:
def eratosthenes(n):
P = [i for i in range(2, n+1)]
p = 0
while True:
for i in P[p + 1:]:
if i % P[p] == 0:
P.remove(i)
if P[p]**2 >= P[-1]:
break
p += 1
return P
aNumber = (int)(input("Enter a number:"));
print (eratosthenes(aNumber))
view raw PrimeNumber.py hosted with ❤ by GitHub


沒有留言: