Emmanuel Akinfulubi

JavaScriptMath

Calculate the LCM from the GCD in JavaScript

Intermediate · 4 min read

The least common multiple (LCM) of two numbers is the smallest number that both divide into. For 4 and 6 it is 12. You meet it whenever two cycles need to line up: one bus every 4 minutes and another every 6 meet again after 12 minutes. You also need it to add fractions with different bottoms.

In this tutorial you will write lcm(a, b) using the GCD, the greatest common divisor, from the previous exercise. Then you will find two ordinary-looking whole numbers where the textbook formula returns a value with a decimal part, and fix it by changing the order of one multiplication and one division. You need to know how gcd works.

The link between GCD and LCM

For any two positive whole numbers, the GCD times the LCM equals the two numbers multiplied together:

JavaScript

console.log(6 * 36, 12 * 18); // 216 216

The GCD of 12 and 18 is 6, and their LCM is 36. So the LCM is a * b / gcd(a, b). That formula is the whole method.

Safe integers, in one paragraph

JavaScript numbers count in exact steps of 1 only up to 2 to the 53rd, about 9 million billion (9e15). This limit is called Number.MAX_SAFE_INTEGER. Past it, the gaps between storable numbers get bigger than 1, so a result is rounded to the nearest storable value, without warning.

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

38 The least common multiple, from the GCD

fair

Write lcm(a, b) using the GCD. Then find a pair of ordinary-looking integers where a * b / gcd returns a value that is not even an integer, and a / gcd * b is exactly right.

Stuck? Three hints, smallest first
  1. 1. gcd(a, b) * lcm(a, b) === a * b, which is where the formula comes from.
  2. 2. Divide before you multiply: a / gcd is exact, and dividing first keeps the intermediate small.
  3. 3. Two numbers around 3e7 and 2.8e8 have a product past 2**53, where doubles stop counting in ones.

Step 1: a gcd to build on

Step 1

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

Step 2: the textbook formula

Step 2

const lcmNaive = (a, b) => (a * b) / gcd(a, b);
console.log(lcmNaive(4, 6));  // 12
console.log(lcmNaive(21, 6)); // 42
console.log(lcmNaive(9, 28)); // 252

All correct. When two numbers share no factor, like 9 and 28, the GCD is 1, so the LCM is just their product.

Step 3: two bigger numbers

Now take these two. Both are multiples of 12345679:

Step 3

const a = 37037037;
const b = 283950617;
console.log(gcd(a, b)); // 12345679
console.log(a * b);     // 10516689508001828
console.log(Number.isSafeInteger(a * b)); // false

Neither number is unusual. But their product is past the safe limit, so the printed value is already rounded. The true product is 10516689508001829, an odd number, and the stored value is one less.

Step 4: the wrong answer

Step 4

console.log(lcmNaive(a, b)); // 851851850.9999999
console.log(Number.isInteger(lcmNaive(a, b))); // false

A least common multiple with a decimal part. That can't be right: the LCM of two whole numbers is always a whole number. The formula isn't wrong. The problem is the order: multiplying first made a number too big to store exactly, and the error carried through the division.

Step 5: divide first

The GCD divides a exactly, by definition. So a / gcd(a, b) is always a whole number, and a small one. Do that division first, then multiply by b:

Step 5

const lcm = (a, b) => (a / gcd(a, b)) * b;
console.log(lcm(a, b)); // 851851851
console.log(Number.isSafeInteger(851851851)); // true

Exact. a / gcd is 3, and 3 times 283950617 is 851851851. The true LCM was a small, safe number all along. Only the middle step of the naive version was too big.

This is a habit worth keeping in any formula: when you multiply and then divide by something you know is a factor, divide first.

Step 6: the edge cases

Step 6

console.log(lcm(7, 7)); // 7
console.log(lcm(0, 5)); // 0
console.log(gcd(12, 18) * lcm(12, 18) === 12 * 18); // true

The LCM of a number with itself is the number. With a zero, gcd(0, 5) is 5 and 0 / 5 is 0, so the LCM is 0. The last line checks the GCD-times-LCM rule from the start.

The full solution

The answer panel builds gcd, both LCM versions and the two large numbers, then prints the small cases, the product, and both results for the large pair. The checks underneath confirm every value, including that multiplying first gives 851851850.9999999 and dividing first gives exactly 851851851. Press Run to see the output.

The answer

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

const lcmNaive = (a, b) => (a * b) / gcd(a, b);        // multiplies first
const lcm = (a, b) => (a / gcd(a, b)) * b;            // divides first

// Both share the factor 12345679, so the true LCM is small; only a * b is huge.
const a = 37037037;
const b = 283950617;

console.log('lcm(4, 6)       :', lcm(4, 6));
console.log('gcd * lcm       :', gcd(12, 18) * lcm(12, 18), 'and a * b:', 12 * 18);
console.log('gcd(a, b)       :', gcd(a, b));
console.log('a * b           :', a * b, '<- past 2**53, so already approximate');
console.log('multiply first  :', lcmNaive(a, b));
console.log('divide first    :', lcm(a, b));

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('lcm(4, 6) is 12, and lcm(21, 6) is 42', [lcm(4, 6), lcm(21, 6)], [12, 42]);
test('for coprime inputs it is just the product', lcm(9, 28), 252);
test('gcd times lcm is the product of the inputs', gcd(12, 18) * lcm(12, 18), 12 * 18);
test('lcm(n, n) is n, and lcm with 0 is 0', [lcm(7, 7), lcm(0, 5)], [7, 0]);
test('a and b share the factor 12345679', gcd(a, b), 12345679);
test('their product is not a safe integer', Number.isSafeInteger(a * b), false);
test('so multiplying first returns something that is not even whole', [lcmNaive(a, b), Number.isInteger(lcmNaive(a, b))], [851851850.9999999, false]);
test('while dividing first is exact', lcm(a, b), 851851851);
test('and the true LCM was a safe integer the whole time', Number.isSafeInteger(851851851), true);

The formula is not in question; the order of operations is. a * b here is 1.05e16, past 2 ** 53, so the product is rounded before the division ever happens and the result comes back as 851851850.9999999 — a least common multiple with a fractional part. a / gcd(a, b) is exact because the GCD divides a by definition, so dividing first keeps every intermediate inside the range where doubles count in ones.

This generalises past LCM. Whenever a formula multiplies then divides by something you know is a factor, reorder it. The combinatorics in exercise 55 is the same trick applied to n!, where the naive order overflows to Infinity instead of merely rounding.

Common mistakes

  • Multiplying before dividing. a * b can pass the safe limit even when the LCM is small. Write (a / gcd(a, b)) * b.
  • Trusting the printed product. Past 2 to the 53rd, the value shown is already rounded. Check with Number.isSafeInteger.
  • Calling lcm(0, 0). gcd(0, 0) is 0, so this divides 0 by 0 and returns NaN. Guard zeros if they can reach the function.

Try it yourself

  1. Two buses leave a station together, one every 12 minutes and one every 18. When do they next leave together?
  2. Add the fractions 1/4 and 1/6 by first finding the LCM of 4 and 6.
  3. Find another pair of numbers where lcmNaive gives a non-whole result. (Hint: pick two multiples of a large shared factor.)

Keep practising

Newsletter

New writing, when it lands.

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