Skip to content
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
26 changes: 26 additions & 0 deletions Maths/LeastCommonMultiple.js
Original file line number Diff line number Diff line change
@@ -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 }
43 changes: 43 additions & 0 deletions Maths/test/LeastCommonMultiple.test.js
Original file line number Diff line number Diff line change
@@ -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)
})
})
Loading