ZLA
AST

Problem 25 - 1000-digit Fibonacci Number

Project Euler
Post Image
March 11, 2024
Read Time: 1 min

Problem

This problem comes from Project Euler 25

Problem

The Fibonacci sequence is defined by the recurrence relation:

Fn=Fn1+Fn2 F_n = F_{n-1} + F_{n-2}, where F1=1 F_1 = 1 and F2=1 F_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, F12 F_{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. (I say stuff like this a lot don’t I? Trust me, me not that smaht)

  1. Calculate the current Fibonacci number Fn F_n
  2. Convert Fn F_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