diff --git a/Maths/LeastCommonMultiple.js b/Maths/LeastCommonMultiple.js new file mode 100644 index 0000000000..bfdb7d2f4f --- /dev/null +++ b/Maths/LeastCommonMultiple.js @@ -0,0 +1,26 @@ +/** + * @function leastCommonMultiple + * @description Finds the least common multiple (LCM) of two positive + * integers using the relationship: LCM(a, b) = (a * b) / GCD(a, b). + * @param {number} a - First positive integer + * @param {number} b - Second positive integer + * @returns {number} - The LCM of a and b + * @see https://en.wikipedia.org/wiki/Least_common_multiple + * @example leastCommonMultiple(4, 6) => 12 + * @example leastCommonMultiple(12, 15) => 60 + * @example leastCommonMultiple(7, 5) => 35 + */ +const leastCommonMultiple = (a, b) => { + if (!Number.isInteger(a) || !Number.isInteger(b) || a < 1 || b < 1) { + throw new TypeError('Both inputs must be positive integers') + } + const gcd = (x, y) => { + while (y !== 0) { + ;[x, y] = [y, x % y] + } + return x + } + return (a * b) / gcd(a, b) +} + +export { leastCommonMultiple } diff --git a/Maths/test/LeastCommonMultiple.test.js b/Maths/test/LeastCommonMultiple.test.js new file mode 100644 index 0000000000..67677286c3 --- /dev/null +++ b/Maths/test/LeastCommonMultiple.test.js @@ -0,0 +1,43 @@ +import { leastCommonMultiple } from '../LeastCommonMultiple.js' + +describe('leastCommonMultiple', () => { + test('leastCommonMultiple(4, 6) returns 12', () => { + expect(leastCommonMultiple(4, 6)).toBe(12) + }) + + test('leastCommonMultiple(12, 15) returns 60', () => { + expect(leastCommonMultiple(12, 15)).toBe(60) + }) + + test('leastCommonMultiple(7, 5) returns 35', () => { + expect(leastCommonMultiple(7, 5)).toBe(35) + }) + + test('leastCommonMultiple(1, 1) returns 1', () => { + expect(leastCommonMultiple(1, 1)).toBe(1) + }) + + test('leastCommonMultiple of same numbers returns that number', () => { + expect(leastCommonMultiple(5, 5)).toBe(5) + }) + + test('leastCommonMultiple(3, 4) returns 12', () => { + expect(leastCommonMultiple(3, 4)).toBe(12) + }) + + test('leastCommonMultiple(100, 75) returns 300', () => { + expect(leastCommonMultiple(100, 75)).toBe(300) + }) + + test('throws TypeError for zero input', () => { + expect(() => leastCommonMultiple(0, 5)).toThrow(TypeError) + }) + + test('throws TypeError for negative input', () => { + expect(() => leastCommonMultiple(-4, 6)).toThrow(TypeError) + }) + + test('throws TypeError for float input', () => { + expect(() => leastCommonMultiple(4.5, 6)).toThrow(TypeError) + }) +})