dilluns, 5 de març del 2012

Fibonacci

Here's a divertimento motivated by a twit @Monica_Usart.

It computes (using Javascript) the first n elements of the fibonacci sequence.





Number of elements in the sequence:




The code is straighforward:

< script language="javascript">
function fibonum( x)
{
a=""; for (i=1; i <= x; i++) { if (i > 1) a +=","; a+= fibo(i) }; return a;
}

function fibo(n)
{
if (n==1) return 1;if (n == 2) return 2; return fibo(n-1)+ fibo(n-2);
}

function dofibo()
{ document.getElementById("result").innerHTML=fibonum(document.getElementById("iter").value);
}



< form action="#">
< input type="button" value="Compute Fibonnaci" onclick="javascript:dofibo()">
Number of elements in the sequence: < input name="iter" id="iter" type="text" value="1">
< textarea name="result" id="result" rows="10" cols="80">press 'Compute Fiboonacci' to get the fibonacci sequence < /textarea>
< /script>< /form>