Skip to content

Instantly share code, notes, and snippets.

@ryancole
Created September 25, 2014 03:29
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 ryancole/78f2abe44674ef3f3840 to your computer and use it in GitHub Desktop.
Save ryancole/78f2abe44674ef3f3840 to your computer and use it in GitHub Desktop.
fibonacci
function fibonacci (n) {
return n < 2 ? n : fibonacci(n - 1) + fibonacci(n - 2);
};
var fibonacci_memo = (function () {
var memo = [0,1];
function fib (n) {
var result = memo[n];
if (typeof result !== 'number') {
result = fib(n - 1) + fib(n - 2);
memo[n] = result;
}
return result;
};
return fib;
}());
for (var i = 0; i <= 40; i += 1) {
console.log('// ' + i + ': ' + fibonacci(i));
}
for (var i = 0; i <= 40; i += 1) {
console.log('// ' + i + ': ' + fibonacci_memo(i));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment