Although I have already made a decision, I think I can offer a simpler solution. Just store the numbers in arrays, one digit per element and add, as in elementary school, βin columnsβ. This happens as follows:
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 this:
function fib(n) { var f1 = [0]; var f2 = [1]; while (n--) { var f3 = add(f1, f2) f1 = f2; f2 = f3; } return f1.join(""); }
It seems completely inefficient, but it only takes a split second to get fib(4000)
on a Macbook 2.3 GHz.
georg source share