Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add leastCommonMultipleArray function and corresponding tests #1158

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import leastCommonMultiple from '../leastCommonMultiple';
import leastCommonMultiple, { leastCommonMultipleArray } from '../leastCommonMultiple';

describe('leastCommonMultiple', () => {
it('should find least common multiple', () => {
Expand All @@ -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);
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}