factorial
parital week 4 tutorial solution
by Alvan
HTML
<div id="result">
</div>
CSS
th {color: blue;}
.n {color: red}
.factorial {color: green;}
JavaScript
// Compute n! using a recursive function
function factorialRecursive (n) {
var value;
if (n==0)
value = 1;
else if (n>0)
value = factorialRecursive(n-1) * n;
return value;
}
// Compute n! using an iterative function
function factorialIterative (n) {
var value;
if (n >= 0) {
value = 1;
for (var i=2 ; i<=n; i++)
value *= i;
}
return value;
}
function factorialTable(maxN, fact) {
//start off the table
var HTML="<table>";
// Add the header
HTML += "<th> n </th>";
HTML += "<th> n! </th>";
// Loop through up to and including hte last value in the table
for (var n=0 ; n<=maxN ; n++) {
HTML += "<tr>";
HTML += "<td class='n'> " + n + " </td>";
var nf = fact(n);
HTML += "<td class='factorial'> " + nf + " </td>";
HTML += "</tr>";
}
// Finish up.
HTML += "</table>";
return HTML;
}
// Get results for the recursive solution"
var HTML = "<h2> Recursive Solution </h2>";
HTML += factorialTable(10, factorialRecursive);
// Get the results for the iterative solution
HTML += "<h2> Iterative Solution </h2>";
HTML += factorialTable(10, factorialIterative);
// Display the results
document.getElementById("result").innerHTML = HTML;