Skip to content

Commit 248cf62

Browse files
feat: add least common multiple algorithm
1 parent 5c39e87 commit 248cf62

2 files changed

Lines changed: 69 additions & 0 deletions

File tree

‎Maths/LeastCommonMultiple.js‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
/**
2+
* @function leastCommonMultiple
3+
* @description Finds the least common multiple (LCM) of two positive
4+
* integers using the relationship: LCM(a, b) = (a * b) / GCD(a, b).
5+
* @param {number} a - First positive integer
6+
* @param {number} b - Second positive integer
7+
* @returns {number} - The LCM of a and b
8+
* @see https://en.wikipedia.org/wiki/Least_common_multiple
9+
* @example leastCommonMultiple(4, 6) => 12
10+
* @example leastCommonMultiple(12, 15) => 60
11+
* @example leastCommonMultiple(7, 5) => 35
12+
*/
13+
const leastCommonMultiple = (a, b) => {
14+
if (!Number.isInteger(a) || !Number.isInteger(b) || a < 1 || b < 1) {
15+
throw new TypeError('Both inputs must be positive integers')
16+
}
17+
const gcd = (x, y) => {
18+
while (y !== 0) {
19+
;[x, y] = [y, x % y]
20+
}
21+
return x
22+
}
23+
return (a * b) / gcd(a, b)
24+
}
25+
26+
export { leastCommonMultiple }
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
import { leastCommonMultiple } from '../LeastCommonMultiple.js'
2+
3+
describe('leastCommonMultiple', () => {
4+
test('leastCommonMultiple(4, 6) returns 12', () => {
5+
expect(leastCommonMultiple(4, 6)).toBe(12)
6+
})
7+
8+
test('leastCommonMultiple(12, 15) returns 60', () => {
9+
expect(leastCommonMultiple(12, 15)).toBe(60)
10+
})
11+
12+
test('leastCommonMultiple(7, 5) returns 35', () => {
13+
expect(leastCommonMultiple(7, 5)).toBe(35)
14+
})
15+
16+
test('leastCommonMultiple(1, 1) returns 1', () => {
17+
expect(leastCommonMultiple(1, 1)).toBe(1)
18+
})
19+
20+
test('leastCommonMultiple of same numbers returns that number', () => {
21+
expect(leastCommonMultiple(5, 5)).toBe(5)
22+
})
23+
24+
test('leastCommonMultiple(3, 4) returns 12', () => {
25+
expect(leastCommonMultiple(3, 4)).toBe(12)
26+
})
27+
28+
test('leastCommonMultiple(100, 75) returns 300', () => {
29+
expect(leastCommonMultiple(100, 75)).toBe(300)
30+
})
31+
32+
test('throws TypeError for zero input', () => {
33+
expect(() => leastCommonMultiple(0, 5)).toThrow(TypeError)
34+
})
35+
36+
test('throws TypeError for negative input', () => {
37+
expect(() => leastCommonMultiple(-4, 6)).toThrow(TypeError)
38+
})
39+
40+
test('throws TypeError for float input', () => {
41+
expect(() => leastCommonMultiple(4.5, 6)).toThrow(TypeError)
42+
})
43+
})

0 commit comments

Comments
 (0)