function fibo() {
var first,second,add;
for(var i=0;i<4000;i++){
if(i === 0){
first = 1;
second = 2;
}
add = first + second;
first
Although already accepted, I think I can offer a simpler solution. Just store numbers in arrays, one digit per element, and perform addition like you did in elementary school - "in columns". It goes like this:
function add(a, b) {
while (a.length < b.length) a.unshift(0);
while (a.length > b.length) b.unshift(0);
var carry = 0, sum = []
for (var i = a.length - 1; i >= 0; i--) {
var s = a[i] + b[i] + carry;
if (s >= 10) {
s = s - 10;
carry = 1;
} else {
carry = 0;
}
sum.unshift(s);
}
if (carry)
sum.unshift(carry);
return sum;
}
And the fibonacci function is like this:
function fib(n) {
var f1 = [0];
var f2 = [1];
while (n--) {
var f3 = add(f1, f2)
f1 = f2;
f2 = f3;
}
return f1.join("");
}
Seems totally ineffective, but only takes fractions of second to get fib(4000)
on a 2.3GHz macbook.
Because Number.MAX_VALUE + Number.MAX_VALUE === Infinity
The issue is that sum
exceeds JavaScripts capabilities for storing numeric values.