Definition
Largest divisor
gcd(a, b) divides both; gcd = 1 means coprime.
The GCD of two integers is the largest positive integer that divides both. This tutorial covers Euclid’s algorithm (iterative and recursive), gcd, a live preview, worked JavaScript examples, edge cases, and complexity.
Largest divisor
gcd(a, b) divides both; gcd = 1 means coprime.
gcd(b, a%b)
Remainders shrink until b becomes 0.
gcd = 6
Trace: 48→18→12→6→0.
Helper
Reuse gcd in lcm and fraction reduction.
Try a, b
Compute gcd on magnitudes in the browser.
Euclid steps
Worst case near consecutive Fibonacci pairs.
The greatest common divisor gcd(a, b) is the largest positive integer that divides both a and b. Euclid’s rule gcd(a, b) = gcd(b, a % b) reduces the pair until the remainder is zero — then the leftover value is the answer.
Example: gcd(48, 18) = 6. If gcd is 1, the numbers are coprime. Also, lcm(a, b) = |a b| / gcd(a, b) for nonzero pairs.
GCD underpins fraction reduction, modular inverses, Diophantine equations, and many interview number-theory warm-ups.
(a, b) ← (b, a % b).
When b = 0, return a.
Keep the result nonnegative.
Equals |n| for n ≠ 0.
In short: replace (a, b) with (b, a % b) until b is 0; the leftover a is the gcd.
Given integers a and b, compute gcd(a, b).
// gcd(48, 18) = 6
// gcd(17, 13) = 1 (coprime)
// gcd(0, 21) = 21 | Item | Type | Description |
|---|---|---|
a, b | number | Any integers (we normalize with Math.abs). |
| Return | number | Nonnegative gcd (0 for the (0, 0) convention here). |
function gcd(a, b):
a = Math.abs(a)
b = Math.abs(b)
while b != 0:
(a, b) = (b, a mod b)
return a | Method | Idea | Notes |
|---|---|---|
| Iterative Euclid | Loop with % | O(1) extra space — interview default |
| Recursive Euclid | gcd(b, a % b) | Matches the math formula closely |
gcd | Helper function | Reuse in lcm and real projects |
| Goal | Pattern |
|---|---|
| Normalize | a = Math.abs(a); b = Math.abs(b) |
| Euclid step | a, b = b, a % b |
| Stop | while b != 0 then return a |
| Helper | gcd(a, b) |
| LCM | Math.abs(a * b) / gcd(a, b) |
| Classic | gcd(48, 18) = 6 |
Same Euclidean math — pick by clarity and constraints.
while b: a,b=b,a%bO(1) space — best default
gcd(b, a % b)Reads like the textbook rule
gcd()Reuse in lcm and fraction code
write EuclidThen mention gcd / binary gcd
Reach for GCD whenever common divisors or modular structure matter.
Classic modulo + loop problem with log-time analysis.
Divide numerator and denominator by gcd.
Inverse of a mod m exists when gcd(a, m) = 1.
Worst-case Euclid pairs are consecutive Fibonacci numbers.
State the convention (often 0) before coding.
Key benefit: a short log-time algorithm that unlocks fractions, LCM, and modular arithmetic.
Enter two integers (safe range). We compute gcd on magnitudes.
Three complete JavaScript programs — iterative Euclid, recursive Euclid, and a gcd helper with LCM. Click View Output to reveal sample console results.
Interview-default loop with constant extra space.
Uses a loop to compute gcd for 48 and 18.
function findGcd(num1, num2) {
num1 = Math.abs(num1);
num2 = Math.abs(num2);
while (num2 !== 0) {
[num1, num2] = [num2, num1 % num2];
}
return num1;
}
const number1 = 48;
const number2 = 18;
const g = findGcd(number1, number2);
console.log(`GCD of ${number1} and ${number2} is: ${g}`); Each loop step keeps the gcd unchanged and reduces the second value until it becomes zero. The leftover first value is the answer.
Same remainder chain, written as a recurrence.
Base case b == 0; otherwise recurse on (b, a % b).
function gcdRecursive(a, b) {
a = Math.abs(a);
b = Math.abs(b);
if (b === 0) {
return a;
}
return gcdRecursive(b, a % b);
}
const number1 = 48;
const number2 = 18;
console.log(`GCD of ${number1} and ${number2} is: ${gcdRecursive(number1, number2)}`); Recursive calls follow the same remainder chain as iterative Euclid, then return the final nonzero value. Stack depth is O(log min(a, b)).
Reuse gcd in the lcm formula for pairs of integers.
Shared gcd helper plus the classic LCM identity.
function gcd(a, b) {
a = Math.abs(a);
b = Math.abs(b);
while (b !== 0) {
[a, b] = [b, a % b];
}
return a;
}
function lcm(a, b) {
if (a === 0 || b === 0) {
return 0;
}
return Math.abs(a * b) / gcd(a, b);
}
for (const [a, b] of [[48, 18], [17, 13], [0, 21], [-12, 18]]) {
const g = gcd(a, b);
console.log(`gcd(${a}, ${b}) = ${g}, lcm = ${lcm(a, b)}`);
} Prefer a tested gcd helper in real projects (it also handles negatives). In interviews, write Euclid yourself first, then mention helper utilities and the LCM identity.
Set a = Math.abs(a), b = Math.abs(b).
While b != 0, replace (a, b) with (b, a % b).
When b is 0, a is the gcd.
Largest nonnegative common divisor.
gcd(48, 18)Trace the Euclidean remainder chain for the classic interview pair.
| Step | (a, b) | a % b | Next |
|---|---|---|---|
| 1 | (48, 18) | 12 | (18, 12) |
| 2 | (18, 12) | 6 | (12, 6) |
| 3 | (12, 6) | 0 | (6, 0) |
| 4 | (6, 0) | — | return 6 |
Final answer: gcd(48, 18) = 6.
Where GCD shows up beyond the interview prompt.
Modulo loops with clear log-time analysis.
Example: write findGcd(a, b).
Simplify p/q by dividing by gcd.
Example: 18/48 → 3/8.
Compute least common multiple safely.
Example: |a*b| / gcd(a, b).
Check coprimality for inverses.
Example: gcd(a, m) = 1.
GCD is the largest shared divisor.
Example: related interview page.
Extended Euclid finds x, y with ax + by = gcd.
Example: mention if asked for identity.
Pro Tip: say “gcd(a, b) = gcd(b, a % b)” before coding — it proves you know the invariant.
Why Euclid works well in interviews and classwork.
A few lines encode a deep number-theory idea.
O(log min(a, b)) steps in practice.
Iterative and recursive both match the math.
LCM, extended Euclid, and binary gcd.
Pro Tip: lead with iterative Euclid; offer recursive and gcd as follow-ups.
Small habits that keep GCD solutions interview-ready.
Keep the returned gcd nonnegative.
Say your convention (often 0) up front.
Expect 6; also try (0, 21) and (17, 13).
O(1) space and no recursion-depth worry.
Show you know |ab| / gcd when asked.
Pro Tip: worst-case Euclid step counts appear on consecutive Fibonacci inputs — a nice follow-up after the Fibonacci page.
Mistakes that commonly break GCD solutions.
Negative inputs can yield a negative-looking remainder story.
→ Normalize with abs first.
Crashing or returning nonsense.
→ Document convention (often return 0).
Looping from min(a, b) to 1 is O(min) and slow.
→ Use Euclid instead.
Computing a * b before dividing in fixed-width languages.
→ In JavaScript numbers are IEEE doubles; use Math.abs(a / g * b) or divide before multiply when values are huge.
Special-casing zero incorrectly.
→ Euclid already handles it if Math.abs is applied.
Normalize signs and define behavior for gcd(0, 0) explicitly.
gcd(0, 0)Many implementations return 0 by convention.
gcd(0, n)Equals |n| for n ≠ 0.
Use absolute values to keep gcd nonnegative.
gcd(a, b) = gcd(b, a)Input order does not change the answer.
gcd = 1Numbers share no common divisor greater than 1.
JavaScript supports them; runtime grows with digit length.
Handy follow-ups interviewers sometimes ask.
Try these variations to lock in the pattern.
Quick Takeaway: keep replacing (a, b) with (b, a % b) until b is 0; the leftover a is the gcd.
| Version | Time | Extra space |
|---|---|---|
| Iterative Euclid | O(log min(a, b)) | O(1) |
| Recursive Euclid | same | O(log min(a, b)) stack |
gcd | same order | O(1) |
Worst-case step count appears on consecutive Fibonacci inputs.
GCD is the largest nonnegative common divisor. Euclid reduces (a, b) via remainders until b is 0; write it iteratively in interviews and use gcd in production.
Practice the three examples above, then continue to LCM to pair gcd with the classic identity.
Normalize signs, define gcd(0, 0), and mention the LCM identity when asked.
Compute gcd the interview-friendly way.
gcd(b, a%b)
Euclidb = 0 → a
Baseuse Math.abs()
Guardgcd + lcm
ReuseO(log min)
AnalysisBézout's identity: for integers a, b not both zero, there exist integers x, y such that gcd(a,b) = a x + b y.
Learn how to find the least common multiple using the gcd identity.
9 people found this page helpful