Skip to content

Instantly share code, notes, and snippets.

@Irene-123
Created May 25, 2020 05:49
Show Gist options
  • Save Irene-123/e397c1de3c6d63331d70cef9b69f6da0 to your computer and use it in GitHub Desktop.
Save Irene-123/e397c1de3c6d63331d70cef9b69f6da0 to your computer and use it in GitHub Desktop.
Efficient algorithm for computing nth fibbonacci number
```python3
#code contributed by kirti purohit.
#time complexity O(n)
#which is much more efficient than the naive algorithm having a time complexity of O(2**n)
def fib(n,memo):
result=0
if memo[n] is not None:
return memo[n]
if n==1 or n==2:
result=1
else:
result=fib(n-1,memo)+fib(n-2,memo)
memo[n]=result
return result
def fib_memo(n):
memo = [None] * (n + 1)
return fib(n, memo)
if __name__ == '__main__':
n=int(input())
print(fib_memo(n))
```
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment