Created
March 14, 2018 02:50
-
-
Save scriptonian/5b1cc8fc0ae006d88cbd62d719f54ddb to your computer and use it in GitHub Desktop.
Factorial using Dynamic Programming
This file contains hidden or 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
/* | |
* 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