diff --git a/src/algorithms/math/least-common-multiple/__test__/leastCommonMultiple.test.js b/src/algorithms/math/least-common-multiple/__test__/leastCommonMultiple.test.js index 2152e110a1..6612edc130 100644 --- a/src/algorithms/math/least-common-multiple/__test__/leastCommonMultiple.test.js +++ b/src/algorithms/math/least-common-multiple/__test__/leastCommonMultiple.test.js @@ -15,4 +15,13 @@ describe('leastCommonMultiple', () => { expect(leastCommonMultiple(-7, -9)).toBe(63); expect(leastCommonMultiple(-7, 9)).toBe(63); }); + + it('should avoid rounding an intermediate product for safe integer inputs', () => { + const multiple = Number.MAX_SAFE_INTEGER - 1; + + expect(leastCommonMultiple(multiple, 3)).toBe(multiple); + expect(leastCommonMultiple(3, multiple)).toBe(multiple); + expect(leastCommonMultiple(-multiple, 3)).toBe(multiple); + expect(leastCommonMultiple(multiple, -3)).toBe(multiple); + }); }); diff --git a/src/algorithms/math/least-common-multiple/leastCommonMultiple.js b/src/algorithms/math/least-common-multiple/leastCommonMultiple.js index 26a7681039..9f3a7570e1 100644 --- a/src/algorithms/math/least-common-multiple/leastCommonMultiple.js +++ b/src/algorithms/math/least-common-multiple/leastCommonMultiple.js @@ -7,5 +7,6 @@ import euclideanAlgorithm from '../euclidean-algorithm/euclideanAlgorithm'; */ export default function leastCommonMultiple(a, b) { - return ((a === 0) || (b === 0)) ? 0 : Math.abs(a * b) / euclideanAlgorithm(a, b); + // Divide first to avoid rounding an unnecessarily large intermediate product. + return ((a === 0) || (b === 0)) ? 0 : Math.abs((a / euclideanAlgorithm(a, b)) * b); }