Emmanuel Akinfulubi

JavaScriptRecursion

GCD using recursion in JavaScript

Beginner · 4 min read

The greatest common divisor (GCD) of two numbers is the biggest number that divides both of them with nothing left over. The GCD of 48 and 18 is 6. You use it to simplify fractions (48/18 becomes 8/3 once you divide both by 6), to split things into equal groups, and to find the lowest common multiple, which you need when adding fractions.

In this tutorial you will write gcd(a, b) as a recursive function using a trick that is over two thousand years old, Euclid's algorithm. You need to know what a function is and how the % operator works. Recursion itself is explained as we go.

Euclid's idea

Trying every number from 1 upward would work, but it's slow. Euclid noticed something much faster: the GCD of a and b is the same as the GCD of b and the remainder of a ÷ b. Each step swaps in a smaller pair of numbers:

Worked example

gcd(48, 18)   48 % 18 is 12
gcd(18, 12)   18 % 12 is 6
gcd(12, 6)    12 % 6 is 0
gcd(6, 0)     the second number is 0, so the answer is 6

When the second number reaches 0, the first number is the answer. That is the base case, the point where the function stops calling itself.

A quick reminder about %

% gives the remainder after dividing. 48 % 18 is 12, because 18 goes into 48 twice with 12 left over. One detail matters later: the result takes the sign of the left-hand number.

JavaScript

console.log(48 % 18);  // 12
console.log(-48 % 18); // -12
console.log(48 % -18); // 12

Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.

2 Greatest common divisor

easy

Find the largest number that divides two numbers with no remainder, using recursion.

Stuck? Three hints, smallest first
  1. 1. Euclid: the GCD of a and b equals the GCD of b and a % b.
  2. 2. The base case is b === 0, and the answer is then a.
  3. 3. This is tail recursion, so the loop version is a two-line rewrite.

Step 1: turn the rule into a function

Euclid's rule already has the shape of a recursive function: a base case and a smaller call.

Step 1

function gcd(a, b) {
  return b === 0 ? a : gcd(b, a % b);
}
console.log(gcd(48, 18));   // 6
console.log(gcd(17, 5));    // 1
console.log(gcd(270, 192)); // 6

The ? : is the ternary operator, a short if/else: if b === 0, return a, otherwise return gcd(b, a % b). Two numbers with a GCD of 1, like 17 and 5, share no factor except 1.

gcd(270, 192) takes only five calls: (270, 192), (192, 78), (78, 36), (36, 6) and (6, 0). The numbers shrink fast, which is why this is so quick.

Step 2: fix negative numbers

A divisor is usually given as a positive number. But try a negative input with Step 1's function:

JavaScript

function gcd(a, b) {
  return b === 0 ? a : gcd(b, a % b);
}
console.log(gcd(48, -18)); // -6

Because % keeps the sign of the left number, a negative can travel all the way to the base case. Wrapping the answer in Math.abs, which removes the minus sign, fixes it in one place:

Step 2

function gcd(a, b) {
  return b === 0 ? Math.abs(a) : gcd(b, a % b);
}
console.log(gcd(48, -18)); // 6
console.log(gcd(-48, 18)); // 6
console.log(gcd(0, 5));    // 5
console.log(gcd(5, 0));    // 5

Zero works too. Every number divides 0, so the GCD of 0 and 5 is 5.

Step 3: write it as a loop

The recursive call is the very last thing the function does. That is called tail recursion, and it means the function rewrites into a loop with no extra bookkeeping:

Step 3

function gcdLoop(a, b) {
  while (b !== 0) [a, b] = [b, a % b];
  return Math.abs(a);
}
console.log(gcdLoop(270, 192)); // 6

[a, b] = [b, a % b] swaps in the new pair in one line. Both versions do exactly the same steps.

Step 4: get the LCM for free

