gcd

JavaScript, Math, Algorithm, Recursion

Calculates the greatest common divisor between two or more numbers/arrays.

  • The inner _gcd function uses recursion.
  • Base case is when y equals 0. In this case, return x.
  • Otherwise, return the GCD of y and the remainder of the division x/y.
const gcd = (...arr) => {
  const _gcd = (x, y) => (!y ? x : gcd(y, x % y));
  return [...arr].reduce((a, b) => _gcd(a, b));
};
Examples
gcd(8, 36); // 4
gcd(...[12, 8, 32]); // 4

Recommended snippets

  • lcm

    JavaScript, Math

    Calculates the least common multiple of two or more numbers.

  • euclideanDistance

    JavaScript, Math

    Calculates the distance between two points in any number of dimensions.

  • geometricProgression

    JavaScript, Math

    Initializes an array containing the numbers in the specified range where start and end are inclusive and the ratio between two terms is step. Returns an error if step equals 1.