Files
30-seconds-of-code/snippets/gcd.md
2017-12-29 16:34:06 +05:30

449 B

gcd

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

The helperGcd 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 gcm = (...arr) => {
 arr = [].concat(...arr)
const helperGcd = (x, y) => (!y ? x : gcd(y, x % y));
return arr.reduce((a, b) => helperGcd(a, b))
}
gcd(8, 36); // 4