find the least common multiple of a list of numbers in javascript

To find the least common multiple (LCM) of a list of numbers, we need to first find the greatest common divisor (GCD) of the numbers. Once we have the GCD, we can use the formula:

LCM = (a * b) / GCD(a, b)

To find the LCM of a list of numbers, we can apply this formula recursively to pairs of numbers until we have a single LCM.

Here's some JavaScript code to find the LCM of a list of numbers:

index.tsx
// Function to find the greatest common divisor of two numbers
function gcd(a, b) {
  if (b === 0) {
    return a;
  } else {
    return gcd(b, a % b);
  }
}

// Function to find the least common multiple of two numbers
function lcm(a, b) {
  return (a * b) / gcd(a, b);
}

// Function to find the least common multiple of a list of numbers
function lcmList(numbers) {
  // Start with the first number in the list
  var result = numbers[0];

  // Iterate over the rest of the numbers in the list
  for (var i = 1; i < numbers.length; i++) {
    // Calculate the LCM of the current number and the result so far
    result = lcm(result, numbers[i]);
  }

  return result;
}

// Example usage
var nums = [3, 6, 9];
var result = lcmList(nums);
console.log(result); // Output: 18
775 chars
33 lines

gistlibby LogSnag