A unit fraction contains 1 in the numerator. The decimal representation of the unit fractions with denominators 2 to 10 are given:
1/2 = 0.5 1/3 = 0.(3) 1/4 = 0.25 1/5 = 0.2 1/6 = 0.1(6) 1/7 = 0.(142857) 1/8 = 0.125 1/9 = 0.(1) 1/10 = 0.1 Where 0.1(6) means 0.166666..., and has a 1-digit recurring cycle. It can be seen that 1/7 has a 6-digit recurring cycle.
Find the value of d < 1000 for which 1/d contains the longest recurring cycle in its decimal fraction part. Note: http://www.mathblog.dk/project-euler-26-find-the-value-of-d-1000-for-which-1d-contains-the-longest-recurring-cycle/ For any deminator (d) there can only be up to (d-1) potential remainders. as soon as you see a repeat, you will get the same remainder
In [29]:
top = 1000
#top = 10
biggie, answer = 0, 0
def calcremains(num):
remain = 1 % num
found = set()
for y in range(1,num):
found.add(remain)
remain = (remain * 10) % num
if remain == 0:
return(found)
return(found)
for x in range(2,top):
temp = len(calcremains(x))
if biggie < temp:
biggie = temp
answer = x
print(answer, biggie)
Problem 25 The Fibonacci sequence is defined by the recurrence relation:
Fn = Fn−1 + Fn−2, where F1 = 1 and F2 = 1. Hence the first 12 terms will be:
F1 = 1 F2 = 1 F3 = 2 F4 = 3 F5 = 5 F6 = 8 F7 = 13 F8 = 21 F9 = 34 F10 = 55 F11 = 89 F12 = 144 The 12th term, F12, is the first term to contain three digits.
What is the index of the first term in the Fibonacci sequence to contain 1000 digits? Note: Go ahead and calculate Whie I did not use this, it is an interesting view on python - https://technobeans.com/2012/04/16/5-ways-of-fibonacci-in-python/
In [10]:
def fib(num,last,lastlast):
if num == 0:
return(0)
elif num == 1:
return(1)
else:
total = last + lastlast
return(total)
last, lastlast,x = 0,0,0
done = False
while not done:
temp = fib(x,last,lastlast)
if (len(str(temp)) < 1000):
last = lastlast
lastlast = temp
x += 1
else:
print(x, temp)
done = True
In [ ]: