From 69439ef859e3cb1ad172f9eb3ab18c02e8775682 Mon Sep 17 00:00:00 2001 From: "pranav.date" Date: Sun, 12 Oct 2025 13:51:31 +0530 Subject: [PATCH 1/2] lcm.js file added --- Maths/LCM.js | 36 ++++++++++++++++++++++++++++++++++++ Maths/test/LCM.test.js | 28 ++++++++++++++++++++++++++++ 2 files changed, 64 insertions(+) create mode 100644 Maths/LCM.js create mode 100644 Maths/test/LCM.test.js diff --git a/Maths/LCM.js b/Maths/LCM.js new file mode 100644 index 0000000000..d976371735 --- /dev/null +++ b/Maths/LCM.js @@ -0,0 +1,36 @@ +/** + * @function lcm + * @description Compute the least common multiple (LCM) of two integers. + * @param {number} a - first integer + * @param {number} b - second integer + * @return {number} LCM of a and b + * @example lcm(4,6) -> 12 + * @example lcm(7,3) -> 21 + */ +const gcd = (x, y) => { + let a = Math.abs(x) + let b = Math.abs(y) + if (Number.isNaN(a) || Number.isNaN(b)) throw new TypeError('Argument is NaN - Not a Number') + while (b !== 0) { + const t = a % b + a = b + b = t + } + return a +} + +const lcm = (a, b) => { + const na = Number(a) + const nb = Number(b) + + if (Number.isNaN(na) || Number.isNaN(nb) || typeof a === 'object' || typeof b === 'object') { + throw new TypeError('Argument is NaN - Not a Number') + } + + if (na === 0 || nb === 0) return 0 + + // lcm(a,b) = |a * b| / gcd(a,b) + return Math.abs((na / gcd(na, nb)) * nb) +} + +export { lcm } diff --git a/Maths/test/LCM.test.js b/Maths/test/LCM.test.js new file mode 100644 index 0000000000..d673464a71 --- /dev/null +++ b/Maths/test/LCM.test.js @@ -0,0 +1,28 @@ +import { describe, it, expect } from 'vitest' +import { lcm } from '../LCM' + +describe('lcm()', () => { + it('returns 0 when either argument is 0', () => { + expect(lcm(0, 5)).toBe(0) + expect(lcm(7, 0)).toBe(0) + }) + + it('computes LCM for positive integers', () => { + expect(lcm(4, 6)).toBe(12) + expect(lcm(7, 3)).toBe(21) + expect(lcm(21, 6)).toBe(42) + }) + + it('computes LCM when inputs are negative', () => { + expect(lcm(-4, 6)).toBe(12) + expect(lcm(4, -6)).toBe(12) + expect(lcm(-4, -6)).toBe(12) + }) + + it('throws for non-numeric inputs', () => { + // @ts-ignore + expect(() => lcm('a', 5)).toThrow() + // @ts-ignore + expect(() => lcm(4, {})).toThrow() + }) +}) From 0390653b688b06fe4d49864b719aeb78558ec466 Mon Sep 17 00:00:00 2001 From: "pranav.date" Date: Mon, 13 Oct 2025 10:40:54 +0530 Subject: [PATCH 2/2] change sin package json --- package.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/package.json b/package.json index e667e1eea2..ec4d5c84c7 100644 --- a/package.json +++ b/package.json @@ -13,11 +13,11 @@ "author": "TheAlgorithms", "license": "GPL-3.0", "devDependencies": { + "@vitest/coverage-v8": "^1.2.1", "globby": "^13.2.2", "husky": "^8.0.3", "prettier": "^3.0.3", - "vitest": "^1.2.1", - "@vitest/coverage-v8": "^1.2.1" + "vitest": "^3.2.4" }, "engines": { "node": ">=20.6.0"