Elt*_*ooo 5 python math exp gmpy
我刚刚遇到了声称被谷歌 2004 年使用的挑战之一
(the first 10-digit prime in e).com
Run Code Online (Sandbox Code Playgroud)
除此之外,我想接受挑战并用 python 解决它
>>> '%0.52f' % math.exp(1)
'2.71828182845904509079**5598298427**6488423347473144531250'
>>> '%0.52f' % numpy.exp(1)
'2.71828182845904509079**5598298427**6488423347473144531250'
Run Code Online (Sandbox Code Playgroud)
我的程序返回的5598298427是一个素数
上网查了一下,正确答案是7427466391
但是 python 中的 exp 数字不包括上面的数字
import numpy
import math
def prime(a):
if a == 2: return True
if a % 2 == 0: return False
if a < 2: return False
i = 2
n = math.sqrt(a) + 1
while(i < n):
if a % i == 0:
return False
i += 1
return True
def prime_e():
e = '%0.51f' % math.exp(1)
e = e.replace("2.","")
for i in range(len(e)):
x = int(e[i:10+i])
if prime(x):
return [i, x]
print prime_e()
Run Code Online (Sandbox Code Playgroud)
那么我做错了什么吗?
编辑:使用 gmpy2
def exp():
with gmpy2.local_context(gmpy2.context(), precision=100) as ctx:
ctx.precision += 1000
return gmpy2.exp(1)
Run Code Online (Sandbox Code Playgroud)
742746639199次迭代后返回
实际e(欧拉常数)值为
http://www.gutenberg.org/files/127/127.txt
2.71828182845904523536028747135266249775724709369995957496696762772407663035354759457138217852516642 7427466391 93200305992 1817413596629043572900334295260595630...
所以挑战的正确答案是7427466391。您无法通过以下方式计算所需精度的emath.exp(1)