I was solving problem 26 on Project Euler where I need to calculate the length of the recurring part of 1/n where n is all integers between 1 and 1000, and see which number makes the longest recurring part. That meant that I needed my division done a lot more precisely. So I was playing around with my decimal precision by changing getContext().prec, but then somehow increasing the accuracy made the program a lot faster. I ran this program using Python 3.7. Here is the code:
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)
This was the result when I used precision of 500:
>>> print(answer)
349
>>> print(time.time() - s)
2.923844575881958
...and this is what I got when I used precision of 5000:
>>> print(answer)
983
>>> print(time.time() - s)
0.07812714576721191
I swapped 500 with 5000, and not only did it give me the correct answer since the recurring part of 1/answer was probably longer than 500, but it also was much faster. I have tried this with an online Python interpreter, and it also gave me similar result. Why is it like this?
