From 4deb253d4c9e79ad77d32b09c4870b90d18d42cd Mon Sep 17 00:00:00 2001 From: Rohit Tanwar Date: Fri, 22 Dec 2017 18:46:17 +0530 Subject: [PATCH] make gcd accept variable arguments --- snippets/gcd.md | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/snippets/gcd.md b/snippets/gcd.md index 34fb21833..bda988f05 100644 --- a/snippets/gcd.md +++ b/snippets/gcd.md @@ -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 ```