diff --git a/snippets/arrayGcd.md b/snippets/arrayGcd.md deleted file mode 100644 index feb20cc00..000000000 --- a/snippets/arrayGcd.md +++ /dev/null @@ -1,17 +0,0 @@ -### arrayGcd - -Calculates the greatest common denominator (gcd) of an array of numbers. - -Use `Array.reduce()` and the `gcd` formula (uses recursion) to calculate the greatest common denominator of an array of numbers. - -```js -const arrayGcd = arr => { - const gcd = (x, y) => (!y ? x : gcd(y, x % y)); - return arr.reduce((a, b) => gcd(a, b)); -}; -``` - -```js -arrayGcd([1, 2, 3, 4, 5]); // 1 -arrayGcd([4, 8, 12]); // 4 -``` diff --git a/snippets/arrayLcm.md b/snippets/arrayLcm.md deleted file mode 100644 index 5486edea5..000000000 --- a/snippets/arrayLcm.md +++ /dev/null @@ -1,18 +0,0 @@ -### arrayLcm - -Calculates the lowest common multiple (lcm) of an array of numbers. - -Use `Array.reduce()` and the `lcm` formula (uses recursion) to calculate the lowest common multiple of an array of numbers. - -```js -const arrayLcm = arr => { - const gcd = (x, y) => (!y ? x : gcd(y, x % y)); - const lcm = (x, y) => x * y / gcd(x, y); - return arr.reduce((a, b) => lcm(a, b)); -}; -``` - -```js -arrayLcm([1, 2, 3, 4, 5]); // 60 -arrayLcm([4, 8, 12]); // 24 -``` diff --git a/snippets/gcd.md b/snippets/gcd.md index e651c30db..8c4011b4d 100644 --- a/snippets/gcd.md +++ b/snippets/gcd.md @@ -1,13 +1,17 @@ ### gcd -Calculates the greatest common divisor between two numbers. +Calculates the greatest common divisor between two or more numbers/arrays. -Use recursion. +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 gcd = (x, y) => (!y ? x : gcd(y, x % y)); +const gcd = (...arr) => { + let data = [].concat(...arr); + const helperGcd = (x, y) => (!y ? x : gcd(y, x % y)); + return data.reduce((a, b) => helperGcd(a, b)); +} ``` ```js diff --git a/snippets/lcm.md b/snippets/lcm.md index 9152f9aac..215158c30 100644 --- a/snippets/lcm.md +++ b/snippets/lcm.md @@ -1,17 +1,20 @@ ### lcm -Returns the least common multiple of two numbers. +Returns the least common multiple of two or numbers/arrays. Use the greatest common divisor (GCD) formula and `Math.abs()` to determine the least common multiple. The GCD formula uses recursion. ```js -const lcm = (x, y) => { +const lcm = (...arr) => { + let data = [].concat(...arr); const gcd = (x, y) => (!y ? x : gcd(y, x % y)); - return Math.abs(x * y) / gcd(x, y); -}; + const helperLcm = (x, y) => x * y / gcd(x, y); + return arr.reduce((a, b) => helperLcm(a, b)) +} ``` ```js lcm(12, 7); // 84 +lcm([1,3,4],5); // 60 ```