diff --git a/src/algorithms/math/least-common-multiple/__test__/leastCommonMultiple.test.js b/src/algorithms/math/least-common-multiple/__test__/leastCommonMultiple.test.js index 2152e110..6a0abf3c 100644 --- a/src/algorithms/math/least-common-multiple/__test__/leastCommonMultiple.test.js +++ b/src/algorithms/math/least-common-multiple/__test__/leastCommonMultiple.test.js @@ -1,4 +1,4 @@ -import leastCommonMultiple from '../leastCommonMultiple'; +import leastCommonMultiple, { leastCommonMultipleArray } from '../leastCommonMultiple'; describe('leastCommonMultiple', () => { it('should find least common multiple', () => { @@ -15,4 +15,14 @@ describe('leastCommonMultiple', () => { expect(leastCommonMultiple(-7, -9)).toBe(63); expect(leastCommonMultiple(-7, 9)).toBe(63); }); + + it('should find least common multiple of an array', () => { + expect(leastCommonMultipleArray([4, 6])).toBe(12); + expect(leastCommonMultipleArray([6, 21, 14])).toBe(42); + expect(leastCommonMultipleArray([3, 5, 7])).toBe(105); + expect(leastCommonMultipleArray([2, 3, 5, 7, 11])).toBe(2310); + expect(leastCommonMultipleArray([1000000, 2, 3])).toBe(3000000); + expect(leastCommonMultipleArray([-9, -18, -27])).toBe(54); + expect(leastCommonMultipleArray([7, -9, 3])).toBe(63); + }); }); diff --git a/src/algorithms/math/least-common-multiple/leastCommonMultiple.js b/src/algorithms/math/least-common-multiple/leastCommonMultiple.js index 26a76810..de298782 100644 --- a/src/algorithms/math/least-common-multiple/leastCommonMultiple.js +++ b/src/algorithms/math/least-common-multiple/leastCommonMultiple.js @@ -5,7 +5,14 @@ import euclideanAlgorithm from '../euclidean-algorithm/euclideanAlgorithm'; * @param {number} b * @return {number} */ - export default function leastCommonMultiple(a, b) { return ((a === 0) || (b === 0)) ? 0 : Math.abs(a * b) / euclideanAlgorithm(a, b); } + +/** + * @param {number[]} numbers + * @return {number} + */ +export function leastCommonMultipleArray(numbers) { + return numbers.reduce((acc, val) => leastCommonMultiple(acc, val), 1); +}