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