Why does this Fibonacci number function return infinity for the 4000th value?

前端 未结 8 1385
攒了一身酷
攒了一身酷 2021-01-06 10:03
function fibo() {
var first,second,add;
for(var i=0;i<4000;i++){
    if(i === 0){
        first = 1;
        second = 2;
    }
    add = first + second;
    first         


        
相关标签:
8条回答
  • 2021-01-06 10:35

    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.

    0 讨论(0)
  • 2021-01-06 10:36

    Because Number.MAX_VALUE + Number.MAX_VALUE === Infinity

    The issue is that sum exceeds JavaScripts capabilities for storing numeric values.

    0 讨论(0)
提交回复
热议问题