Skip to content

Instantly share code, notes, and snippets.

@jsphkhan
Last active June 27, 2018 17:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jsphkhan/773b68bceb8500ccbdbd46124903ce00 to your computer and use it in GitHub Desktop.
Save jsphkhan/773b68bceb8500ccbdbd46124903ce00 to your computer and use it in GitHub Desktop.
Print the fibonacci series till the nth sequence. Use memoization. (JavaScript solution)
//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