From aa76e6a6d5720efcc7d04e5ee9e8806acbeac4a5 Mon Sep 17 00:00:00 2001 From: sarthakgupta1907-cell Date: Sat, 7 Nov 2026 01:42:38 +0530 Subject: [PATCH] feat: add greatest common divisor algorithm --- Maths/GreatestCommonDivisor.js | 23 +++++++++++++ Maths/test/GreatestCommonDivisor.test.js | 43 ++++++++++++++++++++++++ 2 files changed, 66 insertions(+) create mode 100644 Maths/GreatestCommonDivisor.js create mode 100644 Maths/test/GreatestCommonDivisor.test.js diff --git a/Maths/GreatestCommonDivisor.js b/Maths/GreatestCommonDivisor.js new file mode 100644 index 0000000000..0cd72e27c0 --- /dev/null +++ b/Maths/GreatestCommonDivisor.js @@ -0,0 +1,23 @@ +/** + * @function greatestCommonDivisor + * @description Finds the greatest common divisor (GCD) of two integers + * using the Euclidean algorithm. + * @param {number} a - First positive integer + * @param {number} b - Second positive integer + * @returns {number} - The GCD of a and b + * @see https://en.wikipedia.org/wiki/Greatest_common_divisor + * @example greatestCommonDivisor(12, 8) => 4 + * @example greatestCommonDivisor(100, 75) => 25 + * @example greatestCommonDivisor(7, 5) => 1 + */ +const greatestCommonDivisor = (a, b) => { + if (!Number.isInteger(a) || !Number.isInteger(b) || a < 1 || b < 1) { + throw new TypeError('Both inputs must be positive integers') + } + while (b !== 0) { + ;[a, b] = [b, a % b] + } + return a +} + +export { greatestCommonDivisor } diff --git a/Maths/test/GreatestCommonDivisor.test.js b/Maths/test/GreatestCommonDivisor.test.js new file mode 100644 index 0000000000..997afce321 --- /dev/null +++ b/Maths/test/GreatestCommonDivisor.test.js @@ -0,0 +1,43 @@ +import { greatestCommonDivisor } from '../GreatestCommonDivisor.js' + +describe('greatestCommonDivisor', () => { + test('greatestCommonDivisor(12, 8) returns 4', () => { + expect(greatestCommonDivisor(12, 8)).toBe(4) + }) + + test('greatestCommonDivisor(100, 75) returns 25', () => { + expect(greatestCommonDivisor(100, 75)).toBe(25) + }) + + test('greatestCommonDivisor(7, 5) returns 1', () => { + expect(greatestCommonDivisor(7, 5)).toBe(1) + }) + + test('greatestCommonDivisor(1, 1) returns 1', () => { + expect(greatestCommonDivisor(1, 1)).toBe(1) + }) + + test('greatestCommonDivisor of same numbers returns that number', () => { + expect(greatestCommonDivisor(5, 5)).toBe(5) + }) + + test('greatestCommonDivisor(48, 18) returns 6', () => { + expect(greatestCommonDivisor(48, 18)).toBe(6) + }) + + test('greatestCommonDivisor(100, 10) returns 10', () => { + expect(greatestCommonDivisor(100, 10)).toBe(10) + }) + + test('throws TypeError for zero input', () => { + expect(() => greatestCommonDivisor(0, 5)).toThrow(TypeError) + }) + + test('throws TypeError for negative input', () => { + expect(() => greatestCommonDivisor(-12, 8)).toThrow(TypeError) + }) + + test('throws TypeError for float input', () => { + expect(() => greatestCommonDivisor(12.5, 8)).toThrow(TypeError) + }) +})