Decompose huge number in javascript

3

Continuing with this question

The problem is that there are numbers in my variable, that is, I am not able to get the values above 1073741824 and I wanted to get in 562949953421312 according to my last question.

Are there any number limits on the variable in javascript?

In my console.log(fatores) , it shows an empty array, or negative (depends on the number).

n = 562949953421312;
power = 0;
var fatores = []
while (n != 0) {
    if ((n & 1) != 0) {
        fatores[fatores.length] = (1 << power);
    }
    ++power;
    n >>>= 1;
}
console.log(fatores) // returna vazio '[]'
    
asked by anonymous 14.07.2014 / 22:33

1 answer

7

JavaScript numbers are double s, ie floating point with "double" precision (64 bits) . This means that the largest integer accurately representable is 2^53 = 9007199254740992 (larger numbers can be represented, but with "holes" between one and the other).

If you need to represent numbers larger than 2^53 , then I suggest looking for a "big number" library (or "big integer", or "big decimal"). I do not know any particular ones to recommend, but there are several, just see exactly what you need and if the library supports (usually at least basic arithmetic operations will be supported).

These libraries typically do this using not a variable, but an array of numbers to represent a larger number. That is, the supported precision is virtually unlimited, except for the amount of memory on your computer (or the maximum number of elements in an array supported by the language / implementation). Of course, their performance is less than the use of a single variable, so these libraries should only be used when really needed.

Update: Although JavaScript represents numbers as double s, bitwise operations as << , >>> , & , etc. treat their operands as 32-bit integers . For this reason, the largest number that can be handled by these operators is not 2^53 , but 2^31-1 = 2147483647 (the largest positive integer representable in 32 bits). Trying to use them with larger numbers will then cause unexpected behavior.

I have modified the code to use simple multiplication / division by 2 - instead of bitwise operations, and it now works as expected:

    var n = 562949953421312;
    var power = 1;
    var fatores = [];
    while (n != 0) {
        if (n % 2 !== 0) {
            fatores[fatores.length] = power;
            n--;
        }
        power *= 2;
        n /= 2;
    }

Example in jsFiddle (type a number in the text box and press Enter ).     

14.07.2014 / 22:45