Skip to content

Instantly share code, notes, and snippets.

@scriptonian
Created March 14, 2018 02:50
Show Gist options
  • Save scriptonian/5b1cc8fc0ae006d88cbd62d719f54ddb to your computer and use it in GitHub Desktop.
Save scriptonian/5b1cc8fc0ae006d88cbd62d719f54ddb to your computer and use it in GitHub Desktop.
Factorial using Dynamic Programming
/*
* USING RECURSION
*/
function factorialRecursion(n) {
if(n === 0 || n === 1) {
return 1;
}
return n * factorialRecursion(n - 1);
}
var recSum = factorialRecursion(5);
console.log(recSum);
/*
* USING DYNAMIC PROGRAMMING
*/
function factorialDP(n) {
//define table to hold values - DP
var table = [];
//base case
table[0] = 1;
for(var i = 1; i <= n; i++) {
//use the value stored in the previos slot
table[i] = i * table[i - 1];
}
//return final slot value
return table[n];
}
var dpSum = factorialDP(5);
console.log(dpSum);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment