Loop Assignment 4 — Find All Common Divisors Using For Loop
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

C Program: Find All Common Divisors of Two Numbers Using a For Loop

📑 On this page:
  • What a "Common Divisor" Is
  • Why the Loop Stops at the Smaller Number
  • Complete C Program
  • Program Output
  • Step-by-Step Explanation
  • Frequently Asked Questions
📚 In this program, you will learn:
  • What a common divisor is — and how the set of common divisors relates to the GCD
  • Why you only need to test values from 1 up to the smaller input
  • How to write the divisibility test with % and print results inside the loop
  • How to handle the awkward zero cases without producing nonsense
  • Why the last printed value is always the GCD — a useful cross-check

What a "Common Divisor" Is

A common divisor of two numbers is any positive integer that divides both of them with no remainder. For 12 and 18, the common divisors are 1, 2, 3, and 6. For 8 and 15, the only common divisor is 1. For 100 and 75, the common divisors are 1, 5, and 25.

You already met the largest of these — that's the GCD. This program asks for the full list, smallest to largest. The key insight, and one worth remembering, is that the GCD is always the last common divisor when you list them in order. Which means if you already wrote the GCD program from assignment 1, you can think of this one as the same test repeated many times, printing every value that passes.

The practical use is small but real. Whenever you need to simplify a fraction (divide both parts by the GCD — which is the largest common divisor), or when you're working out which tile sizes fit a rectangular floor exactly, the list of common divisors tells you all the valid options, not just the biggest one.

💡 In one line: every value i from 1 up to the smaller input is a common divisor if it divides both — and the largest such value is the GCD.

Diagram showing divisors of 12 (1, 2, 3, 4, 6, 12) and divisors of 18 (1, 2, 3, 6, 9, 18), with the intersection 1, 2, 3, 6 highlighted

Why the Loop Stops at the Smaller Number

If d is a common divisor of a and b, then d divides a, which means d cannot be bigger than a. It also divides b, so it can't be bigger than b either. So it can't be bigger than either of them — which means it can't be bigger than the smaller one. That's why the loop only needs to run from 1 to min(a, b). Testing past that is wasted work.

For 12 and 18, min(12, 18) = 12, so we test 1, 2, 3, …, 12. Each test is a single % operation for each input, so 24 modulo operations in total. On modern hardware that's a few nanoseconds — nothing. Only when the inputs get huge (millions) does the cost of this approach become noticeable, and even then a proper divisor-listing algorithm is a bigger change than just a faster loop.

The output order matters too. Listing smallest-first is the natural way to present it, and it makes the final printed value the GCD — which is a nice built-in sanity check. If the last printed number doesn't divide both inputs, something is wrong.

Pair Common divisors Count GCD (last value)
12, 181, 2, 3, 646
8, 15111
100, 751, 5, 25325
9, 271, 3, 939
24, 361, 2, 3, 4, 6, 12612
17, 341, 17217

Complete C Program

Program: list all common divisors of two numbers with a for loop

#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;
    }

    /* Normalise to non-negative values */
    if (a < 0) a = -a;
    if (b < 0) b = -b;

    /* Zero edge cases */
    if (a == 0 && b == 0) {
        printf("Every positive integer divides 0 and 0, so the list is infinite.\n");
        return 0;
    }
    if (a == 0) { int t = a; a = b; b = t; }  /* then only b is zero */
    if (b == 0) {
        printf("Every divisor of %d is a common divisor.\n", a);
        printf("Common divisors: ");
        for (int i = 1; i <= a; i++) {
            if (a % i == 0) printf("%d ", i);
        }
        printf("\n");
        return 0;
    }

    /* Normal case: no common divisor can exceed the smaller input */
    int smaller = (a < b) ? a : b;
    int last    = 0;  /* tracks the largest common divisor, i.e. the GCD */

    printf("Common divisors of %d and %d: ", a, b);
    for (int i = 1; i <= smaller; i++) {
        if (a % i == 0 && b % i == 0) {
            printf("%d ", i);
            last = i;
        }
    }
    printf("\nGCD = %d\n", last);

    return 0;
}
                                    

