659 B
659 B
title, tags, expertise, cover, firstSeen, lastUpdated
| title | tags | expertise | cover | firstSeen | lastUpdated |
|---|---|---|---|---|---|
| Greatest common divisor | math,algorithm,recursion | intermediate | blog_images/flower-pond.jpg | 2017-12-17T17:55:51+02:00 | 2020-12-29T12:36:50+02:00 |
Calculates the greatest common divisor between two or more numbers/arrays.
- The inner
_gcdfunction uses recursion. - Base case is when
yequals0. In this case, returnx. - Otherwise, return the GCD of
yand the remainder of the divisionx / 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