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

前端 未结 8 1386
攒了一身酷
攒了一身酷 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:27

    For better results you can use the jsperf.com: http://jsperf.com/fib-vs-fib-loga/

    Just a lite change in the function to get the max position possible to calculate by javascript.

    Yes, the result will be diferent on each browser and arch bean used.

    function fibo() {
        var first,second,add;
        for(var i=0;i<4000;i++){
            if(i === 0){
                first = 1;
                second = 2;
            }
            if(first+second > Number.MAX_VALUE){
                console.debug(i, first, second);
                return;
            }
            add = first + second;
            first = second;
            second = add;
        }
        alert(add);
    }
    fibo();
    

    The result is: 1473 8.077637632156222e+307 1.3069892237633987e+308 Where 1473 is the maximum fibonacci position possible to calculate with javascript.

提交回复
热议问题