Skip to content

Commit 8343b44

Browse files
committed
Added LCM for Array
1 parent ca3d16d commit 8343b44

File tree

2 files changed

+56
-0
lines changed

2 files changed

+56
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
import leastCommonMultipleArray from '../leastCommonMultipleArray';
2+
3+
describe('leastCommonMultiple', () => {
4+
it('should find least common multiple', () => {
5+
expect(() => leastCommonMultipleArray([])).toThrow(Error('Array is empty'));
6+
expect(leastCommonMultipleArray([0, 0])).toBe(0);
7+
expect(leastCommonMultipleArray([1, 0])).toBe(0);
8+
expect(leastCommonMultipleArray([0, 1])).toBe(0);
9+
expect(leastCommonMultipleArray([4, 6])).toBe(12);
10+
expect(leastCommonMultipleArray([6, 21])).toBe(42);
11+
expect(leastCommonMultipleArray([7, 2])).toBe(14);
12+
expect(leastCommonMultipleArray([3, 5])).toBe(15);
13+
expect(leastCommonMultipleArray([7, 3])).toBe(21);
14+
expect(leastCommonMultipleArray([1000000, 2])).toBe(1000000);
15+
expect(leastCommonMultipleArray([-9, -18])).toBe(18);
16+
expect(leastCommonMultipleArray([-7, -9])).toBe(63);
17+
expect(leastCommonMultipleArray([-7, 9])).toBe(63);
18+
expect(leastCommonMultipleArray([2, 3, 5])).toBe(30);
19+
expect(leastCommonMultipleArray([2, 4, 5])).toBe(20);
20+
expect(leastCommonMultipleArray([2, 4, 6, 8])).toBe(24);
21+
expect(leastCommonMultipleArray([2, 4, 6, 7, 8])).toBe(168);
22+
expect(leastCommonMultipleArray([2, 3, 5, 7, 11, 13, 17, 19])).toBe(9699690);
23+
});
24+
});
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
import euclideanAlgorithm from '../euclidean-algorithm/euclideanAlgorithm';
2+
3+
/**
4+
* Function to find the least common multiple of an array of numbers.
5+
* @param {Array<number>} nums Array of numbers.
6+
* @return {number}
7+
* @throws {Error("Array is empty")} - Thrown when the input array is empty.
8+
*/
9+
10+
export default function leastCommonMultipleArray(nums) {
11+
// Remove duplicates from array
12+
const uniqueNums = [...new Set(nums)];
13+
// Checks if array is empty then throw error
14+
if (uniqueNums.length === 0) {
15+
throw new Error('Array is empty');
16+
}
17+
// Checks if array contains 0 then return 0 as LCM
18+
for (let i = 0; i < uniqueNums.length; i += 1) {
19+
if (uniqueNums[i] === 0) {
20+
return 0;
21+
}
22+
}
23+
// Initialize LCM with first element of array
24+
let lcm = Math.abs(uniqueNums[0]);
25+
// Iterate over the array and find LCM of each element
26+
for (let i = 1; i < uniqueNums.length; i += 1) {
27+
const currentGCD = euclideanAlgorithm(lcm, uniqueNums[i]);
28+
lcm = Math.abs(lcm * uniqueNums[i]) / currentGCD;
29+
}
30+
// Return LCM
31+
return lcm;
32+
}

0 commit comments

Comments
 (0)