Emmanuel Akinfulubi

JavaScriptBasic

Find the GCD and LCM of two numbers in JavaScript

Intermediate · 4 min read

The greatest common divisor (GCD) of two numbers is the biggest number that divides both of them evenly. For 12 and 18 it is 6. The lowest common multiple (LCM) is the smallest number that both divide into evenly. For 4 and 6 it is 12. You use the GCD to simplify fractions (12/18 becomes 2/3), and the LCM to find when two repeating things line up, like two buses that leave every 4 and every 6 minutes.

In this tutorial you will write gcd(a, b) using an algorithm over two thousand years old, then build lcm(a, b) on top of it with one line. You need to know what a function and a loop are, and what the % operator does. A quick reminder follows.

The % operator

% gives the remainder after dividing:

JavaScript

console.log(18 % 12); // 6: 18 is one 12 with 6 left over
console.log(12 % 6);  // 0: 12 divides evenly by 6

A remainder of 0 means "divides evenly". The whole algorithm is built on this.

Euclid's idea

You could find the GCD by trying every number from 1 upwards. Euclid's algorithm is much faster. It rests on one fact: the GCD of a and b is the same as the GCD of b and a % b. So you keep replacing the pair with a smaller pair until the second number is 0. The first number is then the answer.

Follow it for 12 and 18:

Output

(12, 18) -> 12 % 18 is 12, so the next pair is (18, 12)
(18, 12) -> 18 % 12 is 6,  so the next pair is (12, 6)
(12, 6)  -> 12 % 6 is 0,   so the next pair is (6, 0)
(6, 0)   -> stop. The GCD is 6.

Notice the first round just swapped the numbers. That means you don't need to care which one is bigger.

Here is the exercise. Try it yourself first if you like, or follow the steps.

32 Greatest common divisor and lowest common multiple

fair

Find the greatest common divisor of two numbers, then use it to find their lowest common multiple.

Stuck? Three hints, smallest first
  1. 1. Euclid’s algorithm: replace the pair with (b, a % b) until b is zero.
  2. 2. Once you have the GCD, the LCM is a * b / gcd(a, b).
  3. 3. Divide before multiplying to avoid overflowing on large inputs.

Step 1: the loop

Keep going while b isn't 0. Each round, the new pair is (b, a % b):

JavaScript

function gcd(a, b) {
  while (b !== 0) [a, b] = [b, a % b];
  return a;
}
console.log(gcd(12, 18)); // 6
console.log(gcd(18, 12)); // 6
console.log(gcd(17, 5));  // 1
console.log(gcd(0, 7));   // 7

[a, b] = [b, a % b] is destructuring. The right side builds the new pair from the current values, and the left side unpacks it into a and b at the same time. Without it, you would need a temporary variable.

17 and 5 share no divisor except 1. Numbers like that are called coprime. And gcd(0, 7) is 7, because every number divides 0.

Step 2: negative numbers

The greatest common divisor of -12 and -18 is still 6, but the loop gives:

JavaScript

function gcd(a, b) {
  while (b !== 0) [a, b] = [b, a % b];
  return a;
}
console.log(gcd(-12, -18)); // -6

In JavaScript, % keeps the sign of the number on the left, so negative values carry through. A greatest common divisor is normally given as a positive number, so drop the signs at the start with Math.abs:

Step 2

function gcd(a, b) {
  a = Math.abs(a);
  b = Math.abs(b);
  while (b !== 0) [a, b] = [b, a % b];
  return a;
}
console.log(gcd(-12, -18)); // 6

Step 3: the LCM from the GCD

There is a neat link between the two: for any two numbers, gcd(a, b) * lcm(a, b) equals a * b. So the LCM is a * b / gcd(a, b). For 4 and 6: 4 * 6 is 24, the GCD is 2, and 24 / 2 is 12.

The answer does one more thing: it divides before it multiplies, writing a / gcd(a, b) * b. The result is the same, but the number in the middle stays smaller. With very large inputs, a * b could go past the point where JavaScript numbers stay exact, and dividing first avoids that.

Step 3

function lcm(a, b) {
  if (a === 0 || b === 0) return 0;
  return Math.abs(a / gcd(a, b) * b);
}
console.log(lcm(4, 6));  // 12
console.log(lcm(0, 5));  // 0
console.log(gcd(12, 18) * lcm(12, 18), 12 * 18); // 216 216

The zero check comes first because gcd(0, 0) is 0, and dividing by 0 would give NaN. The last line checks the link between GCD and LCM. It makes a handy self-test for any GCD you write.

Step 4: a whole list

reduce walks through an array and combines the items two at a time. The GCD of three numbers is the GCD of the first two, combined with the third. So reduce can use gcd and lcm directly as its combining function:

JavaScript

const gcdAll = (values) => values.reduce(gcd);
const lcmAll = (values) => values.reduce(lcm);
console.log(gcdAll([12, 18, 24])); // 6
console.log(lcmAll([2, 3, 4]));    // 12

For [12, 18, 24]: gcd(12, 18) is 6, then gcd(6, 24) is 6. No starting value is passed, so reduce starts with the first item. That means an empty list would throw an error, so only call these on lists with at least one number.

The full solution

The complete answer has gcd, lcm and the list versions, and checks coprime numbers, zeros, the order of the inputs and the link between the two. Press Run to see the output.

The answer

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

// Divide first, then multiply, so the intermediate value stays smaller.
function lcm(a, b) {
  if (a === 0 || b === 0) return 0;
  return Math.abs(a / gcd(a, b) * b);
}

console.log('gcd(12, 18) =', gcd(12, 18));
console.log('gcd(17, 5)  =', gcd(17, 5), '(coprime)');
console.log('lcm(4, 6)   =', lcm(4, 6));

// Works for a whole list by folding.
const gcdAll = (values) => values.reduce(gcd);
const lcmAll = (values) => values.reduce(lcm);

console.log('gcd of [12, 18, 24] =', gcdAll([12, 18, 24]));
console.log('lcm of [2, 3, 4]    =', lcmAll([2, 3, 4]));

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 of 12 and 18', gcd(12, 18), 6);
test('coprime numbers give 1', gcd(17, 5), 1);
test('gcd with zero is the other number', gcd(0, 7), 7);
test('order does not matter', gcd(18, 12), gcd(12, 18));
test('lcm of 4 and 6', lcm(4, 6), 12);
test('lcm with zero is zero', lcm(0, 5), 0);
test('gcd across a list', gcdAll([12, 18, 24]), 6);
test('lcm across a list', lcmAll([2, 3, 4]), 12);
test('gcd times lcm equals the product', gcd(12, 18) * lcm(12, 18), 12 * 18);

The last assertion is a genuine identity worth knowing: for any two numbers, gcd(a,b) * lcm(a,b) === a * b. It makes a good self-check on any GCD implementation. Note also the ordering in lcm — dividing before multiplying keeps the intermediate result small, which matters once the inputs get large.

Common mistakes

  • Stopping when a is 0 instead of b. The loop must run until the second number of the pair is 0. Then the first number is the GCD.
  • Multiplying before dividing in lcm. a * b can grow huge. a / gcd(a, b) * b gives the same answer with a smaller number in the middle.
  • Forgetting the zero case in lcm. gcd(0, 0) is 0, and dividing by it gives NaN.

Try it yourself

  1. Use gcd to simplify a fraction: simplify(12, 18) should return [2, 3].
  2. Two buses leave the station every 12 and every 15 minutes. Use lcm to find how many minutes until they leave together again.
  3. Rewrite gcd with recursion: if b is 0 return a, otherwise return 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.