make gcd accept variable arguments

This commit is contained in:
Rohit Tanwar
2017-12-22 18:46:17 +05:30
parent 18741354c3
commit 4deb253d4c

View File

@ -1,12 +1,16 @@
### gcd ### 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`. 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`. Otherwise, return the GCD of `y` and the remainder of the division `x/y`.
```js ```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 // gcd (8, 36) -> 4
``` ```