The lowest common multiple (LCM) is the smallest number both inputs divide into. For 4 and 6 it is 12. GCD times LCM always equals the two numbers multiplied together, so you can work out the LCM from the GCD:

Step 4

function gcd(a, b) {
  return b === 0 ? Math.abs(a) : gcd(b, a % b);
}
const lcm = (a, b) => Math.abs(a / gcd(a, b) * b);
console.log(lcm(4, 6));   // 12
console.log(lcm(48, 18)); // 144

Dividing before multiplying keeps the in-between number small, so very large inputs are less likely to go past what a Number can hold.

Step 5: a whole list

To find the GCD of more than two numbers, take the GCD of the first two, then the GCD of that with the third, and so on. reduce does exactly that:

Step 5

function gcd(a, b) {
  return b === 0 ? Math.abs(a) : gcd(b, a % b);
}
const gcdAll = (nums) => nums.reduce(gcd);
console.log(gcdAll([24, 36, 60])); // 12

The full solution

The panel has the recursive gcd, the loop version, lcm and gcdAll, with checks for zero, negatives and order. Press Run to see the output.

The answer

function gcd(a, b) {
  return b === 0 ? Math.abs(a) : gcd(b, a % b);
}

// The same steps as a loop. Nothing is lost, because the recursive call is the
// last thing that happens (tail recursion).
function gcdLoop(a, b) {
  while (b !== 0) [a, b] = [b, a % b];
  return Math.abs(a);
}

// GCD gives you LCM for free. Divide first, so the product cannot overflow.
const lcm = (a, b) => Math.abs(a / gcd(a, b) * b);

// Extends to a whole list by folding.
const gcdAll = (nums) => nums.reduce(gcd);

for (const [a, b] of [[48, 18], [17, 5], [270, 192], [0, 5]]) {
  console.log(`gcd(${a}, ${b}) =`, gcd(a, b), ' lcm =', lcm(a, b));
}
console.log('gcd of the whole list:', gcdAll([24, 36, 60]));

Output


      
11 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 11 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

11 checks

test('a shared factor is found', gcd(48, 18), 6);
test('coprime numbers give 1', gcd(17, 5), 1);
test('a bigger pair', gcd(270, 192), 6);
test('order does not matter', gcd(18, 48), gcd(48, 18));
test('gcd with 0 is the other number', gcd(0, 5), 5);
test('and the other way round', gcd(5, 0), 5);
test('negatives give a positive divisor', gcd(-48, 18), 6);
test('the loop agrees', gcdLoop(270, 192), gcd(270, 192));
test('lcm of 4 and 6 is 12', lcm(4, 6), 12);
test('gcd times lcm equals the product', gcd(48, 18) * lcm(48, 18), 48 * 18);
test('a whole list folds', gcdAll([24, 36, 60]), 12);

gcd(a, b) === gcd(b, a % b) shrinks the problem fast — gcd(270, 192) finishes in five steps. The Math.abs matters because % in JavaScript keeps the sign of the left operand, so -48 % 18 is -12 and a negative could fall out of the base case. In lcm, dividing before multiplying keeps the intermediate value small; a * b / gcd gives the same answer but can overflow on the way.

Common mistakes

  • Stopping when a reaches 0 instead of b. The rule divides by b, so b === 0 is the base case. Checking the wrong one gives wrong answers or divides by zero.
  • Forgetting Math.abs. gcd(48, -18) returns -6 without it.
  • Computing the LCM as a * b / gcd(a, b). The answer is the same, but the product can grow too big along the way. Divide first.

Try it yourself

  1. Write simplify(top, bottom) that returns a fraction in lowest terms, so simplify(48, 18) gives [8, 3].
  2. Add a counter and find how many calls gcd(89, 55) makes. Those are two Fibonacci numbers, which is the slowest case for Euclid.
  3. Use reduce and lcm to find the smallest number that 1 to 10 all divide into.

Keep practising

Newsletter

New writing, when it lands.

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