Skip to content
Devtoolry

Numbers · beginner

JavaScript Program to Find the GCD (HCF) of Two Numbers

Find the greatest common divisor (GCD or HCF) of two numbers in JavaScript with Euclid's algorithm, recursively and with a loop, and use it to get the LCM.

The greatest common divisor (GCD), or highest common factor (HCF), is the largest number that divides two numbers exactly. gcd(48, 18) is 6, which simplifies 48/18 to 8/3.

Euclid's algorithm uses one fact: gcd(a, b) = gcd(b, a % b), and gcd(a, 0) = a. It needs only a handful of steps even for large numbers. JavaScript has no built-in gcd function, so this is worth knowing.

The program

JavaScript
function gcd(a, b) {
  [a, b] = [Math.abs(a), Math.abs(b)];
  while (b !== 0) {
    [a, b] = [b, a % b];
  }
  return a;
}

console.log(gcd(48, 18));
console.log(gcd(17, 5));
console.log(gcd(0, 9));

const lcm = (a, b) => (a / gcd(a, b)) * b;
console.log("LCM:", lcm(12, 18));
Output
6
1
9
LCM: 36

How it works

  1. Math.abs() makes both numbers positive, so the result is positive too.
  2. While b is not 0, the pair (a, b) becomes (b, a % b): (48, 18) → (18, 12) → (12, 6) → (6, 0).
  3. When b reaches 0, a holds the GCD.
  4. The LCM is a × b ÷ gcd(a, b). Dividing first, (a / gcd) * b, keeps intermediate values smaller.

Watch it run line by line

Step through gcd(48, 18) and watch the pair a, b change on every pass: (18, 12), (12, 6), (6, 0). Then lcm calls gcd, so two frames are on the stack at once.

“Visualize step by step” opens the program in the JavaScript Compiler and records every step in your browser. Use the arrow keys to move forwards and backwards; changed variables are highlighted.

Another way: Recursive one-liner

The recursive form reads like the mathematical definition. Each call is one step of the algorithm, so the stack stays very small.

JavaScript
const gcd = (a, b) => (b === 0 ? Math.abs(a) : gcd(b, a % b));
console.log(gcd(48, 18), gcd(84, 126));
console.log([12, 18, 30].reduce(gcd));
Output
6 42
6

Common mistakes

  • Looping over every number up to min(a, b): correct but slow for large values.
  • Computing a * b / gcd for big numbers: a * b can exceed Number.MAX_SAFE_INTEGER even when the LCM does not.
  • Updating a and b in two separate statements, so the second uses the already-changed a.

Try it yourself

  • Simplify the fraction 84/126 with the GCD.
  • Compute the LCM of an array of numbers with reduce().

Open the program in the JavaScript Compiler, change it and press Run: there is nothing to install, and your code never leaves your browser.

Browse all 25 JavaScript examples, or write your own program in the online JavaScript Compiler.