Loop Assignment 5 — GCD of Three Numbers Using Nested Loops
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

C Program: Find the GCD of Three Numbers Using Nested Loops

📑 On this page:
  • Extending GCD to Three Numbers
  • Two Ways to Compute GCD(a, b, c)
  • Complete C Program
  • Program Output
  • Step-by-Step Explanation
  • Frequently Asked Questions
📚 In this program, you will learn:
  • 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 gcd calls
  • 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.

Diagram showing three numbers 12, 18, and 30 with their shared divisors 1, 2, 3, 6 highlighted — the largest being 6

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 searchCount up to min, test each divisorO(min(a, b, c))The assignment, teaching, exam answers
Chained gcd callsGCD(GCD(a, b), c) with EuclidO(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:

  1. i = 1 — 12, 18, 30 all divisible by 1 → last = 1
  2. i = 2 — all divisible by 2 → last = 2
  3. i = 3 — all divisible → last = 3
  4. i = 4 — 18 % 4 = 2 → skip
  5. i = 5 — 12 % 5 = 2 → skip
  6. i = 6 — all divisible by 6 → last = 6
  7. i = 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.

📖 Related Tutorials

  • 1. Find the GCD of Two Numbers Using a While Loop
  • 2. Find the LCM of Two Numbers Using a For Loop
  • 3. Check Whether Two Numbers Are Coprime Using a While Loop
  • 4. Find All Common Divisors of Two Numbers Using a For Loop
  • 30. Check Whether Two Integers Are Amicable Using a For Loop
  • Nested for loop
  • Nested While Loop
  • All 30 Loop Assignments

Previous Topic: -->> 4. Find All Common Divisors of Two Numbers Using a For Loop   ||   Next Topic: -->> 6. Count the Digits in an Integer Using a While Loop


C Language

  • Home
  • Why C Language
  • History of C Language
  • Applications of C Language
  • Introduction To C
    • What is Program?
    • Structure of C Program
    • Working Of C Program
    • CHARACTER SET
    • VARIABLES AND IDENTIFIERS
    • BUILT-IN DATA TYPES
    • OPERATORS AND EXPRESSIONS
    • CONSTANTS AND LITERALS
    • SIMPLE ASSIGNMENT STATEMENT
    • BASIC INPUT/OUTPUT STATEMENT
    • SIMPLE 'C' PROGRAMS
    • Assignments
  • Operators in C Programming
    • Arithmetic Operators
    • Assignment Operators
    • Increment and Decrement Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Other Operators
    • Assignments
  • CONDITIONAL STATEMENTS
    • DECISION MAKING WITHIN A PROGRAM
    • CONDITIONS
    • IF STATEMENT
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • SWITCH CASE
    • Assignments
  • LOOPS STATEMENTS
    • Introduction to Loops
    • GO TO Statement
    • Do while Loop
    • While Loop
    • Nested While Loop
    • Difference Between While and Do while
    • Difference Between Goto and loop
    • while loop assignments
    • C FOR Loop
    • C For loop examples
    • Nested for loop
    • Nested for loop examples
    • Infinite while Loops
    • Infinite for Loops
    • Continue in Loops
    • break in Loops
    • difference while do..while & for
    • Assignments
  • Arrays
    • One Dimensional Array
    • Declaring 1D Arrays
    • Initilization of 1D arrays
    • Accessing element of one 1D Array
    • Read and Display 1D Arrays
    • Two Dimensional Arrays
    • Declare 2D Arrays
    • Read and Display 2D Arrays
    • Assignments/Examples
  • Functions
    • Introduction
    • Need For User-Defined Function
    • Multiple Function Program
    • Modular Programming
    • Elements Of User Defined Function
    • Function Definition
    • Function Declaration
    • Types of functions
    • Nesting of Function
    • Recursion
    • Passing Array To Functions
    • Scope,Visibility and Lifetime of Variables
    • Assignments
  • Structure
    • Introduction
    • Array vs Structure
    • Defining Structure
    • Declaring Structure Variables
    • Type Defined Structure
    • Accessing Structure Members
    • Structure Initilization
    • Copying & Comparing Structure Variables
    • Array of Structure
    • Arrays Within Structure
    • Structures Within Structures
    • Structures and Functions
    • Structure Examples/Assignments
  • Union
    • Define Union
    • Create and use Union
    • Difference Between Structure and Union
    • Union Examples
    • Union FAQ
  • Pointers
    • What Are Pointers In C?
    • How Do We Use Pointers In C?
    • Declaration Of A Pointer
    • The Initialization Of A Pointer
    • Syntax Of Pointer Initialization
    • Use Of Pointers In C
    • The Pointer To An Array
    • The Pointer To A Function
    • The Pointer To A Structure
    • Types Of Pointers
    • The Null Pointer
    • The Void Pointer
    • The Wild Pointer
    • The Near Pointer
    • The Huge Pointer
    • The far Pointer
    • dangling pointer
    • Accessing Pointers- Indirectly And Directly
    • Pros Of Using Pointers In C
    • Cons Of Pointers In C
    • Applications Of Pointers In C
    • The & Address Of Operator In C
    • How To Read The Complex Pointers In C?
    • Practice Problems On Pointers
  • File Processiong
    • File Handling In C
    • Types Of Files In C
    • Operations Done In File Handling
    • File Examples
    • Binary Files
    • count words,lines in a file
    • Copy files
    • Update File
    • count vowels in a file
  • Preprocessor
    • Macro substitution division
    • File Inclusion
    • Conditional Compilation
    • Other directives
    • Examples
  • Dynamic Memory Allocation
    • malloc
    • calloc
    • free
    • realloc
    • Examples
  • Storage Classes
  • Graphics
  • Frequently Asked Interview Questions (FAQ)
    • Introduction To C FAQ
    • Operators FAQ
    • Conditional Statements FAQ
    • Loops FAQ
    • Arrays FAQ
    • Function FAQ
    • Structure FAQ
    • Pointers FAQ
    • Files FAQ
    • Storage classes FAQ
    • Dynamic Memory FAQ
  • Programs/Assignments
    • Introduction To C
    • Operators
    • Conditional Statements
    • Loops
    • Arrays
    • Function
    • Structure
    • Pointers
    • Files
    • Storage classes
    • Dynamic Memory
  • Case Studies
  • Multiple Choice Questions
    • Introduction To C MCQ
    • Operators MCQ
    • Conditional Statements MCQ
    • Loops MCQ
    • Arrays MCQ
    • Function MCQ
    • Structure MCQ
    • Pointers MCQ
    • Files MCQ
    • Storage classes MCQ
    • Dynamic Memory MCQ
    • More MCQ

Get in touch

  • tech2dsm@gmail.com

© Sankalan Data Tech. All rights reserved.