make gcd accept variable arguments

This commit is contained in:
Rohit Tanwar
2017-12-22 18:46:17 +05:30
parent 528bdd7ccd
commit 1b34907f96

View File

@ -1,12 +1,16 @@
### gcd
Calculates the greatest common divisor between two numbers.
Calculates the greatest common divisor between two or more numbers numbers.
Use recursion.
The helper function uses recursion.
The helper case takes two arguments x and y
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 gcd = (x, y) => !y ? x : gcd(y, x % y);
const gcd = (...arr) => {
const gcdHelper = (x, y) => !y ? x : gcd(y, x % y);
return arr.reduce((a,b) => gcdHelper(a,b))
}
// gcd (8, 36) -> 4
```