Published: March 5, 2024

Project Euler

Problem 25 - 1000-digit Fibonacci Number

Problem

This problem comes from Project Euler 25

Problem

The Fibonacci sequence is defined by the recurrence relation:

Fn=Fn1+Fn2F_n = F_{n-1} + F_{n-2} , where F1=1F_1 = 1 and F2=1F_2 = 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, F12F_{12} , 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.

  1. Calculate the current Fibonacci number FnF_n
  2. Convert FnF_n to a string and check the string length
  3. If the string length is greater than 1000, we’re done
  4. If not, calculate the next Fibonacci number