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
6Implementation 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