为了确定一个数是否是素数,有一个筛子和素数检验。# for large numbers, xrange will throw an error.
# OverflowError: Python int too large to convert to C long
# to get over this:
def mrange(start, stop, step):
while start < stop:
yield start
start += step
# benchmarked on an old single-core system with 2GB RAM.
from math import sqrt
def is_prime(num):
if num == 2:
return True
if (num < 2) or (num % 2 == 0):
return False
return all(num % i for i in mrange(3, int(sqrt(num)) + 1, 2))
# benchmark is_prime(100**10-1) using mrange
# 10000 calls, 53191 per second.
# 60006 function calls in 0.190 seconds.
这似乎是最快的。有另一个版本使用not any,您可以看到def is_prime(num)
# …
return not any(num % i == 0 for i in mrange(3, int(sqrt(num)) + 1, 2))
然而,在基准测试中,我在测试100**10-1是否是素数时,得到了70006 functio