And here is a more compact version if you're aiming for the shortest correct program rather than the most readable one. It skips the zero handling and the GCD tracking, so it's only suitable when you know both inputs are positive:

Compact version (positive inputs only)

#include <stdio.h>

int main(void) {
    int a, b;
    printf("Enter two positive integers: ");
    scanf("%d %d", &a, &b);

    int smaller = (a < b) ? a : b;
    printf("Common divisors: ");
    for (int i = 1; i <= smaller; i++)
        if (a % i == 0 && b % i == 0)
            printf("%d ", i);
    printf("\n");
    return 0;
}
                                    

Both versions produce the same list for positive inputs. The first one earns its extra lines by handling zero correctly and by reporting the GCD as a by-product of the loop — two small conveniences that make it more useful as a standalone program.

Program Output

Enter two integers: 12 18
Common divisors of 12 and 18: 1 2 3 6
GCD = 6
                                

Try 8 and 15 — you should see just "1" and GCD = 1, confirming they're coprime. Try 100 and 75 — the list is "1 5 25" with GCD = 25. Try 24 and 36 — six values (1, 2, 3, 4, 6, 12) with GCD = 12. Then try 0 and 12 — the program switches to the "every divisor of 12 is a common divisor" branch and prints 1 2 3 4 6 12.

Step-by-Step Explanation

Let's walk through 12 and 18 first, then unpack the tricky bits.

1. Input handling and normalisation

As in the previous programs in this series, the two if lines convert negatives to positives. The divisor list of −12 and 18 is the same as that of 12 and 18 — but computing modulo with negative operands can produce results that are hard to reason about, and there's no benefit. Taking absolute values first is a habit worth keeping.

2. The three zero cases

Zero needs its own logic, because "divide by zero" isn't the issue here — it's "how many divisors does zero have." Every positive integer divides zero. So:

  1. 0 and 0: every positive integer is a common divisor — the list is infinite. Print a message and stop.
  2. 0 and n (for n > 0): the common divisors are just the divisors of n, because every integer divides 0. The program swaps to make b == 0 in this case, then lists divisors of a.
  3. n and 0: same as above, just with the roles reversed.

Without these branches, the main loop would run from 1 to 0 (never execute, because 0 < 1) and print nothing — which is confusing. Handling them explicitly is honest and clear.

3. The main loop

For 12 and 18, smaller = 12. The loop runs i = 1 through 12 and tests each one:

  1. i = 1 — 12 % 1 = 0, 18 % 1 = 0 → print 1, last = 1
  2. i = 2 — 12 % 2 = 0, 18 % 2 = 0 → print 2, last = 2
  3. i = 3 — 12 % 3 = 0, 18 % 3 = 0 → print 3, last = 3
  4. i = 4 — 12 % 4 = 0, 18 % 4 = 2 → skip
  5. i = 5 — 12 % 5 = 2, 18 % 5 = 3 → skip
  6. i = 6 — 12 % 6 = 0, 18 % 6 = 0 → print 6, last = 6
  7. …
  8. i = 12 — 12 % 12 = 0, 18 % 12 = 6 → skip

Final output: 1 2 3 6, and last holds 6 — the GCD.

4. Why the loop stops at the smaller number

Suppose d divides both a and b. Then d ≤ a and d ≤ b, so d ≤ min(a, b). Anything bigger than the smaller input can't divide it, so it can't be a common divisor. Testing beyond min(a, b) would be pure waste — every test would fail.

For 12 and 18, testing up to 12 is one-third of the way to 18; for 100 and 1000000, it would be one ten-thousandth. The saving is significant when the inputs are very different sizes.

5. The last variable

As the loop runs, last is overwritten every time a common divisor is found. By the end of the loop, last holds the most recent — which, because i is increasing, is also the largest. That value is the GCD by definition. So the program reports it without computing it separately, which is a small efficiency and a nice demonstration that "GCD = largest common divisor" isn't just an abstract definition — the program's own loop shows it directly.

