我知道python“慢得像脏东西”,但我想做一个快速而高效的程序来找到素数。这就是我所拥有的:num = 5 #Start at five, 2 and 3 are printed manually and 4 is a multiple of 2
print("2")
print("3")
def isPrime(n):
#It uses the fact that a prime (except 2 and 3) is of form 6k - 1 or 6k + 1 and looks only at divisors of this form.
i = 5
w = 2
while (i * i <= n): #You only need to check up too the square root of n
if (n % i == 0): #If n is divisable by i, it is not a prime
return False
i += w
w = 6 - w
return True #If it isn´t ruled out by now, it is a prime
while True:
if ((num % 2 != 0) and (num % 3 != 0)): #save time, only run the function of numbers that are not multiples of 2 or 3
if (isPrime(num) == True):
print(num) #print the now proved prime out to the screen
num += 2 #You only need to check odd numbers
现在我的问题是:
-这会打印出所有的质数吗?
-这会打印出不是素数的数字吗?
-有没有更有效的方法?
-这将发展到什么程度(python的限制),有什么方法可以提高上限吗?在
使用python 2.7.12
本文介绍了一个用Python实现的高效素数检测程序。通过只检查特定形式的除数并利用素数特性,该程序能够有效地找出素数。作者提出了几个关于程序效率及改进空间的问题。
3653

被折叠的 条评论
为什么被折叠?



