Update least-common-multiple-(LCM).md
This commit is contained in:
@ -1,11 +1,12 @@
|
|||||||
### Least common multiple (LCM)
|
### Least common multiple (LCM)
|
||||||
|
|
||||||
Use this lcm formula `lcm(a,b)=|a*b|/gcd(a,b)` for calculating the least common multiple of two numbers.
|
Use the greatest common divisor (GCD) formula and `Math.abs()` to determine the least common multiple.
|
||||||
Makes use of the [GCD snippet](https://github.com/Chalarangelo/30-seconds-of-code#greatest-common-divisor-gcd).
|
The GCD formula uses recursion.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const lcm = (x,y) => Math.abs(x*y)/(gcd(x,y));
|
const lcm = (x,y) => {
|
||||||
const gcd = (x, y) => !y ? x : gcd(y, x % y);
|
const gcd = (x, y) => !y ? x : gcd(y, x % y);
|
||||||
// lcm(10,5) -> 10
|
return Math.abs(x*y)/(gcd(x,y));
|
||||||
|
};
|
||||||
// lcm(12,7) -> 84
|
// lcm(12,7) -> 84
|
||||||
```
|
```
|
||||||
|
|||||||
Reference in New Issue
Block a user