tvl-depot/scratch/facebook/interview-cake/nth-fibonacci.py
William Carroll 417d3b5fff Implement a bottom-up fibonacci
The bottom-up solution run in O(n) time instead of O(2^n) time, which the
recursive solution runs as:

```
def fib(n):
    return fib(n - 2) + fib(n - 1)
```

Remember that exponential algorithms are usually recursive algorithms with
multiple sibling calls to itself.
2020-11-21 14:48:12 +00:00

6 lines
122 B
Python

def fib(n):
cache = (0, 1)
for _ in range(n):
a, b = cache
cache = (b, a + b)
return cache[0]