GCD and LCM with zero and negative numbers in JavaScript
Beginner · 4 min read
Simplifying 84/126 to 2/3, finding when two repeating events next line up, fitting tiles into a grid: these all come down to two numbers. The greatest common divisor (GCD) is the biggest number that divides both. The lowest common multiple (LCM) is the smallest number that both divide into.
In this tutorial you will write gcd with a method that is over two thousand years old, Euclid's algorithm, and build lcm on top of it. You will make both work with zeros and negative numbers, use them to simplify a fraction, and then find a pair of numbers where an ordinary JavaScript number can't hold the right answer. You need to know %, while loops and arrow functions.
GCD and LCM by example
Take 4 and 6.
- The numbers that divide 4 are 1, 2, 4. The numbers that divide 6 are 1, 2, 3, 6. The biggest one they share is 2, so
gcd(4, 6)is 2. - The multiples of 4 are 4, 8, 12, 16... The multiples of 6 are 6, 12, 18... The first one they share is 12, so
lcm(4, 6)is 12.
There is a neat link between them: gcd(a, b) * lcm(a, b) equals a * b. Here 2 * 12 = 24 = 4 * 6. So once you have the GCD, the LCM comes for free.
Euclid's idea
Listing every divisor is slow. Euclid noticed that the GCD of a and b is the same as the GCD of b and a % b. Keep replacing the pair until the second number is 0, and the first number is the answer.
gcd(48, 18) -> gcd(18, 12) -> gcd(12, 6) -> gcd(6, 0) -> 6
Here is the exercise. If you'd like to try it first, go ahead. Otherwise, read on and we will build it together.
83 Greatest common divisor and lowest common multiple
easyWrite gcd by Euclid's algorithm and lcm in terms of it, make both survive zeros and negatives, use them to reduce 84/126 to its lowest terms, and then try the pair 123456789 and 987654321 to see whether a double can still hold the answer.
Stuck? Three hints, smallest first
- 1. Euclid: replace the pair
(a, b)with(b, a % b)untilbis 0. - 2.
gcd(a, b) * lcm(a, b)isa * b, which gives youlcmfor free. - 3. Divide before you multiply.
a * bcan leave the safe integer range even when the answer would fit.
Step 1: Euclid's algorithm
const gcd = (a, b) => {
a = Math.abs(a);
b = Math.abs(b);
while (b) [a, b] = [b, a % b];
return a;
};
console.log(gcd(48, 18), gcd(17, 5)); // 6 1
while (b) keeps going while b is not 0. The line [a, b] = [b, a % b] swaps in the new pair in one go; this is called destructuring assignment. Two numbers whose GCD is 1, like 17 and 5, share no factor at all.
Math.abs at the start makes negative inputs work: a divisor of -48 is also a divisor of 48.
Step 2: zeros
console.log(gcd(0, 5), gcd(5, 0), gcd(0, 0), gcd(-48, 18)); // 5 5 0 6
Every number divides 0, so the GCD of 0 and 5 is 5. gcd(0, 0) returns 0, which is the usual convention. No special code is needed: the loop already handles them.
Step 3: lcm, and the zero guard
The obvious LCM comes straight from the link above:
const lcmNaive = (a, b) => Math.abs(a * b) / gcd(a, b);
console.log(lcmNaive(4, 6), lcmNaive(0, 0)); // 12 NaN
It works for 4 and 6, but lcmNaive(0, 0) is 0 / 0, which is NaN. Here is a better version:
const lcm = (a, b) => (a === 0 || b === 0 ? 0 : Math.abs(a / gcd(a, b)) * Math.abs(b));
console.log(lcm(4, 6), lcm(21, 6), lcm(0, 5), lcm(0, 0)); // 12 42 0 0
It returns 0 if either number is 0. It also divides before it multiplies. That matters in Step 6.
Step 4: simplify a fraction
To reduce a fraction to lowest terms, divide the top and bottom by their GCD.
const reduceFraction = (n, d) => {
const g = gcd(n, d);
return [n / g, d / g];
};
console.log(reduceFraction(84, 126)); // [ 2, 3 ]
gcd(84, 126) is 42, and 84 / 42 is 2, 126 / 42 is 3.
Step 5: more than two numbers
console.log([12, 18, 24].reduce(gcd), [4, 6, 10].reduce(lcm)); // 6 60
reduce feeds the running answer and the next number back into the function. This works because the GCD of three numbers is the GCD of the first two, then that with the third. The same goes for LCM.
Step 6: a pair that's too big
Now try 123456789 and 987654321.
console.log(lcm(123456789, 987654321), lcmNaive(123456789, 987654321)); // 13548070123626140 13548070123626140
Both versions agree, and both are wrong. The true answer is 13548070123626141. JavaScript numbers hold whole numbers exactly only up to 2 ** 53, about 9 quadrillion, and this answer is bigger. The last digit gets rounded away. Two versions agreeing proves nothing when they share the same limit.
Step 7: BigInt for the exact answer
BigInt is a separate number type for whole numbers of any size. You write one with an n on the end, like 5n.
const gcdBig = (a, b) => {
if (a < 0n) a = -a;
if (b < 0n) b = -b;
while (b) [a, b] = [b, a % b];
return a;
};
const lcmBig = (a, b) => (a / gcdBig(a, b)) * b;
console.log(String(lcmBig(123456789n, 987654321n))); // 13548070123626141
It is the same algorithm, but with BigInt values, so nothing is rounded. Division with BigInt drops any fraction, which is fine here because the GCD always divides evenly. String turns the result into text for printing.
The full solution
The answer panel has gcd, both lcm versions, reduceFraction and the BigInt pair, and prints every case above. Press Run to see the output.
const gcd = (a, b) => {
a = Math.abs(a);
b = Math.abs(b);
while (b) [a, b] = [b, a % b];
return a;
};
// Divide first: a * b overflows the safe range long before the lcm does.
const lcm = (a, b) => (a === 0 || b === 0 ? 0 : Math.abs(a / gcd(a, b)) * Math.abs(b));
const lcmNaive = (a, b) => Math.abs(a * b) / gcd(a, b);
const reduceFraction = (n, d) => {
const g = gcd(n, d);
return [n / g, d / g];
};
// BigInt versions, for when the answer is bigger than a double can hold exactly.
const gcdBig = (a, b) => {
if (a < 0n) a = -a;
if (b < 0n) b = -b;
while (b) [a, b] = [b, a % b];
return a;
};
const lcmBig = (a, b) => (a / gcdBig(a, b)) * b;
console.log('gcd(48, 18) :', gcd(48, 18));
console.log('gcd with 0 or - :', gcd(0, 5), gcd(5, 0), gcd(0, 0), gcd(-48, 18));
console.log('lcm(4, 6) :', lcm(4, 6), 'lcm(21, 6):', lcm(21, 6));
console.log('gcd * lcm = a * b:', gcd(21, 6) * lcm(21, 6), 21 * 6);
console.log('84 / 126 reduces :', reduceFraction(84, 126));
console.log('lists :', [12, 18, 24].reduce(gcd), [4, 6, 10].reduce(lcm));
console.log('big pair, double :', lcm(123456789, 987654321), lcmNaive(123456789, 987654321));
console.log('big pair, BigInt :', String(lcmBig(123456789n, 987654321n)));
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.
test('gcd(48, 18) is 6, and two coprime numbers share only 1', [gcd(48, 18), gcd(17, 5), gcd(35, 64)], [6, 1, 1]);
test('Euclid handles zeros and negatives once you take absolutes', [gcd(0, 5), gcd(5, 0), gcd(0, 0), gcd(-48, 18)], [5, 5, 0, 6]);
test('lcm(4, 6) is 12 and lcm(21, 6) is 42', [lcm(4, 6), lcm(21, 6)], [12, 42]);
test('gcd times lcm gives back the product, which is why one defines the other', gcd(21, 6) * lcm(21, 6) === 21 * 6, true);
test('the guard matters: the unguarded lcm of 0 and 0 is NaN', [lcm(0, 5), lcm(0, 0), Number.isNaN(lcmNaive(0, 0))], [0, 0, true]);
test('84 / 126 reduces to 2 / 3 by dividing both by the gcd', reduceFraction(84, 126), [2, 3]);
test('reduce over a list works because both are associative', [[12, 18, 24].reduce(gcd), [4, 6, 10].reduce(lcm)], [6, 60]);
test('for 123456789 and 987654321 both double routes give the same wrong answer', [lcm(123456789, 987654321), lcmNaive(123456789, 987654321)], [13548070123626140, 13548070123626140]);
test('the true lcm ends in 141, and only BigInt says so', String(lcmBig(123456789n, 987654321n)), '13548070123626141');
Euclid's algorithm is three lines and it is still the fastest thing anyone knows for this. Each step replaces (a, b) with (b, a % b), which shrinks the pair quickly — gcd(123456789, 987654321) settles in a handful of iterations. Taking absolute values first makes it total: negatives work, one zero returns the other operand, and gcd(0, 0) is 0 by convention.
lcm is where the bug lives. Written as a * b / gcd(a, b) it computes a product that may be far larger than the answer, and once that product passes Number.MAX_SAFE_INTEGER the division cannot recover the lost bits. Dividing first — a / gcd(a, b) * b — pushes the limit out, and it costs nothing.
It does not push it out far enough here. The true lcm of 123456789 and 987654321 is 13548070123626141, which is above 2 ** 53, so both double versions return 13548070123626140 and agree with each other while being wrong. That agreement is the trap: two implementations matching is not evidence when both share the same representation. BigInt gets the last digit right because it never rounds.
Common mistakes
- Multiplying before dividing in
lcm.a * bcan grow past the safe range even when the answer would fit. Divide by the GCD first. - Forgetting the zero case in
lcm.lcm(0, 0)with the plain formula isNaN. Return 0 when either input is 0. - Trusting two matching answers. Above 2 ** 53, two Number calculations can agree and both be wrong. Use BigInt when the result can be that big.
Try it yourself
- Two buses leave together. One comes every 12 minutes, the other every 18. After how many minutes do they leave together again?
- Change
reduceFractionso that the minus sign always ends up on the top, soreduceFraction(3, -6)gives[-1, 2]. - Add a counter to
gcdand find out how many loopsgcd(123456789, 987654321)takes.