Files
30-seconds-of-code/snippets/lcm.md
2017-12-30 01:54:53 +11:00

20 lines
455 B
Markdown

### lcm
Returns the least common multiple of two or more numbers/arrays.
Use the greatest common divisor (GCD) formula and `Math.abs()` to determine the least common multiple.
The GCD formula uses recursion.
```js
const lcm = (...arr) => {
const gcd = (x, y) => (!y ? x : gcd(y, x % y));
const _lcm = (x, y) => x * y / gcd(x, y);
return [].concat(...arr).reduce((a, b) => _lcm(a, b));
};
```
```js
lcm(12, 7); // 84
lcm([1, 3, 4], 5); // 60
```