Skip to content

Commit aa76e6a

Browse files
feat: add greatest common divisor algorithm
1 parent 5c39e87 commit aa76e6a

2 files changed

Lines changed: 66 additions & 0 deletions

File tree

‎Maths/GreatestCommonDivisor.js‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
/**
2+
* @function greatestCommonDivisor
3+
* @description Finds the greatest common divisor (GCD) of two integers
4+
* using the Euclidean algorithm.
5+
* @param {number} a - First positive integer
6+
* @param {number} b - Second positive integer
7+
* @returns {number} - The GCD of a and b
8+
* @see https://en.wikipedia.org/wiki/Greatest_common_divisor
9+
* @example greatestCommonDivisor(12, 8) => 4
10+
* @example greatestCommonDivisor(100, 75) => 25
11+
* @example greatestCommonDivisor(7, 5) => 1
12+
*/
13+
const greatestCommonDivisor = (a, b) => {
14+
if (!Number.isInteger(a) || !Number.isInteger(b) || a < 1 || b < 1) {
15+
throw new TypeError('Both inputs must be positive integers')
16+
}
17+
while (b !== 0) {
18+
;[a, b] = [b, a % b]
19+
}
20+
return a
21+
}
22+
23+
export { greatestCommonDivisor }
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
import { greatestCommonDivisor } from '../GreatestCommonDivisor.js'
2+
3+
describe('greatestCommonDivisor', () => {
4+
test('greatestCommonDivisor(12, 8) returns 4', () => {
5+
expect(greatestCommonDivisor(12, 8)).toBe(4)
6+
})
7+
8+
test('greatestCommonDivisor(100, 75) returns 25', () => {
9+
expect(greatestCommonDivisor(100, 75)).toBe(25)
10+
})
11+
12+
test('greatestCommonDivisor(7, 5) returns 1', () => {
13+
expect(greatestCommonDivisor(7, 5)).toBe(1)
14+
})
15+
16+
test('greatestCommonDivisor(1, 1) returns 1', () => {
17+
expect(greatestCommonDivisor(1, 1)).toBe(1)
18+
})
19+
20+
test('greatestCommonDivisor of same numbers returns that number', () => {
21+
expect(greatestCommonDivisor(5, 5)).toBe(5)
22+
})
23+
24+
test('greatestCommonDivisor(48, 18) returns 6', () => {
25+
expect(greatestCommonDivisor(48, 18)).toBe(6)
26+
})
27+
28+
test('greatestCommonDivisor(100, 10) returns 10', () => {
29+
expect(greatestCommonDivisor(100, 10)).toBe(10)
30+
})
31+
32+
test('throws TypeError for zero input', () => {
33+
expect(() => greatestCommonDivisor(0, 5)).toThrow(TypeError)
34+
})
35+
36+
test('throws TypeError for negative input', () => {
37+
expect(() => greatestCommonDivisor(-12, 8)).toThrow(TypeError)
38+
})
39+
40+
test('throws TypeError for float input', () => {
41+
expect(() => greatestCommonDivisor(12.5, 8)).toThrow(TypeError)
42+
})
43+
})

0 commit comments

Comments
 (0)