Find GCD in JavaScript (Euclidean algorithm, BigInt, mathjs)

GCD in JavaScript (greatest common divisor, not denominator): Euclidean gcd recursive and iterative with Math.abs for negatives, reduce fold for many numbers, BigInt gcd without mixing Number, optional mathjs variadic gcd. Short section openers explain each pattern; runnable snippets include plain-language expected values.

Published

Updated

Read time 4 min read

Reviewed byDeepak Prasad

Find GCD in JavaScript (Euclidean algorithm, BigInt, mathjs)

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 searches, the usual implementation is Euclid’s algorithm: repeatedly replace (a, b) with (b, a % b) until b is zero. That shows up when simplifying fractions, aligning repeating cycles, and in small numeric utilities.

Tested on: Node.js v20.18.2. A short note after each snippet states the expected value; the mathjs example needs npm install mathjs and uses {run=false} in the in-page runner.


Quick reference

Use this table when you need a javascript gcd function for two numbers, a list, BigInt, or a quick variadic call via mathjs.

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

The recursive form matches the math definition directly: gcd(a, b) equals gcd(b, a % b) until b === 0, then return a. It is easy to read for js gcd tutorials; for very deep chains you may prefer iteration to avoid stack growth.

javascript
function gcd(a, b) {
  if (b === 0) {
    return a;
  }
  return gcd(b, a % b);
}

console.log(gcd(12, 18));
Output

You should see 6.


2. Iterative form (often preferred for js gcd)

An iterative javascript gcd function uses a while loop and swaps (a, b) with (b, a % b) until b is zero—same mathematics as recursion, usually better for production when inputs can be large. Math.abs normalizes signs so gcd javascript behaves the usual way on negative literals.

javascript
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));
Output

Three lines: 6, 6 again after normalizing -12, and 7 for gcd(0, 7).


3. gcd in javascript for many numbers

GCD is associative: gcd(a, b, c) equals gcd(gcd(a, b), c), so you can fold any non-empty list with reduce once you have a solid two-argument gcd in javascript helper.

javascript
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]));
Output

Folding pairwise over [12, 18, 24] yields 6.


4. gcd in js with BigInt

For integers larger than Number.MAX_SAFE_INTEGER, keep the whole javascript greatest common divisor calculation in BigInt: use 0n, %, and n literals end-to-end. Mixing BigInt with Number in one expression throws, so convert explicitly if you must bridge types.

javascript
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));
Output

You should see 12n.


5. Optional: mathjs for gcd js variadic calls

When a dependency is fine, mathjs exposes a variadic gcd so you can write gcd(12, 18, 24) without folding manually—useful for scripts and calculators, not for every bundle. Install with npm install mathjs, then require or import the function (mathjs gcd docs). The snippet is {run=false} because the public runner does not ship mathjs.

javascript
const { gcd } = require("mathjs");

console.log(gcd(12, 18, 24));
text
6

With mathjs installed locally (the article used mathjs@13 with CommonJS require), the log prints 6.


Summary

These patterns cover most javascript gcd needs in application code: a tiny Euclidean core, sign normalization, list folding, BigInt, and an optional mathjs shortcut.

  • GCD is the largest shared divisor; Euclid’s algorithm uses repeated modulo until b === 0.
  • Normalize negatives with Math.abs (or sign checks for BigInt).
  • Fold reduce across an array for more than two operands; mathjs helps when you want variadic ergonomics.

References

Wikipedia and mathjs documentation for gcd javascript algorithms.


Frequently Asked Questions

1. Is it greatest common divisor or denominator?

The correct term is greatest common divisor (GCD)—the largest integer that divides all inputs with no remainder. Denominator is the bottom of a fraction; it is a different concept.

2. How do I write a javascript gcd function for negative inputs?

Normalize with Math.abs on each operand before the Euclidean loop (or take absolute values inside each recursive step). GCD is usually defined for integers up to sign.

3. What is gcd(0, n) in JavaScript?

With the usual Euclidean loop and Math.abs, gcd(0, n) returns abs(n). If both inputs are 0, the result is conventionally 0.

4. Recursive or iterative gcd in javascript?

Both are correct. Iteration avoids deep recursion stacks on very long chains; recursion is often shorter to read.

5. How do I compute gcd for more than two numbers?

Fold pairwise: gcd(a,b,c) === gcd(gcd(a,b), c). The associative property of GCD makes this order-independent.

6. Can I use BigInt for javascript greatest common divisor?

Yes—the same modulo Euclidean algorithm works with 0n and bigint literals; keep operands as BigInt end-to-end.
Olorunfemi Akinlua

Boasting over five years of experience in JavaScript, specializing in technical content writing and UX design. With a keen focus on programming languages, he crafts compelling content and designs …