Problem
This problem comes from Project Euler 25
Problem
The Fibonacci sequence is defined by the recurrence relation:
, where and
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 = 144The 12th term, , is the first term to contain three digits.
What is the index of the first term in the Fibonacci sequence to contain 1000 digits?
Code
# Project Euler: Problem 25
# 1000-digit Fibonacci number
i = 1
length = 0
F_n_2 = 0
F_n_1 = 1
while length < 1000:
F_n = F_n_1 + F_n_2
F_n_2 = F_n_1
F_n_1 = F_n
length = len(str(F_n))
i += 1
print(i)
Solution
Nothing complicated here.
- Calculate the current Fibonacci number
- Convert to a string and check the string length
- If the string length is greater than 1000, we’re done
- If not, calculate the next Fibonacci number