Add leastCommonMultipleArray function and corresponding tests

This commit is contained in:
Parvez Khan 2024-08-12 20:42:07 +05:30
parent ca3d16dcce
commit 17c999c568
2 changed files with 19 additions and 2 deletions

View File

@ -1,4 +1,4 @@
import leastCommonMultiple from '../leastCommonMultiple'; import leastCommonMultiple, { leastCommonMultipleArray } from '../leastCommonMultiple';
describe('leastCommonMultiple', () => { describe('leastCommonMultiple', () => {
it('should find least common multiple', () => { it('should find least common multiple', () => {
@ -15,4 +15,14 @@ describe('leastCommonMultiple', () => {
expect(leastCommonMultiple(-7, -9)).toBe(63); expect(leastCommonMultiple(-7, -9)).toBe(63);
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);
});
}); });

View File

@ -5,7 +5,14 @@ import euclideanAlgorithm from '../euclidean-algorithm/euclideanAlgorithm';
* @param {number} b * @param {number} b
* @return {number} * @return {number}
*/ */
export default function leastCommonMultiple(a, b) { export default function leastCommonMultiple(a, b) {
return ((a === 0) || (b === 0)) ? 0 : Math.abs(a * b) / euclideanAlgorithm(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);
}