Emmanuel Akinfulubi

JavaScriptMath

GCD and LCM of an array in JavaScript

Intermediate · 4 min read

The GCD and LCM are usually shown for two numbers. Real problems often have more. Three gear wheels with 12, 18 and 24 teeth, or traffic lights that change every 2, 3, 4 and 5 minutes: to find when they all line up, you need the LCM of the whole list.

In this tutorial you will extend gcd and lcm to whole arrays with reduce. The one decision that matters is the starting value, and the wrong choice gives a wrong answer for every list. Then you will solve a famous puzzle: the smallest number that divides evenly by every whole number from 1 to 20. You need to know the two-number gcd and lcm, and have seen reduce once.

reduce, in plain words

reduce walks through a list and keeps a running value. At each item, your function takes the running value and the item, and returns the new running value. The second argument to reduce is the starting value:

JavaScript

console.log([1, 2, 3, 4].reduce((total, x) => total + x, 0)); // 10

It goes 0 + 1, then 1 + 2, then 3 + 3, then 6 + 4. This works for GCD and LCM too, because the order you combine them in doesn't change the result: gcd(gcd(12, 18), 24) is the same as gcd(12, gcd(18, 24)).

The starting value must change nothing

For a sum, you start at 0, because adding 0 changes nothing. For a product, you start at 1. A starting value like that is called an identity. GCD and LCM each have one too, and finding them is the exercise.

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

39 GCD and LCM of a whole list

fair

Extend both operations to an array with reduce. Pick the right starting value for each, then find the smallest number divisible by every integer from 1 to 20.

Stuck? Three hints, smallest first
  1. 1. Both operations are associative, so folding pairwise across the list is valid.
  2. 2. gcd(0, n) is n, so 0 is the identity to start a GCD fold with. For LCM it is 1.
  3. 3. Fold the LCM with the divide-first form, or the running value will drift once it passes 2**53.

Step 1: the two-number helpers

Step 1

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

lcm divides first, so large values stay exact. It also returns 0 straight away when either input is 0. Without that check, lcm(0, 0) would divide 0 by gcd(0, 0), which is 0, and give NaN.

Step 2: the GCD fold, the wrong turn

"Fold" is another name for combining a list with reduce. Starting the GCD fold at 1 looks natural, but try it:

Step 2

console.log([12, 18, 24].reduce(gcd, 1)); // 1, but the answer is 6

gcd(1, anything) is 1, because nothing bigger than 1 divides 1. So the running value is stuck at 1 from the first step, whatever the list.

Step 3: start the GCD fold at 0

gcd(0, n) is n, because every number divides 0. So 0 changes nothing, and it is the identity for GCD:

Step 3

const gcdAll = (ns) => ns.reduce(gcd, 0);
console.log(gcdAll([12, 18, 24])); // 6
console.log(gcdAll([7]));          // 7
console.log(gcdAll([0, 0, 5]));    // 5

Passing gcd straight to reduce works because reduce calls it with the running value and the item first. It also passes an index and the array, but gcd ignores them.

Step 4: the LCM fold starts at 1

For LCM it is the other way round. lcm(1, n) is n, so 1 is the identity. Starting at 0 would make every answer 0:

Step 4

const lcmAll = (ns) => ns.reduce(lcm, 1);
console.log(lcmAll([2, 3, 4, 5])); // 60
console.log([2, 3, 4, 5].reduce(lcm, 0)); // 0

Step 5: the empty list

The starting value is also the answer for an empty list, since there is nothing to combine:

Step 5

console.log(gcdAll([]), lcmAll([])); // 0 1

Without a starting value at all, reduce on an empty list throws an error. Always pass one.

Step 6: the 1 to 20 puzzle

What is the smallest number that divides evenly by every whole number from 1 to 20? That is the LCM of 1 to 20. First make the list:

Step 6

const upTo = (n) => Array.from({ length: n }, (_, i) => i + 1);
console.log(upTo(5));         // [ 1, 2, 3, 4, 5 ]
console.log(lcmAll(upTo(10))); // 2520
console.log(lcmAll(upTo(20))); // 232792560

