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
29 changes: 29 additions & 0 deletions src/utils/lcm.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
//Name: Amit Jaggernauth
//Professor: Richard Krasso
//Course: WEB-450
//Date: 6/9/2024

// lcm.js

/**
* Calculate the Greatest Common Divisor (GCD)
* using the Euclidean algorithm.
*/
function gcd(a, b) {
if (a === 0) return b;
return gcd(b % a, a);
}

/**
* Calculate the Least Common Multiple (LCM)
* of two positive integers.
*/
function lcm(a, b) {
if (a <= 0 || b <= 0) {
throw new Error("Inputs must be positive integers");
}

return Math.abs(a * b) / gcd(a, b);
}

module.exports = { lcm, gcd };
22 changes: 22 additions & 0 deletions test/utils/lcm.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
//Name: Amit Jaggernauth
//Professor: Richard Krasso
//Course: WEB-450
//Date: 6/9/2024

// lcm.test.js

const { lcm } = require("./lcm");

describe("LCM Function", () => {
test("calculates LCM of two small numbers", () => {
expect(lcm(4, 6)).toBe(12);
});

test("calculates LCM when one number is a multiple of the other", () => {
expect(lcm(5, 20)).toBe(20);
});

test("throws an error for non-positive integers", () => {
expect(() => lcm(-3, 6)).toThrow("Inputs must be positive integers");
});
});