The Fibonacci sequence is defined by the recurrence relation:

F*n* = F*n*−1 + F*n*−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 first term in the Fibonacci sequence to contain 1000 digits?


In [1]:
from euler import gen_fibonacci, gen_lte

In [2]:
list(gen_lte(gen_fibonacci(), 100))


Out[2]:
[1, 2, 3, 5, 8, 13, 21, 34, 55, 89]

In [3]:
def gen_fib2():
    yield 1
    for i in gen_fibonacci():
        yield i

In [4]:
list(gen_lte(gen_fib2(), 100))


Out[4]:
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]

In [5]:
def gen_fib3():
    yield 0
    yield 1
    for i in gen_fibonacci():
        yield i

In [6]:
list(gen_lte(gen_fib3(), 100))


Out[6]:
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]

In [7]:
def foo(n):
    for i, fib in enumerate(gen_fib2(), 1):
        if len(str(fib)) >= n:
            return i

In [8]:
foo(3)


Out[8]:
12

In [9]:
%timeit foo(1000)
foo(1000)


1 loops, best of 3: 248 ms per loop
Out[9]:
4782

For extra bonus points, directly calculate the number without generating any Fibonacci numbers.

Hint: Read Knuth.


In [10]:
from math import sqrt, log, ceil

In [11]:
phi = (sqrt(5) + 1.) / 2.
def term_of_ndigits_fib(ndigits):
    return int(ceil((log(sqrt(5)) + (ndigits - 1) * log(10)) / log(phi)))

In [12]:
n = 1000
%timeit term_of_ndigits_fib(n)
term_of_ndigits_fib(n)


1000000 loops, best of 3: 1.8 us per loop
Out[12]:
4782