# λ Fibonacci - dynamic programming

======= Algorithm ======= <syntax js> function fib(n) { if (n <= 0) { return 0; } var a = 1; var b = 1; for (var i=2; i<n; i++) { // Compute the next pair of fibonacci numbers. var oldA = a; a = b; b = oldA + b; } return b; } </syntax> ======= Support ======= <syntax js> function run(args) { delete result; result = fib(args.n); } </syntax> ======= Tests ======= <syntax js> function testTen() { assert (fib(10) === 55, "fib(10)"); } function testEighteen() { assert (fib(18) === 2584 , "fib(18)"); }</syntax> ======= Options ======= <syntax js> { "title":"Fibonacci - dynamic programming", "height":"250px" } </syntax> ======= Visualisation ======= <syntax html> <html> <head> <style type="text/css"> input {width:50px;} </style> <script type="text/javascript"> function update(n, x) { var element = document.getElementById("result"); var result = x.lookupInScope("result"); var i = x.lookupInScope("i"); if (typeof result != "undefined") { element.innerHTML = "= "+result; } else if (i) { element.innerHTML = "Calculating fib("+i+")"; } else { element.innerHTML = ""; } } function args() { var n = document.getElementById('n').value; return {n:n}; } </script> </head> <body> fib( <input id="n" value=12> ) <div id="result"></div> </body> </html> </syntax>