From a4dd3bd2134a1a18940032623d3b163a42bfc2d9 Mon Sep 17 00:00:00 2001 From: Brungeshwar <96064819+Brungeshwar@users.noreply.github.com> Date: Thu, 15 Aug 2024 17:50:47 +0530 Subject: [PATCH] resolved 1154 issue - array-lcm --- .../math/lcm-array/_test_/lcm-array.test.js | 26 +++++++++++++++++++ src/algorithms/math/lcm-array/lcm-array.js | 16 ++++++++++++ 2 files changed, 42 insertions(+) create mode 100644 src/algorithms/math/lcm-array/_test_/lcm-array.test.js create mode 100644 src/algorithms/math/lcm-array/lcm-array.js diff --git a/src/algorithms/math/lcm-array/_test_/lcm-array.test.js b/src/algorithms/math/lcm-array/_test_/lcm-array.test.js new file mode 100644 index 00000000..7e27215e --- /dev/null +++ b/src/algorithms/math/lcm-array/_test_/lcm-array.test.js @@ -0,0 +1,26 @@ +import leastCommonMultipleArray from '../lcm-array.js'; + +describe('leastCommonMultiple', () => { + it('should find least common multiple', () => { + expect(() => leastCommonMultipleArray([])).toThrow(Error('Array is empty')); + expect(leastCommonMultipleArray([0, 0])).toBe(0); + expect(leastCommonMultipleArray([1, 0])).toBe(0); + expect(leastCommonMultipleArray([0, 1])).toBe(0); + expect(leastCommonMultipleArray([4, 6])).toBe(12); + expect(leastCommonMultipleArray([6, 21])).toBe(42); + expect(leastCommonMultipleArray([7, 2])).toBe(14); + expect(leastCommonMultipleArray([3, 5])).toBe(15); + expect(leastCommonMultipleArray([7, 3])).toBe(21); + expect(leastCommonMultipleArray([1000000, 2])).toBe(1000000); + expect(leastCommonMultipleArray([-9, -18])).toBe(18); + expect(leastCommonMultipleArray([-7, -9])).toBe(63); + expect(leastCommonMultipleArray([-7, 9])).toBe(63); + expect(leastCommonMultipleArray([2, 3, 5])).toBe(30); + expect(leastCommonMultipleArray([2, 4, 5])).toBe(20); + expect(leastCommonMultipleArray([2, 4, 6, 8])).toBe(24); + expect(leastCommonMultipleArray([2, 4, 6, 7, 8])).toBe(168); + expect(leastCommonMultipleArray([2, 3, 5, 7, 11, 13, 17, 19])).toBe( + 9699690 + ); + }); +}); diff --git a/src/algorithms/math/lcm-array/lcm-array.js b/src/algorithms/math/lcm-array/lcm-array.js new file mode 100644 index 00000000..e240517a --- /dev/null +++ b/src/algorithms/math/lcm-array/lcm-array.js @@ -0,0 +1,16 @@ +import euclideanAlgorithm from '../euclidean-algorithm/euclideanAlgorithm.js'; + +export default function leastCommonMultipleArray(arr) { + let siz = arr.length; + if (siz == 0) throw new Error('Array is empty'); + for (let num of arr) { + if (num == 0) return 0; + } + let lcm = arr[0]; + for (let i = 0; i < siz; i++) { + let prod = Math.abs(lcm * arr[i]); + let gcd = euclideanAlgorithm(lcm, arr[i]); + lcm = prod / gcd; + } + return lcm; +}