Project Euler

Pandigital Fibonacci ends

Problem 104

The Fibonacci sequence is defined by the recurrence relation:

Fn = Fn−1 + Fn−2, where F1 = 1 and F2 = 1.

It turns out that F541, which contains 113 digits, is the first Fibonacci number for which the last nine digits are 1-9 pandigital (contain all the digits 1 to 9, but not necessarily in order). And F2749, which contains 575 digits, is the first Fibonacci number for which the first nine digits are 1-9 pandigital.

Given that F*k* is the first Fibonacci number for which the first nine digits AND the last nine digits are 1-9 pandigital, find k.


In [1]:
def fibonacci():
    a, b = 0, 1
    while True:
        yield a
        a, b = b, a+b

In [2]:
from itertools import islice
list(islice(enumerate(fibonacci()), 10))


Out[2]:
[(0, 0),
 (1, 1),
 (2, 1),
 (3, 2),
 (4, 3),
 (5, 5),
 (6, 8),
 (7, 13),
 (8, 21),
 (9, 34)]

In [3]:
i = 29348710948704982734509283745029348572309458723049
s = str(i)
s0 = s[:9]
s1 = s[-9:]
s0, s1, set(s0), set(s0) - set('0'), len(set(s0) - set('0')), len(set(s0[:5]) - set('0'))


Out[3]:
('293487109',
 '458723049',
 {'0', '1', '2', '3', '4', '7', '8', '9'},
 {'1', '2', '3', '4', '7', '8', '9'},
 7,
 5)

In [4]:
def is_pandigital(s):
    return len(set(s) - set('0')) == 9

In [5]:
def foo():
    for i, f in enumerate(fibonacci()):
        s = str(f)
        if is_pandigital(s[-9:]):
            return i

In [6]:
foo()


Out[6]:
541

In [7]:
def foo():
    for i, f in enumerate(fibonacci()):
        s = str(f)
        if is_pandigital(s[:9]):
            return i

In [8]:
foo()


Out[8]:
2749

In [9]:
def foo():
    for i, f in enumerate(fibonacci()):
        s = str(f)
        if is_pandigital(s[:9]) and is_pandigital(s[-9:]):
            return i

In [10]:
# foo()

# This took far too long, so I had to refactor for speed.

In [11]:
def foo():
    n = 10 ** 9
    for i, f in enumerate(fibonacci()):
        if is_pandigital(str(f % n)) and is_pandigital(str(f)[:9]):
            return i

In [12]:
%timeit foo()
foo()


1 loop, best of 3: 32.3 s per loop
Out[12]:
329468