Largest product of n contiguous digits of a number in JavaScript



We are required to write a JavaScript function that takes in two numbers as first and the second argument, let us call them m and n.

The first number will generally be a number with multiple digits and the second number will always be smaller than the number of digits in the first number.

The function should find the group of n consecutive digits from m whose product is the greatest.

For example −

If the input numbers are −

const m = 65467586; const n = 3;

Then the output should be −

const output = 280;

because 7 * 5 * 8 = 280 and it’s the maximum consecutive three-digit product in this number

Example

Following is the code −

const m = 65467586; const n = 3; const largestProductOfContinuousDigits = (m, n) => {    const str = String(m);    if(n > str.length){       return 0;    };    let max = -Infinity;    let temp = 1;    for(let i = 0; i < n; i++){       temp *= +(str[i]);    };    max = temp;    for(i = 0; i < str.length - n; i++){       temp = (temp / (+str[i])) * (+str[i + n]);       max = Math.max(temp, max);    };    return max; } console.log(largestProductOfContinuousDigits(m, n));

Output

Following is the console output −

280
Updated on: 2021-01-22T06:54:53+05:30

177 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements