find the common denominator of a list of numbers in javascript

To find the common denominator of a list of numbers in JavaScript, we can use the Least Common Multiple (LCM) formula. First, we need to get the LCM of two numbers, which can be found using the following function:

index.tsx
function getLCM(a, b) {
  return (a * b) / getGCD(a, b);
}

function getGCD(a, b) {
  if (b === 0) return a;
  return getGCD(b, a % b);
}
138 chars
9 lines

We can then iterate over the array of numbers and find the LCM of each pair of numbers. Once we have the LCM of the first two numbers, we can find the LCM of that result and the next number in the array, and so on. Here's the code to find the common denominator:

index.tsx
function getCommonDenominator(numbers) {
  let lcm = numbers[0];
  for (let i = 1; i < numbers.length; i++) {
    lcm = getLCM(lcm, numbers[i]);
  }
  return lcm;
}
165 chars
8 lines

This code takes an array of numbers as input, and returns the LCM of all the numbers in the array.

gistlibby LogSnag