Greatest common divisor

JavaScript, Math, Algorithm, Recursion · Dec 29, 2020

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));
};
gcd(8, 36); // 4
gcd(...[12, 8, 32]); // 4

More like this

  • Least common multiple

    Calculates the least common multiple of two or more numbers.

    JavaScript, Math · Dec 28, 2020

  • Euclidean distance

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

    JavaScript, Math · Dec 28, 2020

  • Vector distance

    Calculates the distance between two vectors.

    JavaScript, Math · Dec 28, 2020