diff --git a/README.md b/README.md index bfb0a410b..abb50682e 100644 --- a/README.md +++ b/README.md @@ -12,6 +12,7 @@ ### Array * [`arrayGcd`](#arraygcd) +* [`arrayLcm`](#arraylcm) * [`arrayMax`](#arraymax) * [`arrayMin`](#arraymin) * [`chunk`](#chunk) @@ -175,6 +176,24 @@ const arrayGcd = arr =>{ [⬆ back to top](#table-of-contents) +### 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)); +} +// arrayLcm([1,2,3,4,5]) -> 60 +// arrayLcm([4,8,12]) -> 24 +``` + +[⬆ back to top](#table-of-contents) + ### arrayMax Returns the maximum value in an array. diff --git a/docs/index.html b/docs/index.html index deec6540b..ef88e9600 100644 --- a/docs/index.html +++ b/docs/index.html @@ -43,6 +43,7 @@
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.
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));
+}
+// arrayLcm([1,2,3,4,5]) -> 60
+// arrayLcm([4,8,12]) -> 24
+
Returns the maximum value in an array.
Use Math.max() combined with the spread operator (...) to get the maximum value in the array.