Files
30-seconds-of-code/snippets/gcd.md
Rohit Tanwar 71019b7197 Update gcd.md
2017-12-29 16:40:42 +05:30

20 lines
454 B
Markdown

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