Last active
August 29, 2015 14:03
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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