The greatest common divisor (GCD) of integers is the largest positive integer that divides each of them with remainder zero. (It is not a “denominator”—that word belongs to fractions.) For gcd javascript, javascript gcd, or greatest common divisor javascript, the standard approach is Euclid’s algorithm using the modulo form gcd(a, b) = gcd(b, a % b) until the second argument becomes zero.
Tested on: all examples in this tutorial were run with Node.js v20.18.2, and the output shown below each snippet is its exact console output.
Quick reference
Use this table for javascript gcd function choices.
| Need | Approach |
|---|---|
| Two integers, no deps | Euclidean loop or recursion with Math.abs |
| Array of integers | reduce with pairwise gcd |
| Huge integers | BigInt + same algorithm |
| Many args, convenience | mathjs gcd |
1. Recursive Euclidean javascript gcd
function gcd(a, b) {
if (b === 0) {
return a;
}
return gcd(b, a % b);
}
console.log(gcd(12, 18));62. Iterative form (often preferred for js gcd)
Same math, while loop instead of recursion:
function gcdIter(a, b) {
a = Math.abs(a);
b = Math.abs(b);
while (b !== 0) {
const t = b;
b = a % b;
a = t;
}
return a;
}
console.log(gcdIter(48, 18));
console.log(gcdIter(-12, 18));
console.log(gcdIter(0, 7));6
6
73. gcd in javascript for many numbers
Pairwise fold reuses any javascript gcd function for two arguments:
function gcdTwo(a, b) {
a = Math.abs(a);
b = Math.abs(b);
while (b !== 0) {
const t = b;
b = a % b;
a = t;
}
return a;
}
function gcdList(nums) {
return nums.reduce((acc, n) => gcdTwo(acc, n));
}
console.log(gcdList([12, 18, 24]));64. gcd in js with BigInt
Use 0n, %, and literals with n—do not mix BigInt and Number in the same arithmetic expression.
function gcdBig(a, b) {
a = a < 0n ? -a : a;
b = b < 0n ? -b : b;
while (b !== 0n) {
const t = b;
b = a % b;
a = t;
}
return a;
}
console.log(gcdBig(120n, 84n));12n5. Optional: mathjs for gcd js variadic calls
If a dependency is acceptable, math.gcd accepts several arguments (see mathjs docs). Install with npm install mathjs, then:
const { gcd } = require("mathjs");
console.log(gcd(12, 18, 24));6This line was captured with mathjs@13 in Node’s CommonJS require form.
Summary
- GCD is the largest shared divisor; Euclid’s algorithm uses repeated modulo until
b === 0. - Normalize negatives with
Math.abs(or sign checks forBigInt). - Fold
reduceacross an array for more than two operands;mathjshelps when you want variadic ergonomics.
References
Wikipedia and mathjs documentation for gcd javascript algorithms.
