make gcd accept variable arguments
This commit is contained in:
@ -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
|
||||||
```
|
```
|
||||||
|
|||||||
Reference in New Issue
Block a user