Created
May 25, 2020 05:49
-
-
Save Irene-123/e397c1de3c6d63331d70cef9b69f6da0 to your computer and use it in GitHub Desktop.
Efficient algorithm for computing nth fibbonacci number
This file contains hidden or 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
| ```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