Last active
June 27, 2018 17:47
-
-
Save jsphkhan/773b68bceb8500ccbdbd46124903ce00 to your computer and use it in GitHub Desktop.
Print the fibonacci series till the nth sequence. Use memoization. (JavaScript solution)
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
//Normal fibonacci - No Memoization | |
//Fib series - 1 1 2 3 5 8 13 21 34 ... | |
//O(2^n) = exponential time complexity | |
function fib(n) { | |
if(n <= 2) { | |
return 1; | |
} | |
return fib(n-2) + fib(n-1); | |
} | |
//With Memoization | |
var arr = [1,1]; //capture the first 2 numbers of the sequence | |
function fib(n) { | |
if(arr[n-1]) { //memoization | |
return arr[n-1]; | |
} else { | |
arr[n-1] = fib(n-2) + fib(n-1); //cache it | |
return arr[n-1]; | |
} | |
} | |
console.log(arr.join(' ')); | |
//Shorter form for Memoization | |
var arr = [1,1]; | |
function fib(n) { | |
return arr[n-1] || (arr[n-1] = fib(n-2) + fib(n-1)); | |
} | |
console.log(arr.join(' ')); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment