100 XP

27. The nth Fibonacci number

Advanced recursion dynamic programming

The Fibonacci numbers are a sequence that starts with 0 and 1. Each number after that is the sum of the two before it:

0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, ...

Write a function fib(n) that takes a whole number n and returns the Fibonacci number at position n, counting from 0: fib(0) is 0, fib(1) is 1 and fib(2) is 1.

It must be fast. n goes up to 90, and the plain recursive version, fib(n - 1) + fib(n - 2), would take years to get there: it works out the same numbers again and again. Your code has to answer fib(90) in well under a second.

Example 1

Inputn = 0
Output0
ExplanationThe sequence starts with 0.

Example 2

Inputn = 10
Output55
ExplanationCounting from 0, position 10 holds 55.

Example 3

Inputn = 6
Output8
Explanation0, 1, 1, 2, 3, 5, 8: position 6 is 8.

Constraints

  • n is a whole number from 0 to 90.
  • The answer can be big (fib(90) has 19 digits), but Python's whole numbers hold it exactly.

Submit also runs 4 more tests you can't see.

Practises Recursion (lesson 20).

Code
def fib(n):
    """Return the nth Fibonacci number, quickly.

    n: int, from 0 to 90
    Returns: int, where fib(0) is 0, fib(1) is 1, and each
        next one is the sum of the two before it
    """
    # Write your code here
    pass