The GCD (Greatest Common Divisor), also called HCF, is the largest positive integer that divides both numbers with no remainder.
Remember
gcd(a, b) = largest d > 0 such that
a % d == 0 and b % d == 0
Example: gcd(48, 18) = 6
48 = 6 * 8
18 = 6 * 3
No larger positive integer divides both
a
b
gcd(a, b)
48
18
6
17
13
1
0
21
21
-12
18
6
Approach
How to Find GCD in JavaScript
Four clear steps — Euclid’s remainder loop is the interview default.
Take absolute values of a and b with Math.abs.
While b !== 0, replace (a, b) with (b, a % b).
When b becomes 0, return a — that is the GCD.
Optionally derive LCM with Math.abs(a / gcd * b).
Method
Idea
Time
Best for
Iterative Euclid
Loop with a % b until b === 0
O(log min)
Interviews, production default
Recursive Euclid
gcd(b, a % b) until base case
O(log min)
Showing the recurrence
LCM via GCD
|a / gcd * b|
O(log min)
Follow-up questions
Pseudocode
Pseudocode
function Gcd(a, b):
a = abs(a)
b = abs(b)
while b != 0:
temp = b
b = a mod b
a = temp
return a
function Lcm(a, b):
if a == 0 or b == 0:
return 0
return abs(a / Gcd(a, b) * b)
Reference
Cheat Sheet
Keep these facts handy while writing the program.
Topic
Detail
Core step
(a, b) ← (b, a % b)
Stop when
b === 0; answer is a
Signs
Use Math.abs first
gcd(0, n)
|n| for n !== 0
gcd(0, 0)
Usually defined as 0
LCM link
lcm = |a / gcd * b|
Classic check
gcd(48, 18) === 6
Try it
Live Preview
Enter two integers to see the Euclidean remainder chain and the GCD.
Same answer as the loop; stack depth is about O(log min(a, b)).
Prefer the iterative version when you must mention space carefully.
Example 3 — LCM via GCD
Use the identity lcm(a, b) = |a / gcd * b| after finding the GCD.
JavaScript
function gcd(a, b) {
a = Math.abs(a);
b = Math.abs(b);
while (b !== 0) {
const temp = b;
b = a % b;
a = temp;
}
return a;
}
function lcm(a, b) {
if (a === 0 || b === 0) {
return 0;
}
const g = gcd(a, b);
return Math.abs(a / g * b);
}
const a = 48;
const b = 18;
console.log("gcd = " + gcd(a, b));
console.log("lcm = " + lcm(a, b));