find the greatest common divisor of a list of numbers in typescript

Here's a TypeScript function that uses the Euclidean algorithm to find the greatest common divisor of an array of numbers:

index.ts
function gcd(numbers: number[]): number {
  let result = numbers[0];
  for (let i = 1; i < numbers.length; i++) {
    result = gcdTwoNumbers(result, numbers[i]);
  }
  return result;
}

function gcdTwoNumbers(a: number, b: number): number {
  if (b === 0) {
    return a;
  }
  return gcdTwoNumbers(b, a % b);
}
312 chars
15 lines

The gcd function takes an array of numbers and iteratively calls gcdTwoNumbers to find the greatest common divisor of all the numbers in the array. The gcdTwoNumbers function uses the Euclidean algorithm to find the greatest common divisor of two numbers.

gistlibby LogSnag