- How to extend the GCD definition from two numbers to three (and beyond)
- Why the search only needs to run up to
min(a, b, c) - How to use a nested loop to test divisibility against three inputs at once
- How the same problem is solved much faster by chaining two
gcdcalls - Why
GCD(a, b, c) = GCD(GCD(a, b), c)— and what that means in practice
Extending GCD to Three Numbers
Two numbers have a GCD — the largest number that divides both. Three numbers have a GCD too: the largest number that divides all three. It's the natural extension. The GCD of 12, 18, and 30 is 6, because 6 divides all three cleanly and nothing larger does. The GCD of 8, 15, and 22 is 1, because no number beyond 1 divides all three — they're collectively coprime, even though some pairs might not be (though here, every pair is coprime).
The visual intuition is the same as for two numbers. Imagine three pieces of wood — say 12, 18, and 30 cm long — and you want to cut all three into equal-length pieces with no waste. The largest piece size that works is the GCD of the three lengths: 6 cm. Each board gives you 2, 3, and 5 pieces respectively, and nothing is left over.
The assignment asks you to do this with nested loops. That's the "brute-force" approach: try each candidate from 1 upward, and see whether it divides all three. It's slower than the clever trick — chaining two GCD calls — but it generalises easily to any number of inputs, and it's a good exercise in nested loops.
💡 In one line: the GCD of three numbers is the largest integer that divides all three. The loop runs from 1 to min(a, b, c), and the largest value that passes the divisibility test is the answer.
Two Ways to Compute GCD(a, b, c)
There are two sensible approaches. The assignment asks for the nested-loop version, but you should know the faster one because it's what real code uses — and because it raises a useful question about how the "nested loop" is genuinely different.
Method 1: Brute-force search (the assignment)
Start at i = 1 and go up to min(a, b, c). For each i, check whether a % i == 0 AND b % i == 0 AND c % i == 0. The largest value that passes is the GCD. This is O(min(a,b,c)) — fine for small inputs, slow for large ones (for GCD(999999, 999998, 999997), it runs nearly a million iterations).
Method 2: Chain two GCD calls (the fast path)
The GCD operation is associative: GCD(a, b, c) = GCD(GCD(a, b), c). So you compute the GCD of the first two numbers with the Euclidean algorithm (which takes about 20 iterations for any input under a billion), then take the GCD of that result with the third. Total: about 40 iterations. That's a factor of roughly 25,000 faster for a million-sized input, and it becomes more dramatic as inputs grow.
| Approach | Idea | Iterations (worst case) | Best for |
|---|---|---|---|
| Nested-loop search | Count up to min, test each divisor | O(min(a, b, c)) | The assignment, teaching, exam answers |
Chained gcd calls | GCD(GCD(a, b), c) with Euclid | O(log(max(a, b, c))) | Production code, interviews, large inputs |
A note on "nested loops" specifically. The assignment's wording ("using nested loops") could mean the outer loop and the three test conditions counted as an inner "loop" of checks. In practice, the common way to write this is one outer for loop and three if conditions, or a nested for that iterates over the three inputs. I show the simplest interpretation below — a single loop, with three divisibility checks. That's what most exam answer keys expect.
Complete C Program
Program: GCD of three numbers with nested loops
#include <stdio.h>
int main(void) {
int a, b, c;
printf("Enter three integers: ");
if (scanf("%d %d %d", &a, &b, &c) != 3) {
printf("Invalid input.\n");
return 1;
}
/* Normalise to non-negative values */
if (a < 0) a = -a;
if (b < 0) b = -b;
if (c < 0) c = -c;
/* Zero handling: GCD(0, 0, 0) is undefined; if any two are zero and
the third is not, the GCD is the third. For simplicity, require all
three to be positive for the main algorithm. */
if (a == 0 || b == 0 || c == 0) {
printf("Please enter three positive integers.\n");
return 0;
}
/* Find the smallest of the three — no common divisor can exceed it */
int smaller = a;
if (b < smaller) smaller = b;
if (c < smaller) smaller = c;
int last = 1; /* tracks the largest divisor that divides all three */
/* Outer loop over candidate divisors, inner set of checks */
for (int i = 1; i <= smaller; i++) {
if (a % i == 0 && b % i == 0 && c % i == 0) {
last = i;
}
}
printf("GCD of %d, %d and %d is %d\n", a, b, c, last);
return 0;
}
Here is the faster version using two chained gcd calls. It's the version you'd actually use in production code — and it also demonstrates the associativity identity that makes GCD such a well-behaved function:
Fast version: GCD(GCD(a, b), c)
#include <stdio.h>
int gcd(int x, int y) {
while (y != 0) {
int r = x % y;
x = y;
y = r;
}
return x;
}
int main(void) {
int a, b, c;
printf("Enter three integers: ");
scanf("%d %d %d", &a, &b, &c);
if (a < 0) a = -a;
if (b < 0) b = -b;
if (c < 0) c = -c;
int g = gcd(gcd(a, b), c);
printf("GCD = %d\n", g);
return 0;
}
For positive inputs, both versions produce the same answer. The nested-loop version is easier to explain on paper. The chained-gcd version is what a professional C programmer would write — and it generalises immediately to four, five, or a thousand numbers (just keep folding: g = gcd(g, next)).
Program Output
Enter three integers: 12 18 30
GCD of 12, 18 and 30 is 6
A few more to try by hand. Twelve, sixteen, and twenty should give 4. Eight, fifteen, and twenty-two should give 1 (they're collectively coprime). Nine, twenty-seven, and eighty-one should give 9. Nine, sixteen, and twenty-five should give 1. And a tricky one: 100, 75, 50 should give 25 — that's the largest number dividing all three, even though 100 and 50 share a larger factor (50), which is ignored because it doesn't also divide 75.
Step-by-Step Explanation
Let's follow the 12, 18, 30 case first, then look at what makes the three-input version trickier than the two-input one.
1. Input handling and normalisation
scanf("%d %d %d", &a, &b, &c) reads three integers at once. The check for != 3 catches inputs that were too short or malformed. The three if statements take absolute values. If any input is zero, the program reports an error — see point 6 below for why.
2. Finding the smallest
int smaller = a; if (b < smaller) smaller = b; if (c < smaller) smaller = c; is the clearest way to write min of three without using fminf or a macro. It runs in constant time — one comparison per input — and it's what makes the loop efficient. If we didn't compute this, we'd have to loop to max(a, b, c), which would test many values that can't possibly divide all three.
3. The main loop
For 12, 18, and 30, smaller = 12. The loop runs i = 1 through 12:
i = 1— 12, 18, 30 all divisible by 1 →last = 1i = 2— all divisible by 2 →last = 2i = 3— all divisible →last = 3i = 4— 18 % 4 = 2 → skipi = 5— 12 % 5 = 2 → skipi = 6— all divisible by 6 →last = 6i = 7 … 12— none divide all three → skip
Final last is 6 — the GCD.
4. Why last is initialised to 1
1 divides every integer, so it will always be found in the loop and overwritten. Initialising to 1 (rather than 0) is a safe choice because it's also the correct answer for any coprime triple — even if the loop somehow failed to update last, the initial value 1 would be the right answer. It's defensive programming, and it costs nothing.
5. Why the loop can stop at min(a, b, c)
Suppose d divides all three numbers. Then d ≤ a, d ≤ b, and d ≤ c, so d ≤ min(a, b, c). Testing beyond min(a, b, c) is guaranteed to fail — you're asking "does this large number divide the smallest of the inputs?" and the answer is always no (unless the large number equals the smallest, which is still within bounds). So the loop range is tight.
6. The zero case
The GCD is defined for pairs of integers, and for one zero with one non-zero it's the non-zero value: GCD(0, 12) = 12. For three inputs it gets more complicated: GCD(0, 0, 12) = 12, GCD(0, 12, 0) = 12, and GCD(0, 0, 0) is undefined (every positive integer divides 0). Rather than handle every combination explicitly, the program rejects any zero input with a friendly message — which is honest and easy to understand. In practice, if you needed to support zero values, you'd fall back to the chained-gcd version, which handles them naturally (the loop terminates immediately and returns the non-zero value).
7. The chained-gcd version — why it's better
The associativity identity GCD(a, b, c) = GCD(GCD(a, b), c) is what makes it possible. It's true because the prime factors of a, b, and c — with the minimum exponent taken across all three — can be computed in two steps: first take the minimum across a and b, then take the minimum of that with c. Each step is a GCD call. And each GCD call uses the Euclidean algorithm, which is O(log n).
In practice, this means gcd(gcd(999999, 999998), 999997) finishes in a few dozen iterations regardless of how large the inputs are. The nested-loop version would take about a million iterations. That's not a small improvement — it's the difference between "instant" and "noticeable pause" on a slow embedded processor.
🎯 Remember this: the nested-loop GCD test runs from 1 to min(a, b, c) and keeps the last value that divides all three. The faster alternative is to chain gcd calls: GCD(a, b, c) = GCD(GCD(a, b), c). Both give the same answer, but the chained version is roughly a million times faster for large inputs.
Frequently Asked Questions
1. What does "nested loops" mean in this context — do I really need two for loops?
Not necessarily. The phrase "nested loops" in the assignment title refers to the general approach of testing candidate divisors inside a loop — the loop over candidates plus the three divisibility checks form a nested structure of operations. Writing three if conditions inside one for loop is the standard interpretation and is what most exam answer keys expect. If your instructor specifically wants two nested for loops, you'd wrap the divisibility checks in an inner loop over an array of the three inputs — that also works and is slightly more general, but the answer is the same.
2. Why can't I just take the minimum of the three as the GCD?
Because the minimum only divides the other two if it happens to be a factor of them. For 12, 18, and 30, the minimum is 12, but 12 doesn't divide 18 or 30. The GCD is 6, which is smaller. The minimum is only the GCD in special cases (like a, 2a, 3a, where a is the minimum and also divides all three). In general, the GCD is at most the minimum — and often smaller.
3. Does the order of the three inputs matter?
No. GCD is commutative and associative — GCD(12, 18, 30) = GCD(18, 12, 30) = GCD(30, 12, 18), and so on. All six orderings give the same answer. This is useful to know because it means you can sort the inputs first (to put the smallest first) without changing the result — and putting the smallest first is exactly what you need for the loop's upper bound.
4. What if one or more inputs are zero?
The pair-wise GCD with zero is defined: GCD(0, n) = |n|. So GCD(0, 12, 18) = GCD(GCD(0, 12), 18) = GCD(12, 18) = 6. The chained-gcd version handles this naturally. The nested-loop version in this program rejects zero inputs because "divides evenly" against 0 is a degenerate case (every number divides 0). If your assignment requires handling zero, use the chained version.
5. Can I extend this to four, five, or more numbers?
Yes, and the chained-gcd version makes it easy: g = gcd(gcd(gcd(a, b), c), d). You can write it as a loop — for (int i = 1; i < n; i++) g = gcd(g, arr[i]); — which handles any number of inputs in about O(n log(max)) time. The nested-loop version becomes unwieldy for many inputs because you'd need one divisibility check per input, but for three or four inputs it's still manageable.
6. Where is GCD of three or more numbers used?
Three-way tiling problems (cutting three boards into equal-length pieces), aligning repeating events on three different schedules (a bus, a tram, and a train all arriving at the same station), simplifying ratios with three parts, and — in more advanced work — finding the largest common factor across all the coefficients of a polynomial. The pattern "GCD of many inputs" is the same: chain GCD calls.
💡 Tip: After you finish this program, try the chained-gcd version and print both results. Compare them to make sure they agree — that's a great way to verify the associativity identity in your own head. Then, when the LCM series reaches three-input LCM (a natural extension of assignment 2), you'll see the same pattern again: fold the operation across the inputs.