Consider:
function fibo() {
var first, second, add;
for(var i=0; i<4000; i++) {
if(i === 0) {
first = 1;
second = 2;
}
add = first + second;
first = second;
second = add;
}
alert(add);
}
fibo();
It is not working and shows infinity. Why?
Simple: because it’s too big.
The 300th term is 222232244629420445529739893461909967206666939096499764990979600, so you might imagine how big the 4000th is. You can’t hold such value in a JavaScript variable.
If you really want to calculate it, use an arbitrary precision library, and maybe something other than JavaScript if you want to calculate it fast.
Check GNU Multiple Precision Arithmetic Library – GMP. Nice to use with C, and it even has special Fibonacci functions.
Here’s a little C program to do the job:
Compile with:
And run 🙂