Smallest Common Multiple - Can someone explain how the provided solutions work?

I know how to find the LCM of 2 numbers using the Euclidian algorithm. I don’t fully understand the logic behind this, but I know that it works and I’ve used it in another setting before, as it is much faster than factoring all the numbers.

However, when I looked at how this can be applied to a set of more than two numbers I got really lost because I’ve never seen such mathematical notation before so I don’t understand how that works.

The provided solution

function smallestCommons(arr) {
  // Setup
  const [min, max] = arr.sort((a, b) => a - b);
  const range = Array(max - min + 1)
    .fill(0)
    .map((_, i) => i + min);
  // GCD of two numbers
  // https://en.wikipedia.org/wiki/Greatest_common_divisor#Euclid's_algorithm
  const gcd = (a, b) => (b === 0) ? a : gcd(b, a % b);
  // LCM of two numbers
  // https://en.wikipedia.org/wiki/Least_common_multiple#Using_the_greatest_common_divisor
  const lcm = (a, b) => a * b / gcd(a, b);
  // LCM of multiple numbers
  // https://en.wikipedia.org/wiki/Least_common_multiple#Other
  return range.reduce((multiple, curr) => lcm(multiple, curr));
}

smallestCommons([1, 5]);

For starters, why did the callback function of .map get an underscore for a parameter? I tried running this without the underscore, and it doesn’t work. According to what I’ve found online, and underscore is basically a variable that tells JS and the programmer to ignore the parameter, in this case being the element parameter of the callback. So what exactly does the method do there?

Also, how does the .reduce() method work at the end? According to Wikipedia, the LCM of multiple non-zero numbers can be rewritten as lcm(a1, a2, … , ar) = lcm(lcm(a1, a2, … , ar-1), ar), and this is what the reducer is supposed to be doing, but I’m not sure exactly how that works. It seems similar to GCD function, but I don’t exactly understand how this would work here.

Challenge: Intermediate Algorithm Scripting - Smallest Common Multiple

Link to the challenge:

The underscore means the first argument for the callback is not used. It doesn’t mean anything else.

I’d review what reduce does if you aren’t familiar with it. Here the callback computes the LCM between the current element and the last LCM computed, starting with the first array element as the first LCM.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.