// 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;
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.