Skip to content

Commit 69439ef

Browse files
author
pranav.date
committed
lcm.js file added
1 parent 08d8c6b commit 69439ef

File tree

2 files changed

+64
-0
lines changed

2 files changed

+64
-0
lines changed

Maths/LCM.js

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
/**
2+
* @function lcm
3+
* @description Compute the least common multiple (LCM) of two integers.
4+
* @param {number} a - first integer
5+
* @param {number} b - second integer
6+
* @return {number} LCM of a and b
7+
* @example lcm(4,6) -> 12
8+
* @example lcm(7,3) -> 21
9+
*/
10+
const gcd = (x, y) => {
11+
let a = Math.abs(x)
12+
let b = Math.abs(y)
13+
if (Number.isNaN(a) || Number.isNaN(b)) throw new TypeError('Argument is NaN - Not a Number')
14+
while (b !== 0) {
15+
const t = a % b
16+
a = b
17+
b = t
18+
}
19+
return a
20+
}
21+
22+
const lcm = (a, b) => {
23+
const na = Number(a)
24+
const nb = Number(b)
25+
26+
if (Number.isNaN(na) || Number.isNaN(nb) || typeof a === 'object' || typeof b === 'object') {
27+
throw new TypeError('Argument is NaN - Not a Number')
28+
}
29+
30+
if (na === 0 || nb === 0) return 0
31+
32+
// lcm(a,b) = |a * b| / gcd(a,b)
33+
return Math.abs((na / gcd(na, nb)) * nb)
34+
}
35+
36+
export { lcm }

Maths/test/LCM.test.js

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
import { describe, it, expect } from 'vitest'
2+
import { lcm } from '../LCM'
3+
4+
describe('lcm()', () => {
5+
it('returns 0 when either argument is 0', () => {
6+
expect(lcm(0, 5)).toBe(0)
7+
expect(lcm(7, 0)).toBe(0)
8+
})
9+
10+
it('computes LCM for positive integers', () => {
11+
expect(lcm(4, 6)).toBe(12)
12+
expect(lcm(7, 3)).toBe(21)
13+
expect(lcm(21, 6)).toBe(42)
14+
})
15+
16+
it('computes LCM when inputs are negative', () => {
17+
expect(lcm(-4, 6)).toBe(12)
18+
expect(lcm(4, -6)).toBe(12)
19+
expect(lcm(-4, -6)).toBe(12)
20+
})
21+
22+
it('throws for non-numeric inputs', () => {
23+
// @ts-ignore
24+
expect(() => lcm('a', 5)).toThrow()
25+
// @ts-ignore
26+
expect(() => lcm(4, {})).toThrow()
27+
})
28+
})

0 commit comments

Comments
 (0)