Search code examples
javascriptfibonacci

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


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?


Solution

  • 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:

    #include <gmp.h>
    
    int main()
    {
        mpz_t num;
        mpz_init(num);
    
        mpz_fib_ui(num, 4000);
        gmp_printf("%Zd\n", num);
    
        return 0;
    }
    

    Compile with:

    cc fib.c -lgmp
    

    And run :-)

    time ./a.out
    39909473435004422792081248094960912600792570982820257852628876326523051818641373433549136769424132442293969306537520118273879628025443235370362250955435654171592897966790864814458223141914272590897468472180370639695334449662650312874735560926298246249404168309064214351044459077749425236777660809226095151852052781352975449482565838369809183771787439660825140502824343131911711296392457138867486593923544177893735428602238212249156564631452507658603400012003685322984838488962351492632577755354452904049241294565662519417235020049873873878602731379207893212335423484873469083054556329894167262818692599815209582517277965059068235543139459375028276851221435815957374273143824422909416395375178739268544368126894240979135322176080374780998010657710775625856041594078495411724236560242597759185543824798332467919613598667003025993715274875
    
    real    0m0.005s
    user    0m0.001s
    sys     0m0.002s