User Tools

Site Tools


λ Factorial - recursive

======= Algorithm ======= <syntax js> function fac(x) { if (x === 0) { return 1; } return x * fac(x-1); } </syntax> ======= Support ======= <syntax js> function run() { return fac(50); } </syntax> ======= Tests ======= <syntax js> function testTen() { assert (fac(10) === 3628800, "fac(10)"); } function testSeven() { assert (fac(7) === 5040 , "fac(7)"); }</syntax> ======= Options ======= <syntax js> { "title":"Factorial - recursive", "height":"150px" } </syntax> ======= Visualisation ======= <syntax html> <html> <head> <script type="text/javascript"> var hasAnswer = false; function update(n, x) { var element = document.getElementById("container"); var html = ""; // recurse down stack var stack = x.stack; for (var i=stack.length-1; i>=0; i--) { var a = stack[i].lookupInScope("x"); if (a) { html = a+" * "+html; } } var r = x.returnedValue; if (r) { var a = x.lookupInScope("x"); if (a) { html = html + a + " * "; } html = html + r; } else { var a = x.lookupInScope("x"); if (!a) a = 50; html = html + "fac("+a+")"; } element.innerHTML = html; } </script> </head> <body id="container" style="height:150px"> </body> </html> </syntax>

algorithm/factorial_recursive.txt · Last modified: 2015/02/02 08:28 (external edit)