Emmanuel Akinfulubi

JavaScriptMath

Euclidean algorithm for GCD in JavaScript

Intermediate · 4 min read

The greatest common divisor (GCD) of two numbers is the biggest number that divides both. For 48 and 18 it is 6. You need it to simplify fractions (18/48 becomes 3/8), to find the largest square tile that covers a floor with no cutting, and to compute common multiples.

The method you will write is over two thousand years old: Euclid's algorithm. In this tutorial you will build two versions of it, one that subtracts and one that uses remainders, count how many steps each takes, and find the inputs that make even the fast one work hardest. You need to know while loops, % and Math.abs.

Euclid's idea

Any number that divides both a and b also divides their difference, a - b. So the GCD of 48 and 18 is the same as the GCD of 30 and 18, then of 12 and 18, and so on. Keep taking the smaller from the larger, and the two numbers shrink until they are equal. That value is the GCD.

Subtracting 18 from 48 twice is the same as taking the remainder: 48 % 18 is 12. The remainder does many subtractions in one go. That is the faster version.

Here is the exercise. Try it yourself first if you like, then read on and we will build it together.

37 The greatest common divisor, by Euclid

fair

Write gcd(a, b) with Euclid's algorithm. Count its steps against the subtraction version on gcd(1, 1000000), and find the input shape that is worst for the remainder version.

Stuck? Three hints, smallest first
  1. 1. The remainder version replaces (a, b) with (b, a % b) until b is 0.
  2. 2. The subtraction version repeatedly takes the smaller from the larger, which is the same idea one unit at a time.
  3. 3. Consecutive Fibonacci numbers make every remainder step remove exactly one term, which is the slowest the remainder version can go.

Step 1: the subtraction version

Step 1

const subtractionSteps = (a, b) => {
  let n = 0;
  while (a !== b) {
    if (a > b) a -= b;
    else b -= a;
    n++;
  }
  return n;
};
console.log(subtractionSteps(1071, 462)); // 11

This version counts its steps instead of returning the GCD, so you can compare the two methods. It takes 11 subtractions for 1071 and 462.

It has a hidden danger: if either number is 0, the loop never ends. With (0, 5), subtracting 0 from 5 changes nothing, and a !== b stays true forever. So keep this one for counting only.

Step 2: the remainder version

Replace the pair (a, b) with (b, a % b), until b becomes 0. Then a is the GCD:

Step 2

function gcd(a, b) {
  a = Math.abs(a);
  b = Math.abs(b);
  while (b) [a, b] = [b, a % b];
  return a;
}
console.log(gcd(48, 18));    // 6
console.log(gcd(1071, 462)); // 21

For 48 and 18 the pairs are (48, 18), then (18, 12), then (12, 6), then (6, 0). b is 0, so the answer is 6.

Two bits of syntax are new here:

  • while (b) keeps looping while b isn't 0. Zero counts as false in a condition.
  • [a, b] = [b, a % b] swaps in both new values at once. The right side is worked out first, using the old a and b, and then both are assigned. This is called destructuring assignment.

Step 3: zeros and negative numbers

Step 3

console.log(gcd(5, 0), gcd(0, 5), gcd(0, 0)); // 5 5 0
console.log(gcd(-8, 12), gcd(-8, -12));        // 4 4
console.log(gcd(17, 5));                       // 1

Every number divides 0, so the GCD of 5 and 0 is 5. Math.abs removes the minus signs at the start, so the answer is never negative. When the GCD is 1, like for 17 and 5, the numbers are called coprime: they share no factor except 1.

Step 4: count the steps

Make a copy of gcd that counts its loop steps:

Step 4

const gcdSteps = (a, b) => {
  let n = 0;
  a = Math.abs(a);
  b = Math.abs(b);
  while (b) {
    [a, b] = [b, a % b];
    n++;
  }
  return n;
};
console.log(gcdSteps(1071, 462)); // 3
console.log(gcdSteps(1, 100000), subtractionSteps(1, 100000)); // 2 99999

3 steps against 11 for the first pair. For 1 and 100000 the gap is huge: the subtraction version takes 1 away 99,999 times, while the remainder version needs 2 steps.

Step 5: the worst case

Which inputs make the remainder version slowest? The answer is consecutive Fibonacci numbers: the list that starts 1, 1 and where each number is the sum of the two before it (1, 1, 2, 3, 5, 8, 13...).

Step 5

