λ Greatest common divisor

======= Algorithm ======= <syntax js> function gcd(a, b) { if (b === 0) { return a; } return gcd(b, a % b); } </syntax> ======= Support ======= <syntax js> function run(args) { delete result; result = gcd(args.a, args.b); } </syntax> ======= Tests ======= <syntax js> function testSimple() { assert( gcd(42, 56) === 14 ); assert( gcd(56, 42) === 14 ); assert( gcd(9, 28) === 1 ); }</syntax> ======= Options ======= <syntax js> { "title": "Greatest common divisor", "height":"250px" } </syntax> ======= Visualisation ======= <syntax html> <html> <head> <style type="text/css"> input {width:50px;} td {padding-left:5px;padding-right:5px} </style> <script type="text/javascript"> function globals() { // clear out result return {result:undefined}; } function update(n, x, isRunning, duration, prev) { var element = document.getElementById("table"); var a = x.lookupInScope("a"); var b = x.lookupInScope("b"); var result = x.lookupInScope("result"); var newPrev = prev; if (typeof result === "undefined") { if (x.stack.length > element.children.length) { var tr = document.createElement('tr'); tr.innerHTML = "<td>"+a+"</td><td>"+b+"</td>"; element.appendChild(tr); newPrev = function() { element.removeChild(tr); prev(); }; } } else {//if (!element.answer) { var tr = document.createElement('tr'); tr.innerHTML = "<td>= "+result+"</td><td></td>"; element.appendChild(tr); //element.answer = true; newPrev = function() { //element.answer=false; element.removeChild(tr); prev(); }; } return newPrev; } function change() { var element = document.getElementById("table"); var children = element.children; for (var i=children.length-1; i>0; i--) { element.removeChild(children[i]); } reset(); } function args() { var a = parseInt(document.getElementById('a').value); var b = parseInt(document.getElementById('b').value); return {a:a, b:b}; } </script> </head> <body> <table><tbody id="table"> <tr><td>a: <input id="a" value=12 onchange="change()"></td><td>b: <input id="b" value=90 onchange="change()"></td></tr> </tbody></table> </body> </html> </syntax>