- What a GCD is, in everyday language — not just the textbook definition
- How Euclid's algorithm works and why it's been trusted for over 2,000 years
- How to write the modulo version in a compact
whileloop - How the repeated-subtraction version works (useful when the modulo is expensive)
- How to handle zero and negative inputs without silent bugs
- Why the loop is guaranteed to terminate
What GCD Really Means
The GCD of two numbers is the largest number that divides both of them without leaving a remainder. If you've ever cut a rectangular piece of paper into identical square tiles with the fewest cuts, you've worked out a GCD. A 24 by 36 cm sheet becomes 6 by 6 cm tiles because GCD(24, 36) = 6 — the largest square that fits whole-number times across both sides.
That's the mental picture to keep. The GCD is the largest square ruler that can measure both lengths exactly. When one number divides the other (say, 12 and 36), the smaller number is automatically the GCD, because it measures both. When they share no common factor other than 1 (like 8 and 15), the GCD is 1 — they're called coprime.
For a loop assignment, the interesting part isn't what the GCD is. It's how to compute it without trying every possible divisor. That's where Euclid comes in.
💡 In one line: GCD(a, b) is the largest number that divides both a and b with no remainder. Euclid's algorithm gets there without ever testing divisors one by one.
Euclid's Algorithm in Plain English
The rule is short: the GCD of a and b is the same as the GCD of b and the remainder when a is divided by b. Repeat that swap until the remainder is zero. The last non-zero number is the GCD.
Why does it work? Because any number that divides both a and b must also divide a − q·b for any integer q — and a % b is exactly the leftover after subtracting as many bs as possible. So the common divisors of (a, b) are precisely the common divisors of (b, a % b). Same set, smaller numbers. The numbers shrink on every step, so the loop must stop — at zero.
Here's the trace for GCD(48, 18):
| Step | a | b | a % b | Action |
|---|---|---|---|---|
| 1 | 48 | 18 | 12 | a ← 18, b ← 12 |
| 2 | 18 | 12 | 6 | a ← 12, b ← 6 |
| 3 | 12 | 6 | 0 | a ← 6, b ← 0 |
| — | 6 | 0 | — | b is zero — stop. GCD = 6 |
Three iterations. A brute-force loop from 1 to min(48, 18) would take 18 iterations. For larger numbers the gap gets enormous — that's why Euclid's algorithm is still used in cryptography and computer algebra today.
Complete C Program
Program: GCD using a while loop (modulo version)
#include <stdio.h>
int main(void) {
int a, b;
printf("Enter two integers: ");
if (scanf("%d %d", &a, &b) != 2) {
printf("Invalid input.\n");
return 1;
}
/* Work with absolute values so negatives don't break the modulo */
if (a < 0) a = -a;
if (b < 0) b = -b;
if (a == 0 && b == 0) {
printf("GCD of 0 and 0 is undefined.\n");
return 0;
}
if (a == 0) {
printf("GCD = %d\n", b);
return 0;
}
if (b == 0) {
printf("GCD = %d\n", a);
return 0;
}
/* Euclid's algorithm — the loop shrinks the pair until b hits 0 */
while (b != 0) {
int rem = a % b;
a = b;
b = rem;
}
printf("GCD = %d\n", a);
return 0;
}
And here is the same algorithm written as the repeated-subtraction version. It's slower for large gaps but easier to reason about if you're meeting the idea for the first time:
Same GCD, using repeated subtraction
/* Both a and b are positive at this point */
while (a != b) {
if (a > b)
a = a - b;
else
b = b - a;
}
/* Loop ends when a == b, and that common value is the GCD */
printf("GCD = %d\n", a);
Both versions arrive at the same answer. The modulo version usually runs in far fewer iterations, because a single a % b subtracts as many copies of b as fit. The subtraction version is the historical form of the algorithm, useful when modulo is costly on small microcontrollers.
Program Output
Enter two integers: 48 18
GCD = 6
Try a few more: 100 and 75 give 25. 17 and 13 give 1 (they're coprime). 8 and 0 give 8. 0 and 0 print the "undefined" message. Each of these exercises a different branch of the input handling.
Step-by-Step Explanation
Let's follow the program through the 48 and 18 case, then look at the parts that often confuse beginners.
1. Reading input safely
scanf("%d %d", &a, &b) returns the number of values it successfully read. Checking for exactly 2 protects the program from being fed letters or an empty input. If the user types something that isn't a number, the program prints "Invalid input." instead of computing nonsense.
2. Absolute values
a % b in C keeps the sign of a, so -48 % 18 is -12, not 12. That can drive the loop into negative territory and produce a wrong answer. Converting both inputs to positive at the start sidesteps the problem entirely. The GCD is always non-negative, so this is safe.
3. The zero checks
Euclid's algorithm assumes both numbers are positive. The three early returns handle the edge cases before the loop: if both are zero, GCD is undefined; if one is zero, the GCD is the other number. (Yes, GCD(0, b) = |b| — every non-zero number divides 0 cleanly.) Without these checks, 0 % 0 would trigger undefined behaviour.
4. The while loop
The loop runs as long as b isn't zero. Inside, rem = a % b finds the leftover. Then we slide the pair: a = b and b = rem. Each iteration, b becomes strictly smaller (because a % b < b), so the loop cannot spin forever. When b finally hits zero, a holds the GCD.
For 48 and 18:
rem = 48 % 18 = 12;a = 18,b = 12rem = 18 % 12 = 6;a = 12,b = 6rem = 12 % 6 = 0;a = 6,b = 0b == 0— exit;a = 6is the GCD
5. Why the loop must stop
Because a % b is always strictly less than b (as long as b > 0), each iteration replaces b with something smaller. The sequence of b values is a strictly decreasing sequence of non-negative integers, so it must reach 0 in finitely many steps. This is the same argument behind every "the algorithm terminates" proof you'll see for Euclid's method.
6. Why not start at the smaller number and count down?
You could: for (i = min(a, b); i >= 1; i--) if (a % i == 0 && b % i == 0) break;. That's simpler to read, and it's a fine first attempt. But for GCD(1,000,000, 999,999) it tests roughly a million candidates, while Euclid's algorithm finishes in about 20 steps. Euclid wins, every time, and that's why it's the algorithm taught — and asked about in interviews.
7. A hidden benefit: LCM for free
Once you have GCD, LCM is one multiplication away: LCM(a, b) = (a / GCD(a, b)) * b. Dividing before multiplying keeps the intermediate result small and avoids overflow. The LCM assignment on this site uses exactly that relationship — it's worth reading next.
🎯 Remember this: Euclid's algorithm says GCD(a, b) = GCD(b, a % b). Repeat until the second number is zero, and the first number is your answer. The loop is short, fast, and guaranteed to stop — and it's the same idea behind the LCM, coprime, and amicable-number programs in this series.
Frequently Asked Questions
1. Why does the loop stop when b becomes zero?
Because by then, a has absorbed all the shared factors. In each iteration we replace (a, b) with (b, a % b). The last non-zero b before the zero step is the GCD — and once we shift, that value sits in a. So when the loop exits, a is the answer.
2. What if the user enters negative numbers?
The program converts them to positive at the start with if (a < 0) a = -a;. C's % operator keeps the sign of the left operand, so -48 % 18 is -12 — that would push the loop into negative values and produce the wrong answer. Taking absolute values is the simplest fix. The GCD is always reported as a positive number.
3. Is the modulo version always faster than repeated subtraction?
In terms of iterations, almost always yes. a % b is equivalent to subtracting b repeatedly until the result is less than b, but it does the job in a single machine instruction on most CPUs. There is one exception: on a few small microcontrollers, division is emulated in software and can be much slower than a subtract loop. For those, the subtraction version may win.
4. What is GCD(0, 0)?
Mathematically, it's undefined. Every number divides 0, so there's no largest common divisor. The program prints "GCD of 0 and 0 is undefined." That's the honest answer — inventing 0 or 1 would be misleading. If you need to keep the code compact, returning 0 is a common convention, but a printed message is clearer for a teaching program.
5. Can I use a for loop instead of while?
Yes, but the syntax gets awkward because you don't know in advance how many iterations you'll need. Write for (; b != 0; ) { int rem = a % b; a = b; b = rem; } and it works, but a while loop is the more natural fit here. This is the general guideline: use while when you're repeating until a condition changes, and for when you know the number of iterations.
6. How is this used in real programs?
GCD shows up in reducing fractions, aligning memory or buffer sizes, determining the size of the smallest repeating unit in tiling problems, and — with the extended version — in modular inverses for RSA encryption. Whenever you need "the largest common chunk," the answer is somewhere in Euclid's algorithm.
💡 Tip: Once this program clicks, try solving it again using the repeated-subtraction loop above. You'll find you understand why the modulo version works once you've walked through the slower version by hand. Then move on to the LCM assignment — it builds directly on this one with a single extra line.