Added LCM for Array

This commit is contained in:
Mukund Mittal 2024-07-25 12:16:26 +05:30
parent ca3d16dcce
commit 8343b44f1d
2 changed files with 56 additions and 0 deletions

View File

@ -0,0 +1,24 @@
import leastCommonMultipleArray from '../leastCommonMultipleArray';
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);
});
});

View File

@ -0,0 +1,32 @@
import euclideanAlgorithm from '../euclidean-algorithm/euclideanAlgorithm';
/**
* Function to find the least common multiple of an array of numbers.
* @param {Array<number>} nums Array of numbers.
* @return {number}
* @throws {Error("Array is empty")} - Thrown when the input array is empty.
*/
export default function leastCommonMultipleArray(nums) {
// Remove duplicates from array
const uniqueNums = [...new Set(nums)];
// Checks if array is empty then throw error
if (uniqueNums.length === 0) {
throw new Error('Array is empty');
}
// Checks if array contains 0 then return 0 as LCM
for (let i = 0; i < uniqueNums.length; i += 1) {
if (uniqueNums[i] === 0) {
return 0;
}
}
// Initialize LCM with first element of array
let lcm = Math.abs(uniqueNums[0]);
// Iterate over the array and find LCM of each element
for (let i = 1; i < uniqueNums.length; i += 1) {
const currentGCD = euclideanAlgorithm(lcm, uniqueNums[i]);
lcm = Math.abs(lcm * uniqueNums[i]) / currentGCD;
}
// Return LCM
return lcm;
}