Skip to content

Instantly share code, notes, and snippets.

@ryancole
Created September 25, 2014 03:36
Show Gist options
  • Save ryancole/71fed8edc2610d53e351 to your computer and use it in GitHub Desktop.
Save ryancole/71fed8edc2610d53e351 to your computer and use it in GitHub Desktop.
factorial
function factorial (n) {
return n <= 1 ? 1 : n * factorial(n - 1);
};
var factorial_memo = (function () {
var memo = [1];
function fac (n) {
var result = memo[n];
if (typeof result !== 'number') {
result = n * fac(n - 1);
memo[n] = result;
}
return result;
};
return fac;
}());
for (var i = 0; i <= 40; i += 1) {
console.log('// ' + i + ': ' + factorial(i));
}
for (var i = 0; i <= 40; i += 1) {
console.log('// ' + i + ': ' + factorial_memo(i));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment