_gcd
function uses recursion.y
equals 0
. In this case, return x
.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
Subscribe to get resources directly to your inbox. You won't receive any spam! ✌️