6. Printing order and format

Each divisor is followed by a single space. There's a subtle cosmetic issue: the last value also gets a trailing space before the newline. Most terminals hide it, but if you're piping output into a script, it can matter. The alternative — printing a space before every divisor except the first — avoids this but complicates the loop. For a teaching program, the trailing space is harmless; for a shell script, use the "if not first, print space" pattern.

7. Time complexity

The loop runs min(a, b) times. That's linear in the smaller input. For small values (up to a few thousand) it's fine. For very large values (millions or more), it becomes slow, and in that case you'd rather find the divisors of the GCD directly, which is faster because the GCD itself is usually much smaller than either input. The next section in this series (GCD of three numbers) touches on the same theme.

🎯 Remember this: a common divisor can't be larger than the smaller of the two inputs, so the loop only runs to min(a, b). Every value that divides both is a common divisor — and the largest such value is the GCD. Report the whole list, and put the GCD at the end so readers can spot it at a glance.

Frequently Asked Questions

1. Why doesn't the loop go all the way to max(a, b) or beyond?

Because nothing bigger than the smaller input can divide it. If a = 12 and b = 18, any common divisor must divide 12 — so it must be ≤ 12. Testing 13 through 18 would just fail every time, because none of them can divide 12. The rule generalises: for any pair, the upper bound is min(a, b), not max(a, b) and certainly not a * b.

2. Is 1 always a common divisor?

Yes, for every pair of positive integers — 1 divides everything. So the list is never empty, and every pair of positive integers has at least one common divisor. The special case of "coprime" is simply "the only common divisor is 1" — no shortage, just no surplus.

3. What about negative inputs?

The program takes absolute values at the start, so −12 and 18 produce the same list as 12 and 18: 1, 2, 3, 6. Divisibility is normally defined on positive integers, and the set of divisors of −12 is the same as the set of divisors of 12 (both are {1, 2, 3, 4, 6, 12} if we restrict to positive divisors). Normalising to positive values avoids any confusion about whether "−2" should appear in the list.

4. Why does the program print "Every divisor of n is a common divisor" when one input is zero?

Because every integer divides 0. So if a = 0 and b = 12, any integer that divides 12 also divides 0, and is therefore a common divisor. The list is exactly the divisors of 12: 1, 2, 3, 4, 6, 12. The program handles this case explicitly because the main loop's bounds (1 to min(0, 12) = 0) would produce no output, which is misleading. Zero and zero is a special case of this — every positive integer divides both, so the list is infinite.

5. How does this relate to the GCD program?

The GCD is the largest common divisor — that's the definition. So the last value printed by this program is the GCD. If you already have the GCD program from assignment 1, this one is the same set of common divisors, in full. In fact you can use this program to double-check the GCD: if the value reported as "GCD" doesn't match assignment 1's output, something is wrong in one of them.

6. Can I make it faster for very large inputs?

Yes, two ways. First, find the GCD by Euclid's algorithm (much faster than looping up to min(a, b)), then list the divisors of the GCD. Since the GCD is usually much smaller than either input, this reduces the loop length dramatically. Second, use a divisor-pair trick: loop only up to √n and add both i and n/i each time — that's O(√n) instead of O(n). For a teaching program, the simple loop is clearer; for production code, the divisor-pair trick is worth knowing.

💡 Tip: Print the GCD as the last item on the list, and add a blank line between the list and the summary. It's a small cosmetic touch that makes the output much easier to read, and it also makes the "GCD is the last common divisor" relationship obvious. Then, when you tackle the LCM assignment next, you'll see how the GCD from this program feeds straight into the LCM formula.

📖 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
  • 5. GCD of Three Numbers Using Nested Loops
  • 30. Check Whether Two Integers Are Amicable Using a For Loop
  • C FOR Loop
  • Nested for loop
  • All 30 Loop Assignments

Previous Topic: -->> 3. Check Whether Two Numbers Are Coprime Using a While Loop   ||   Next Topic: -->> 5. GCD of Three Numbers Using Nested Loops


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.