Skip to content

Instantly share code, notes, and snippets.

@rohit-jamuar
Last active August 29, 2015 14:03
Show Gist options
  • Save rohit-jamuar/6c36e4d5f73152b57710 to your computer and use it in GitHub Desktop.
Save rohit-jamuar/6c36e4d5f73152b57710 to your computer and use it in GitHub Desktop.
Function to get the nth Fibonacci term in linear time and constant space.
def get_n_th_fibo(n):
'''
Returns the nth term of the fibonacci sequence - {0, 1, 1, 2, ...}
F(n) = F(n-1) + F(n-2) where n>=2
F(0) = 0
F(1) = 1
'''
if n == 0:
return 0
elif n in [1, 2]:
return 1
a, b = 1, 1
while n>2:
a, b = b, a+b
n -= 1
return b
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment