Definition
Largest divisor
Largest positive d that divides both a and b (when not both zero).
GCD is a classic interview warm-up: remainders, loops, and the Euclidean algorithm. This tutorial covers the definition of gcd(a, b), iterative and recursive C programs, a live preview, algorithm steps, worked C examples, edge cases, and complexity.
Largest divisor
Largest positive d that divides both a and b (when not both zero).
a mod b
gcd(a, b) = gcd(b, a % b) until the remainder is zero.
O(1) space
A compact while loop is the interview default.
Base b = 0
Same math as a one-line recursive call on (b, a % b).
Two inputs
Compute gcd of two integers instantly in the browser.
|ab|/gcd
Least common multiple follows once you have the gcd.
GCD (greatest common divisor) of two integers that are not both zero is the largest positive integer that divides both. Euclid’s rule gcd(a, b) = gcd(b, a mod b) shrinks the pair until the remainder hits zero — the surviving value is the answer.
In C interviews you are usually asked to implement the Euclidean algorithm iteratively or recursively, discuss gcd(0, n), and note remainder-sign quirks with negatives.
GCD underpins fraction reduction, LCM, modular inverses, and linear Diophantine equations — a small function with wide reach in number theory and crypto warm-ups.
Stop when b = 0; return a.
Every divisor of n divides zero.
Iterative loop or recursive remainder chain.
Prefer nonnegative magnitudes before %.
In short: replace (a, b) with (b, a % b) until b is zero — the remaining a is gcd(a, b).
Given two integers a and b, compute their greatest common divisor using the Euclidean algorithm.
/* Remainder chain for gcd(48, 18)
* gcd(48, 18) = gcd(18, 12)
* = gcd(12, 6)
* = gcd( 6, 0)
* = 6
*/ | Item | Type | Description |
|---|---|---|
a, b | int | Two integers whose gcd to compute (interview demos often nonnegative). |
| Returned / printed gcd | int | Largest positive common divisor (or 0 for the (0, 0) convention). |
function gcd(a, b): // assume nonnegative; define gcd(0,0) as needed
while b != 0:
(a, b) = (b, a mod b)
return a | Method | Idea | Extra space |
|---|---|---|
| Iterative Euclid | Loop while b != 0, swap with remainder | O(1) |
| Recursive Euclid | Return gcd(b, a % b) with base b == 0 | O(log min(a,b)) stack |
| Goal | Pattern |
|---|---|
| Euclid step | (a, b) = (b, a % b) |
| Base case | if (b == 0) return a; |
| Iterative body | temp = b; b = a % b; a = temp; |
| Zero partner | gcd(0, n) = |n| for n ≠ 0 |
| LCM from GCD | lcm = |a / gcd * b| (order carefully to reduce overflow) |
All compute gcd — pick based on clarity and constraints.
while b != 0Interview default — O(1) extra space
gcd(b, a%b)Matches the math line-for-line; uses call stack
shiftsUseful for big integers; overkill for plain int
mention LCMKnow gcd(0,n), signs, and lcm = |ab|/gcd
Reach for GCD when divisibility and modular math matter.
Quick check of loops, remainders, and edge cases like zero.
Divide numerator and denominator by gcd to lowest terms.
Inverse exists iff gcd(a, m) = 1; extended Euclid finds it.
Combine periods or array sizes via lcm = |ab|/gcd.
GCD finds the shared divisor; listing all common divisors is a different prompt.
Key benefit: a tiny algorithm that unlocks fractions, LCM, inverses, and Diophantine checks.
Enter two integers and compute gcd using the same Euclidean recurrence as the C samples.
Two complete C programs — iterative and recursive Euclidean — both for 48 and 18. Click View Output to reveal sample console results.
Classic iterative Euclid for nonnegative interview inputs.
Loop while the remainder is nonzero; when b becomes 0, a holds the gcd.
#include <stdio.h>
int find_gcd(int num1, int num2) {
while (num2 != 0) {
int temp = num2;
num2 = num1 % num2;
num1 = temp;
}
return num1;
}
int main(void) {
int number1 = 48;
int number2 = 18;
int g;
g = find_gcd(number1, number2);
printf("GCD of %d and %d is: %d\n", number1, number2, g);
return 0;
} Each iteration stores the old b in num1 and replaces b by a % b. When b becomes 0, num1 holds the gcd.
Same result with a recursive remainder chain.
Base case gcd(a, 0) = a; otherwise recurse on (b, a % b).
#include <stdio.h>
int gcd_recursive(int a, int b) {
if (b == 0) {
return a;
}
return gcd_recursive(b, a % b);
}
int main(void) {
int number1 = 48;
int number2 = 18;
printf("GCD of %d and %d is: %d\n", number1, number2,
gcd_recursive(number1, number2));
return 0;
} The call stack mirrors the manual remainder sequence. Depth is O(log min(|a|, |b|)) in typical cases — fine for interview-sized integers.
Take absolute values if you want a nonnegative gcd; define (0, 0) separately if needed.
While b ≠ 0, set (a, b) ← (b, a % b).
When b == 0, the remaining a is the gcd.
For (48, 18) the result is 6.
gcd(48, 18)Trace the Euclidean remainder chain until the remainder is zero.
| Step | Pair (a, b) | a % b | Next pair |
|---|---|---|---|
1 | (48, 18) | 12 | (18, 12) |
2 | (18, 12) | 6 | (12, 6) |
3 | (12, 6) | 0 | (6, 0) |
4 | (6, 0) | — | return 6 |
So gcd(48, 18) = 6. Reducing 18/48 by dividing by 6 yields 3/8.
Where gcd shows up beyond the interview prompt.
Divide numerator and denominator by their gcd.
Example: 18/48 → 3/8.
Compute least common multiple via |ab|/gcd.
Example: schedule alignment, array tiling.
Exists when gcd(a, m) = 1; extended Euclid finds it.
Example: modular arithmetic, crypto warm-ups.
ax + by = c is solvable iff gcd(a, b) | c.
Example: coin problems, linear constraints.
RSA and CRT setups need gcd = 1 in places.
Example: choose e coprime to φ(n).
All common divisors divide the gcd — the max is gcd itself.
Example: list divisors of gcd(a, b).
Pro Tip: if the interviewer asks for LCM, compute gcd first and form |a / gcd * b| carefully to reduce overflow risk.
Why Euclid’s algorithm earns interview points.
A few lines of code with logarithmic steps for fixed-width ints.
Easy to prove and explain: common divisors survive the remainder step.
No need to scan all divisors up to min(a, b).
Extended Euclid and LCM build directly on the same loop.
Pro Tip: lead with iterative Euclid; offer the recursive form as the mathematical twin if asked.
Small habits that keep GCD code clean in interviews.
Take absolute values before the loop so remainder signs stay simple.
State your convention (often return 0) in library-style code.
Same math as recursion with O(1) auxiliary space.
Compute a / gcd * b (not a * b / gcd first) when overflow is a risk.
Verify (17, 13), (0, 21), and (48, 18) before claiming done.
Pro Tip: dry-run gcd(48, 18) on paper (table above) before coding — it locks in the remainder chain.
Mistakes that commonly break GCD solutions in C.
C’s % follows toward-zero division; signs can surprise you.
→ Normalize to nonnegative magnitudes first.
The loop returns 0, but some specs leave it undefined.
→ Document your convention in comments or docs.
abs(INT_MIN) HazardAbsolute value of INT_MIN is undefined for int in C.
→ Use wider types or unsigned magnitude tricks when normalizing.
Scanning all candidates up to min(a,b) is slower and noisier.
→ Prefer the remainder loop unless the prompt demands otherwise.
a * b may overflow before dividing by gcd.
→ Compute a / gcd * b with care (and wider types if needed).
Check these inputs before calling the solution done.
gcd(0, n)For n > 0, result is n (or |n| after normalizing).
gcd(0, 0)Loop returns 0; some definitions leave this undefined.
gcd = 1E.g. (17, 13) — still a valid, important outcome.
Mathematical gcd is nonnegative — normalize before %.
abs hazardabs(INT_MIN) is undefined for int; use wider types carefully.
gcd(a,b)=gcd(b,a)Either argument order is fine after the first Euclid step.
Known results for common interview pairs.
(a, b) | gcd |
|---|---|
(48, 18) | 6 |
(17, 13) | 1 |
(0, 21) | 21 |
(12, 18) | 6 |
Try these variations to lock in the pattern.
scanf and print the gcdfind_gcd, then form LCM safely(48, 18) → LCM 144gcd(0, n) = |n| for nonzero n; decide what gcd(0, 0) should return.int, iterative Euclid is already optimal in practice; Stein helps more with big integers.Quick Takeaway: gcd(a, b) = gcd(b, a % b) until b = 0 — iterative Euclid is fast, tiny, and interview-ready.
| Version | Time | Extra space |
|---|---|---|
| Iterative Euclid | O(log min(a, b)) steps (worst Fibonacci pair) | O(1) |
| Recursive Euclid | same | O(log min(a, b)) stack frames |
Lamé’s theorem bounds the number of division steps for inputs with a fixed number of digits.
GCD via Euclid is a small remainder-loop exercise with big payoff: fractions, LCM, modular inverses, and Diophantine checks all build on it. Master both the iterative and recursive forms so you can explain either in an interview.
Practice the two examples above, then continue to happy numbers for another classic digit-iteration warm-up.
Replace (a, b) with (b, a % b) until b = 0, normalize signs, and remember gcd(0, n) = |n|.
gcd(a,b)=gcd(b,a%b) before codinggcd(0,0)abs(INT_MIN) carelesslya * b / gcd without overflow care(0, n) edge caseCompute gcd the interview-friendly way.
gcd(b, a % b)
EuclidWhen b = 0, return a
BaseO(1) space loop
CodeSame math, stack depth
CodeO(log min(a,b))
AnalysisBézout’s identity: for integers a, b not both zero, there exist integers x, y with gcd(a,b) = a x + b y. The extended Euclidean algorithm finds such coefficients while computing the gcd.
Learn how to check whether a number reaches 1 under repeated digit-square sums.
8 people found this page helpful