我在Project Euler上解决问题26,我需要计算1/n的重复部分的长度,其中n是1到1000之间的所有整数,并且看哪个数字是最长的重复部分.这意味着我需要更精确地完成我的部门.所以我通过更改来调整我的小数精度getContext().prec,但是以某种方式提高精度使程序更快.我使用Python 3.7运行了这个程序.这是代码:
import re
import time
s = time.time()
from decimal import *
getcontext().prec = 500 #This part
recurring = 0
answer = 0
p = re.compile(r"([0-9]+?)\1{3,}")
for i in range(1, 1000):
f = p.search(str(Decimal(1) / Decimal(i))[5:])
if f:
number = f.group(1)
if len(str(number)) > len(str(recurring)):
recurring = number
answer = i
print(answer)
print(time.time() - s)
Run Code Online (Sandbox Code Playgroud)
这是我使用500的精度时的结果:
>>> print(answer)
349
>>> print(time.time() - s)
2.923844575881958
Run Code Online (Sandbox Code Playgroud)
......这就是我使用5000的精度时得到的:
>>> print(answer)
983
>>> print(time.time() - s)
0.07812714576721191
Run Code Online (Sandbox Code Playgroud)
我用500交换500,不仅因为1/answer的重复部分可能超过500而给了我正确的答案,但它也快得多.我用在线Python解释器试过这个,它也给了我类似的结果.为什么会这样?