0

Below code is written in javascript and it is working fine for a certain limit of range.I want to check it out for range of 2 million and it is showing result as infinity? How to handle sum of large numbers in javascript?

function fibanocci(n){
    var first = 1;
    var second = 2;
    var next = 0;
    var sum = 2;
    for(var i=0;i<n-2;i++){
        next = first+second;
        first = second;
        second = next;
        if(next%2==0){
            sum = sum+next;
        }
    }
    console.log(sum);
}
georg
  • 211,518
  • 52
  • 313
  • 390
rk rk
  • 314
  • 1
  • 8
  • You obviously can't store this large numbers in a JavaScript Number, you need a big integer implementation – meskobalazs Feb 16 '15 at 10:22
  • The Fibonacci sequence is exponential. Are you sure you want the sum of the first 2 million numbers (a number of the order of half a million digits), or just the sum of all numbers below 2 million? – Phylogenesis Feb 16 '15 at 10:23
  • if you realy need big big big numbers try something like http://silentmatt.com/biginteger/ – Tschallacka Feb 16 '15 at 10:26
  • Project Euler problem 2 asks for the sum of the even Fibonacci numbers less than 4 million, and it also uses the same unusual starting values of 1 and 2 instead of saying that fibonacci(0)=0, fibonacci(1)=1, fibonacci(2)=1. See https://projecteuler.net/problem=2. I suspect that Phylogenesis is right and this is what was intended instead. – Douglas Zare Feb 16 '15 at 18:26

2 Answers2

0

With a number that big you're probably hitting the max number size. this answer says that the largest number javascript can deal with is 9007199254740992. I suppose anything above that might result in infinity.

Community
  • 1
  • 1
donnywals
  • 7,241
  • 1
  • 19
  • 27
  • That's the largest integer that can be held. Above that, it switches to a 64-bit double representation that can store up to about 1e308 with 15 digits of precision. – Phylogenesis Feb 16 '15 at 10:27
  • I doesn't actually switch, it is always a IEEE754 double according to the ECMAScript specification. This is just a turning point, where the integers are no longer safely representable. – meskobalazs Feb 16 '15 at 10:37
0

If you really need to work with such huge numbers, you should consider using a BigInteger implementation for JavaScript, like this one, as the biggest safely representable integer in a JavaScript Number is 2^53-1 = 9007199254740992.

meskobalazs
  • 15,741
  • 2
  • 40
  • 63