mirror of
https://github.moeyy.xyz/https://github.com/trekhleb/javascript-algorithms.git
synced 2024-09-20 07:43:04 +08:00
Add leastCommonMultipleArray function and corresponding tests
This commit is contained in:
parent
ca3d16dcce
commit
17c999c568
@ -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);
|
||||
});
|
||||
});
|
||||
|
@ -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);
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user