Yevhen Klymentiev
dark
light
console
darkness
y.klymentiev@gmail.com
Reusable Snippets|Practical utility code for everyday use — custom-built and ready to share

gcd

Calculates the greatest common divisor (GCD) of two integers using the Euclidean algorithm.

TypeScript
Copied!
1/**
2 * Calculates the greatest common divisor (GCD) of two integers
3 * using the Euclidean algorithm.
4 *
5 * @param a - First integer
6 * @param b - Second integer
7 * @returns The greatest common divisor (always non-negative)
8 * @throws If either number is not a finite integer
9 */
10export function gcd(a: number, b: number): number {
11  if (!Number.isInteger(a) || !Number.isInteger(b)) {
12    throw new Error('Inputs must be integers');
13  }
14
15  a = Math.abs(a);
16  b = Math.abs(b);
17
18  while (b !== 0) {
19    [a, b] = [b, a % b];
20  }
21  return a;
22}
  • Robust Input Validation

    Explicitly checks that inputs are finite integers, preventing misuse with floats or NaN.

  • Mathematically Proven Algorithm

    Implements the efficient and time-tested Euclidean algorithm for optimal GCD calculation.

  • Handles Negative Inputs Gracefully

    Uses Math.abs() to normalize values, ensuring a non-negative result regardless of input sign.

  • Compact and Efficient Logic

    The use of destructuring for swapping and a clean loop makes the implementation both readable and performant.

Tests | Examples

TypeScript
Copied!
1test('gcd - basic case', () => {
2  expect(gcd(48, 18)).toBe(6);
3});
4
5test('gcd - order reversed', () => {
6  expect(gcd(18, 48)).toBe(6);
7});
8
9test('gcd - co-prime numbers', () => {
10  expect(gcd(13, 17)).toBe(1);
11});
12
13test('gcd - one is zero', () => {
14  expect(gcd(0, 25)).toBe(25);
15  expect(gcd(25, 0)).toBe(25);
16});
17
18test('gcd - both zeros', () => {
19  expect(gcd(0, 0)).toBe(0);
20});
21
22test('gcd - negative numbers', () => {
23  expect(gcd(-12, 18)).toBe(6);
24  expect(gcd(12, -18)).toBe(6);
25  expect(gcd(-12, -18)).toBe(6);
26});
27
28test('gcd - throws on non-integer', () => {
29  expect(() => gcd(10.5, 2)).toThrow('Inputs must be integers');
30  expect(() => gcd(10, NaN)).toThrow('Inputs must be integers');
31  expect(() => gcd(10, Infinity)).toThrow('Inputs must be integers');
32});

Common Use Cases

  • Math and Number Theory Applications

    Calculate GCDs in algorithms involving ratios, modular arithmetic, or simplification of fractions.

  • Simplifying Fractions

    Reduce fractions to their simplest form by dividing numerator and denominator by their GCD.

  • Cryptography

    Used in algorithms like RSA where determining co-prime relationships or reducing keys is essential.

  • Computer Graphics and Tiling

    Determine repeatable patterns or grid alignments based on common divisors of dimensions.

  • Scheduling and Syncing Systems

    Find intervals where two periodic tasks align based on shared timing factors.

Codebase: Utilities -> Numbers -> gcd | Yevhen Klymentiev