function fibonacci(n)

{

if (n==0) return 0;

if (n==1) return 1;

var r1 = 0; //f0

var r2 = 1; //f1

var result = 0;

/* this work too

n = n-2

while ( n-- >= 0 )

{

result = r1 + r2;

r1 = r2;

r2 = result

}

*/

var i;

for ( i=2;i<=n;++i)

{

result = r1+r2;

r1=r2;

r2=result;

}

return result;

}

alert(fibonacci(10));

## No comments:

Post a Comment