For 1 to 10 the answer is 2520, and for 1 to 20 it is 232,792,560. Is there anything smaller? Half of it fails for at least one number in the range, so no:

JavaScript

console.log(upTo(20).some((n) => (232792560 / 2) % n !== 0)); // true

Step 7: how fast it grows

Step 7

console.log(lcmAll(upTo(40))); // 5342931457063200
console.log(Number.isSafeInteger(lcmAll(upTo(40)))); // true

By 1 to 40 the answer is about 5.3e15, still under Number.MAX_SAFE_INTEGER, the largest whole number JavaScript stores exactly (about 9e15), but not by much. A bit further and the result stops being exact. At that point the problem needs BigInt, JavaScript's type for whole numbers of any size.

The full solution

The answer panel builds gcd, lcm, gcdAll, lcmAll and upTo, then prints the list results, the empty-list cases and the LCMs of 1 to 10, 20 and 40. The checks underneath confirm each one, including that zeros are ignored by the GCD fold and that the 1 to 40 result is still a safe integer. 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 lcm = (a, b) => (a === 0 || b === 0 ? 0 : (a / gcd(a, b)) * b);

const gcdAll = (ns) => ns.reduce(gcd, 0);        // 0 is the identity for gcd
const lcmAll = (ns) => ns.reduce(lcm, 1);        // 1 is the identity for lcm

const upTo = (n) => Array.from({ length: n }, (_, i) => i + 1);

console.log('gcd of 12, 18, 24 :', gcdAll([12, 18, 24]));
console.log('lcm of 2, 3, 4, 5 :', lcmAll([2, 3, 4, 5]));
console.log('empty list        :', gcdAll([]), lcmAll([]));
console.log('lcm of 1..10      :', lcmAll(upTo(10)));
console.log('lcm of 1..20      :', lcmAll(upTo(20)));
console.log('lcm of 1..40      :', lcmAll(upTo(40)), 'safe?', Number.isSafeInteger(lcmAll(upTo(40))));

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('the GCD of a list', gcdAll([12, 18, 24]), 6);
test('and its LCM', lcmAll([2, 3, 4, 5]), 60);
test('the identities make the empty list behave', [gcdAll([]), lcmAll([])], [0, 1]);
test('a single element folds to itself', [gcdAll([7]), lcmAll([7])], [7, 7]);
test('zeros are ignored by the GCD fold', gcdAll([0, 0, 5]), 5);
test('the numbers 1 to 10 all divide 2520', [lcmAll(upTo(10)), upTo(10).every((n) => 2520 % n === 0)], [2520, true]);
test('for 1 to 20 it is 232792560', lcmAll(upTo(20)), 232792560);
test('and half of it fails, so nothing smaller could work', upTo(20).some((n) => (232792560 / 2) % n !== 0), true);
test('1 to 40 still lands on a safe integer', [lcmAll(upTo(40)), Number.isSafeInteger(lcmAll(upTo(40)))], [5342931457063200, true]);

The identity value is the part that is easy to get wrong. Starting a GCD fold at 1 gives 1 for every list, since gcd(1, anything) is 1; starting at 0 works because gcd(0, n) is n. The LCM fold is the mirror image: 1 is the identity and 0 would swallow the list.

The LCM of 1 to 20 is 232,792,560, and it grows quickly — by 1 to 40 it is 5.34e15, still under Number.MAX_SAFE_INTEGER but not by much. Push the range to 45 and the fold silently leaves exact-integer territory, which is the point at which this problem belongs in BigInt rather than in doubles.

Common mistakes

  • Starting the GCD fold at 1. Every list then gives 1. Start at 0.
  • Starting the LCM fold at 0. Every list then gives 0. Start at 1.
  • Using the multiply-first LCM in a fold. The running value grows quickly, and multiplying first loses exactness sooner. Divide first.

Try it yourself

  1. Three gear wheels have 12, 18 and 24 teeth. Use lcmAll to find how many teeth must pass before all three line up again.
  2. Find the GCD of the prices 450, 600 and 750 naira.
  3. Find the first n for which lcmAll(upTo(n)) is no longer a safe integer.

Keep practising

Newsletter

New writing, when it lands.

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