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

index.ts
function findLCM(numbers: number[]) {
  // base case
  if (numbers.length === 1) {
    return numbers[0];
  }

  // get the LCM of the first two numbers
  const a = numbers[0];
  const b = numbers[1];
  const lcmAB = lcm(a, b);

  // replace the first two numbers with their LCM
  numbers.splice(0, 2, lcmAB);

  // recursively find the LCM of the remaining numbers in the list
  return findLCM(numbers);
}

function lcm(a: number, b: number) {
  // calculate the GCD using the Euclidean algorithm
  const gcdAB = gcd(a, b);

  // use the formula LCM(a, b) = (a * b) / GCD(a, b)
  return (a * b) / gcdAB;
}

function gcd(a: number, b: number) {
  // base case
  if (b === 0) {
    return a;
  }

  // recursively find the GCD using the Euclidean algorithm
  return gcd(b, a % b);
}

// example usage
const numbers = [2, 3, 4, 5];
const result = findLCM(numbers);
console.log(result); // output: 60
898 chars
41 lines

Explanation:

  • The findLCM function takes an array of numbers as an input and returns their least common multiple (LCM). It does this by recursively finding the LCM of the first two numbers in the list, then replacing those two numbers with their LCM and continuing the process until only one number remains.
  • The lcm function takes two numbers as input and returns their LCM. It does this by first calculating their greatest common divisor (GCD) using the Euclidean algorithm, then using the formula LCM(a, b) = (a * b) / GCD(a, b).
  • The gcd function takes two numbers as input and returns their GCD. It does this recursively using the Euclidean algorithm until the second number becomes 0, at which point the first number is the GCD.

gistlibby LogSnag