Skip to content

Instantly share code, notes, and snippets.

@sergeyprokudin
Created January 11, 2019 12:30
Show Gist options
  • Save sergeyprokudin/e8e1eeb9263766cc43a05ab9190442e4 to your computer and use it in GitHub Desktop.
Save sergeyprokudin/e8e1eeb9263766cc43a05ab9190442e4 to your computer and use it in GitHub Desktop.
Compute Fibonacci Numbers with Python
def fib(n):
""" Compute nth element of a Fibonacci sequence:
1, 2, 3, 5, 8, 13, 21, ...
f(n) = f(n-1) + f(n-2)
f(0) = 0
f(1) = 1
f(2) = 1
f(3) = 2
Parameters
----------
n: uint
nth element to compute
Returns
-------
uint
Computed value of a nth element of a Fibonacci sequence.
Algorithm
---------
Algo#1: simple 2 recursive calls f(n-1), f(n-2). Not efficient - creates a tree of depth n, with 2*n elements
Algo#2: no explicit recursion, just operating on array of two elements!
0 -> [0]
1 -> [0, 1]
2 -> [1, 1]
3 -> [1, 2]
4 -> [2, 3]
....
"""
if n==0:
return 0
if n==1:
return 1
two_last = [0, 1]
for i in range(2, n+1):
curr = two_last[0] + two_last[1]
two_last[0] = two_last[1]
two_last[1] = curr
return two_last[1]
for i in range(0, 100):
print(fib(i))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment