Question

I am trying to write a code that will figure out the largest product of 5 consecutive numbers in a given number.
The code I have attempts to convert the number into an array and then for-loop through the array, multiplying every 5 consecutive single digit numbers and comparing it with the last.
Once the number I pass through the function exceeds 21 digits, I'm guessing the computer converts the number into scientific notation which throws the whole function off.
Here's the code, where it runs fine with 21 digits:

function func(value){
    var number = value;
    console.log(number);
    var output = [];
    sNumber = number.toString();
    console.log(sNumber);
    for (var i = 0; i < sNumber.length; i++) {
        output.push(+sNumber.charAt(i));
    }
    console.log(output);
    var productToCompare;
    var largerProduct = 0;
    for (var j = 0; j < output.length - 4; j++) {
        productToCompare = output[j]*output[j+1]*output[j+2]*output[j+3]*output[j+4];
        console.log(productToCompare);
        if (productToCompare > largerProduct) {
            largerProduct = productToCompare;
        }
    }
    return largerProduct;
}

func(13245678901234567890);

Soon as I add another digit:

func(123465789012345678901);

It starts using scientific notation.
Is this due to the nature of Javascript, the computer I'm using, the compiler or what?

Was it helpful?

Solution

As with a lot of things you'll run up against limitations of the fundamental data types used in JavaScript. In this case it seems to be a limit of the integer type.

The number 13245678901234567890 fits inside a 64-bit integer. Adding another digit pushes it into a range that cannot be represented that way so a floating-point number is required.

When testing this in different JavaScript engines you might get different values. Anything beyond 2147483648 is liable to end up cast as a floating point value.

Whenever you're doing mathematical calculations, try to avoid doing string computations on them. The string representation of a number is rather arbitrary and is not to be trusted.

What you should be doing is dividing by some factor of 10 and doing modulo-10 to get the individual digits.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top