【发布时间】:2018-05-01 19:57:05
【问题描述】:
我试图从这个答案中实现第一个 is_prime 函数: https://stackoverflow.com/a/17298131/6208280
# 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))
但我在测试大量数字时遇到了一点问题。
对于非常大的数字,我收到溢出错误:long int too large to convert to float
我检查了浮动的最大值:
sys.float_info.max
1.7976931348623157e+308
对于is_prime(10**308),一切正常...但例如is_prime(10**309) 会出现这个溢出错误(因为float max?)。
这是否意味着 1.7976931348623157e+308 是这种 is_prime() 函数的限制,或者是否有任何解决方案可以使用 is_prime() 函数检查更高的数字?
在我看来,诸如“使用小数”之类的解决方案并不能真正解决问题,因为素数检查功能需要的精度不足?
【问题讨论】:
-
这意味着
(sys.float_info.max - ϵ) ** 2是极限,因为您正在调用sqrt(num)。有“整数平方根算法”可以避开任何使用浮点数,可能像this one -
您有没有想过要检查一个 308 位数字是否为质数需要多少操作,以及需要多长时间?对于 20 位数字,您的函数已经太慢了,更不用说 300 位数字了。
标签: python algorithm int precision primes