Dev Helpers

JavaScript / Algorithms

Compute greatest common divisor

Dev Helpers · April 3, 2026

The Euclidean algorithm reduces a pair by taking successive remainders. Each step produces a smaller divisor until the remainder reaches zero.

Worked example

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

Result

6

Implementation notes

Specify a sign convention for the result. Many callers expect a nonnegative divisor even if one input was negative.

Try it yourself

Try a multiple of the other number and a pair of coprime numbers.

Open the JavaScript example →

Editorial date April 3, 2026 · Published December 6, 2026

Related articles

Sum distances with a Euclidean norm

A diagonal is longer than either of its components. Math.hypot combines perpendicular distances without making the caller square each input.

Build an OS-independent path

Path conventions belong to the destination. Use an explicit path flavour when generating portable asset names.

Resolve ranked ties

A leaderboard needs an explicit tie policy. Ranking tied scores and sorting their display order are separate decisions.