【发布时间】:2017-02-27 10:22:55
【问题描述】:
我知道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
【问题讨论】:
-
非常相关,但不完全相同:stackoverflow.com/q/2068372/1639625
-
你不能只是走进 Python 教堂并说 “它像泥土一样慢”.. 即使是这样。
-
可以使用Miller-Rabin过滤、Pocklington测试等
标签: python performance python-2.7 math primes