const fib = [1, 1];
while (fib.length < 14) fib.push(fib.at(-1) + fib.at(-2));
const fibStepCounts = fib.slice(0, 12).map((f, i) => gcdSteps(f, fib[i + 1]));
console.log(fibStepCounts); // [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 ]

With a pair like 8 and 13, each remainder step only steps back one place in the list: (13, 8) becomes (8, 5), then (5, 3), and so on. So the steps grow by one per Fibonacci number, while the numbers themselves grow much faster. No other pair of that size takes more steps, which is why Euclid's algorithm stays fast even for very large numbers.

The full solution

The answer panel builds gcd, gcdSteps and subtractionSteps, finds the GCD of both example pairs, compares step counts and prints the Fibonacci counts. The checks underneath confirm each result, including the zero and negative cases and that the answer divides both inputs. Press Run to see the output.

The answer

function gcd(a, b) {
  a = Math.abs(a);
  b = Math.abs(b);
  while (b) [a, b] = [b, a % b];
  return a;
}

const gcdSteps = (a, b) => {
  let n = 0;
  a = Math.abs(a);
  b = Math.abs(b);
  while (b) {
    [a, b] = [b, a % b];
    n++;
  }
  return n;
};

const subtractionSteps = (a, b) => {
  let n = 0;
  while (a !== b) {
    if (a > b) a -= b;
    else b -= a;
    n++;
  }
  return n;
};

const fib = [1, 1];
while (fib.length < 14) fib.push(fib.at(-1) + fib.at(-2));
const fibStepCounts = fib.slice(0, 12).map((f, i) => gcdSteps(f, fib[i + 1]));

// The worst pair for subtraction: one small argument, one large.
const bySubtraction = subtractionSteps(1, 100000);
const byRemainder = gcdSteps(1, 100000);

console.log('gcd(48, 18)      :', gcd(48, 18));
console.log('gcd(1071, 462)   :', gcd(1071, 462), 'in', gcdSteps(1071, 462), 'remainder steps');
console.log('the same by subtraction:', subtractionSteps(1071, 462), 'steps');
console.log('gcd(1, 100000)   :', byRemainder, 'remainder steps against', bySubtraction, 'subtractions');
console.log('consecutive Fibonacci pairs cost:', fibStepCounts);

Output


      
9 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 9 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

9 checks

test('gcd(48, 18) is 6', gcd(48, 18), 6);
test('gcd(1071, 462) is 21, in three remainder steps', [gcd(1071, 462), gcdSteps(1071, 462)], [21, 3]);
test('subtraction needs eleven for the same pair', subtractionSteps(1071, 462), 11);
test('and 99999 for gcd(1, 100000), where remainders need 2', [bySubtraction, byRemainder], [99999, 2]);
test('zero is absorbing: gcd(n, 0) is n, and gcd(0, 0) is 0', [gcd(5, 0), gcd(0, 5), gcd(0, 0)], [5, 5, 0]);
test('signs are stripped, so the result is never negative', [gcd(-8, 12), gcd(-8, -12)], [4, 4]);
test('coprime numbers share only 1', [gcd(17, 5), gcd(9, 28)], [1, 1]);
test('the answer divides both inputs, and nothing larger does', [270 % gcd(270, 192), 192 % gcd(270, 192), gcd(270, 192)], [0, 0, 6]);
test('consecutive Fibonacci numbers cost one step per term: the worst case', fibStepCounts, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]);

The subtraction form is the one people reinvent, and gcd(1, 100000) shows what it costs: 99,999 passes to discover an answer the remainder form reaches in two, because a % b does every one of those subtractions at once. Worse, the subtraction loop never terminates if either argument is 0 — while (a !== b) spins forever on (0, 5), which is why the version above is only used for counting.

The Fibonacci result is the theoretical worst case made concrete. Each remainder step on (F(k), F(k+1)) yields a quotient of exactly 1, so it removes one term and no more, and the step count grows linearly with the index while the numbers grow exponentially. That is where the bound of about log of the smaller input comes from: no pair does worse.

Common mistakes

  • Using the subtraction version with a 0. while (a !== b) never ends for (0, 5).
  • Swapping in two lines. Writing a = b; b = a % b; uses the new a on the second line, so it is wrong. Use [a, b] = [b, a % b] or a temporary variable.
  • Forgetting Math.abs. With negative inputs, the answer can come out negative.

Try it yourself

  1. Find the largest square tile that covers a 240 cm by 180 cm floor exactly.
  2. Simplify the fraction 84/126 by dividing both parts by their GCD.
  3. Write a recursive version: gcd(a, b) returns a when b is 0, otherwise gcd(b, a % b).

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.