Function Assignment 7 โ€” Find the GCD (Greatest Common Divisor) of Two Numbers Using a Function
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

C Program: Find the GCD (Greatest Common Divisor) of Two Numbers Using a Function

๐Ÿ“‘ On this page:
  • What is the GCD?
  • Euclid's algorithm โ€” 2,300 years and still fast
  • Complete C Program
  • Program Output
  • Step-by-Step Explanation
  • Frequently Asked Questions
๐Ÿ“š In this program, you will learn:
  • What the GCD is and where it's used (fractions, cryptography, LCM)
  • How the Euclidean algorithm works โ€” the oldest efficient algorithm still in use
  • Why the algorithm is correct (the key math identity behind it)
  • How to handle negative inputs and the gcd(0, 0) edge case
  • How to write the same algorithm both iteratively and recursively

What is the GCD?

The greatest common divisor of two integers a and b is the largest positive integer that divides both of them without a remainder. For example, gcd(12, 18) = 6 because 6 is the largest number that divides both 12 and 18 evenly. Likewise, gcd(48, 36) = 12, gcd(17, 5) = 1 (17 and 5 are coprime), and gcd(100, 75) = 25.

The GCD shows up everywhere: simplifying fractions (divide numerator and denominator by their GCD), computing the LCM (which is (a ร— b) / gcd(a, b)), solving linear Diophantine equations, implementing RSA and other cryptographic algorithms, and even in music theory (harmonics, tuning). It's one of those fundamental operations that looks trivial until you need it โ€” and then you need it in a dozen different places.

The naive way to find the GCD is to loop from 1 to min(a, b) and remember the largest divisor. That works for small numbers, but it's O(min(a, b)) โ€” for large inputs like 1,000,000 and 999,999, you'd loop a million times. There's a much better way: the Euclidean algorithm, developed by Euclid around 300 BC. It runs in O(log(min(a, b))) time โ€” for the same million-sized inputs, it takes around twenty iterations. It's one of the oldest algorithms in continuous use, and it's still the standard.

The key insight behind it is this: gcd(a, b) = gcd(b, a % b). If you replace the pair (a, b) with (b, a mod b), the GCD stays the same. Repeat until b becomes 0; at that point, the GCD is a. That's the whole algorithm, and it's astonishingly effective. Understanding why the identity holds is the interesting part โ€” we'll walk through it in the explanation section.

๐Ÿ’ก In one line: write a function gcd(int a, int b) that loops with while (b != 0) { int r = a % b; a = b; b = r; }, then returns a. Take absolute values first so negative inputs don't break the loop.

Two numbers, a and b, and their GCD shown as the largest common factor โ€” for 48 and 36, it's 12.

Euclid's algorithm โ€” 2,300 years and still fast

Here's the whole thing, in pseudocode:

gcd(a, b):
    while b != 0:
        r = a mod b
        a = b
        b = r
    return a
                                

Each iteration replaces the pair with a smaller one, because a mod b is always strictly less than b. So the second number strictly decreases each iteration, and eventually reaches 0. At that point, the first number holds the GCD. That's the termination proof, and it's trivially obvious once you see it โ€” which is part of the algorithm's beauty.

Let's trace it for gcd(48, 36):

Iteration a b a mod b (r)
1483612
236120
3120โ€”

Two iterations, then b = 0, so we return a = 12. Correct โ€” and much faster than looping up to 36. For larger inputs, the gap grows dramatically. Try gcd(1, 000, 000, 999, 999) โ€” Euclidean gives 1 in one iteration, because 1000000 mod 999999 = 1, and then gcd(999999, 1) gives 1 in the next iteration. A brute-force loop would take a million steps.

The algorithm is sometimes called the "subtractive Euclidean algorithm" when written with subtraction (a = a - b) instead of modulo. The two are equivalent in principle โ€” a mod b is just a minus b repeated as many times as needed. The modulo version is much faster for inputs where a is much larger than b. Always use the modulo version.

๐ŸŽฏ Key identity: gcd(a, b) = gcd(b, a % b). Why? Because any common divisor of a and b also divides a % b (since a % b = a - kยทb for some integer k), and vice versa. The set of common divisors is unchanged, so the maximum is unchanged.

Complete C Program

Program: iterative Euclidean algorithm

#include <stdio.h>
#include <stdlib.h>   /* for abs() */

/* Function prototype */
int gcd(int a, int b);

int main(void) {
    int a, b;

    printf("Enter two integers: ");
    scanf("%d %d", &a, &b);

    printf("GCD of %d and %d is %d\n", a, b, gcd(a, b));

    return 0;
}

/* Iterative Euclidean algorithm */
int gcd(int a, int b) {
    a = abs(a);
    b = abs(b);

    while (b != 0) {
        int r = a % b;
        a = b;
        b = r;
    }
    return a;
}
                                    

And a recursive version โ€” shorter, and arguably closer to the mathematical definition:

Variant: recursive Euclidean algorithm

#include <stdio.h>
#include <stdlib.h>

int gcd(int a, int b) {
    a = abs(a);
    b = abs(b);

    if (b == 0) return a;
    return gcd(b, a % b);
}

int main(void) {
    int a, b;
    printf("Enter two integers: ");
    scanf("%d %d", &a, &b);
    printf("GCD of %d and %d is %d\n", a, b, gcd(a, b));
    return 0;
}
                                    

The recursive version reads almost exactly like the mathematical identity: "gcd(a, b) = gcd(b, a % b), unless b is 0, in which case it's a." Recursion depth is O(log(min(a, b))), which is small enough that stack overflow is practically impossible for 32-bit inputs (worst case: about 45 levels for gcd(Fibonacci(45), Fibonacci(44))). So the recursive version is safe here โ€” unlike Fibonacci, where the recursive version is exponential. This is a case where recursion genuinely is the clearer expression.

And a version that prints every step, which is a great way to see the algorithm work:

Variant: print each iteration

#include <stdio.h>
#include <stdlib.h>

int gcd_verbose(int a, int b) {
    a = abs(a);
    b = abs(b);

    while (b != 0) {
        int r = a % b;
        printf("  a = %d, b = %d, a mod b = %d\n", a, b, r);
        a = b;
        b = r;
    }
    return a;
}

int main(void) {
    int a, b;
    printf("Enter two integers: ");
    scanf("%d %d", &a, &b);
    printf("Computing gcd(%d, %d):\n", a, b);
    printf("GCD = %d\n", gcd_verbose(a, b));
    return 0;
}
                                    

Running this with 48 36 shows the sequence of reductions that leads to the answer. It's a small thing, but for a first encounter with the algorithm, it makes the process concrete. Once you've seen it a few times, the print statements become unnecessary noise โ€” but for learning, they're worth having.

Program Output

A typical run of the first program:

Enter two integers: 48 36
GCD of 48 and 36 is 12
                                

With one number being a multiple of the other:

Enter two integers: 100 25
GCD of 100 and 25 is 25
                                

With coprime numbers:

Enter two integers: 17 5
GCD of 17 and 5 is 1
                                

With negative numbers:

Enter two integers: -48 36
GCD of -48 and 36 is 12
                                

With zero:

Enter two integers: 0 5
GCD of 0 and 5 is 5
                                

And the verbose version with 48 36:

Enter two integers: 48 36
Computing gcd(48, 36):
  a = 48, b = 36, a mod b = 12
  a = 36, b = 12, a mod b = 0
GCD = 12
                                

Two iterations, and the answer is 12. Notice how quickly the numbers shrink โ€” from 48 and 36 down to 12 and 0 in one step, then done. That's the O(log) behavior in action. For Fibonacci-adjacent inputs (which are the worst case for Euclid), the number of iterations grows slowly โ€” gcd(F(n), F(n-1)) takes about n iterations, and F(n) is exponential in n. So even the worst case is logarithmic.

Step-by-Step Explanation

Let's look at the code and then dive into why the algorithm works.

1. The abs() lines

a = abs(a); b = abs(b); โ€” the GCD is defined to be positive, regardless of the signs of the inputs. Taking absolute values at the top of the function means the rest of the code doesn't need to worry about signs. Without this, a negative a could produce a negative result (since a % b in C preserves the sign of a), and a negative b could make the loop misbehave. The abs function is in <stdlib.h>; for long you'd use labs, and for float/double you'd use fabs from <math.h>.

2. The while loop

while (b != 0) โ€” we keep iterating as long as b is not zero. Each iteration computes r = a % b, then shifts the pair down: a = b, b = r. The new b (which is r) is strictly less than the old b, so the loop must terminate. When it does, b is 0, and the GCD is whatever a is now.

3. The final return

return a; โ€” at this point, b == 0, and a holds the GCD. The reason is the identity: gcd(a, 0) = a for any a. This is trivially true โ€” every number divides 0, so the largest common divisor of a and 0 is just a. So when the loop ends, returning a is correct.

4. Why the identity gcd(a, b) = gcd(b, a % b) holds

This is the heart of the algorithm, so it's worth explaining slowly. Suppose d is a common divisor of a and b. That means a = d ร— m and b = d ร— n for some integers m and n. Now, a % b = a - k ร— b for some integer k (the quotient of the integer division). Substituting: a - k ร— b = d ร— m - k ร— d ร— n = d ร— (m - k ร— n). So a % b is divisible by d. Therefore, any common divisor of a and b is also a divisor of a % b. This means the set of common divisors of (a, b) is a subset of the common divisors of (b, a % b). By symmetry (working the argument backwards), the sets are equal. So the greatest element is the same โ€” and gcd(a, b) = gcd(b, a % b). QED.

5. Tracing gcd(48, 36) through the code

  1. Start: a = 48, b = 36. Loop condition: b != 0 is true.
  2. Compute r = 48 % 36 = 12. Set a = 36, b = 12.
  3. Loop condition: b != 0 (12) is true.
  4. Compute r = 36 % 12 = 0. Set a = 12, b = 0.
  5. Loop condition: b != 0 is false. Exit loop.
  6. Return a = 12. โœ“

Two iterations. Compare with the brute-force approach: looping from 1 to 36 and checking divisors takes 36 iterations. For 1,000,000 and 999,999, the difference is roughly 1,000,000 to 2 โ€” a factor of 500,000. This is why Euclidean is the standard.

6. The gcd(0, 0) case

What happens if both inputs are 0? The function sets a = 0, b = 0, the loop condition is false immediately, and it returns 0. Is 0 a valid GCD? The GCD of two zeros is conventionally undefined (or 0 by some conventions), since every positive integer divides 0. Most programs don't call gcd(0, 0) โ€” if you're computing fractions, a zero denominator is already an error. If you want the function to behave sensibly, you could return an error or print a warning, but for most uses, returning 0 is fine. Document it, or validate inputs in main before calling.

7. Comparison with the recursive version

The recursive version reads almost exactly like the mathematical identity: if (b == 0) return a; return gcd(b, a % b);. Because recursion depth is bounded by O(log(min(a, b))) โ€” worst case around 45 for 32-bit inputs โ€” stack overflow is a non-issue, and the recursive version is arguably clearer. The iterative version avoids function call overhead but adds a while loop and a temporary variable. For this algorithm, most people prefer the recursive form for its directness โ€” it reads like a proof. For production code, either is fine; pick whichever your team finds clearer.

8. Why not the subtraction version?

The subtractive version of Euclid replaces a % b with repeated subtraction: while (a != b) { if (a > b) a -= b; else b -= a; }, returning a at the end. It works, but it can be O(max(a, b)) in the worst case โ€” for gcd(1000000, 1), it would subtract 1 from 1000000 a million times. The modulo version compresses that into one step (1000000 % 1 = 0). The subtractive version is historically interesting (it's closer to what Euclid actually described) but practically obsolete. Always use modulo.

9. Connection to LCM

Once you have gcd, computing the LCM is trivial: lcm(a, b) = (a ร— b) / gcd(a, b). That's exactly what assignment 8 will do. For this program, knowing that the GCD is the building block for the LCM shows why it's worth implementing carefully โ€” it's not just a standalone curiosity, it's the primitive that many other algorithms rely on.

๐Ÿ” Try this: run the verbose version with gcd(Fibonacci(20), Fibonacci(19)) = gcd(6765, 4181). Count the iterations โ€” you'll see that the worst case for Euclid is when the inputs are consecutive Fibonacci numbers, and even then the number of iterations is proportional to the index, not the value. That's the logarithmic behavior in its most striking form.

Frequently Asked Questions

1. What's the difference between GCD and HCF?

Nothing โ€” they're the same concept with different names. GCD (Greatest Common Divisor) and HCF (Highest Common Factor) both refer to the largest positive integer that divides two or more numbers. Some textbooks use GCD, others use HCF; they're interchangeable. In computer science, GCD is more common.

2. Is the recursive version safe for large inputs?

Yes. The recursion depth of the Euclidean algorithm is O(log(min(a, b))). For 32-bit int values (max about 2.1 billion), the worst case is around 45 recursive calls โ€” well within the default stack size (typically 8 MB or more). Unlike Fibonacci or naive tree traversal, the recursion here is bounded and shallow. Both versions work; choose based on readability preferences, not safety.

3. Why do we take abs() at the start?

The GCD is defined to be positive. The algorithm works correctly with positive inputs, but with negative inputs, the % operator in C preserves the sign of the dividend โ€” -48 % 36 = -12, not 12. This would break the invariant and produce a negative result. Taking abs() at the start normalizes the inputs and lets the algorithm work as designed. It's a one-line fix that prevents a whole category of subtle bugs.

4. What's gcd(0, 0)?

Mathematically undefined. Every positive integer divides 0, so there's no largest common divisor. Conventionally, some texts say gcd(0, 0) = 0, and our function returns 0 for this case (the loop doesn't run, returns the initial a). If you need to handle gcd(0, 0) as an error, add an explicit check in main: if (a == 0 && b == 0) { printf("GCD of two zeros is undefined\n"); return 1; }. For most uses, the function's default behavior is fine.

5. Can the GCD function handle more than two numbers?

Yes, by nesting: gcd(a, b, c) = gcd(gcd(a, b), c). The GCD is associative, so you can fold the function over an array: start with result = arr[0], then for each subsequent element, result = gcd(result, arr[i]). This works because gcd(gcd(a, b), c) = gcd(a, gcd(b, c)). You'll see this pattern in problems that ask for the GCD of an array.

6. Why is the Euclidean algorithm so fast?

The key is that a % b < b always โ€” the second argument strictly decreases. And it usually decreases a lot: if a and b are random, a % b is on average about b/2, so the numbers halve each iteration. That gives O(log(max(a, b))) iterations. The worst case is consecutive Fibonacci numbers, where the reduction is slowest โ€” but even then, it's O(log) because F(n) โ‰ˆ ฯ†โฟ. This is one of the earliest examples of algorithmic analysis โ€” Euclid himself wrote about it.

๐Ÿ’ก Tip: Once this works, try implementing the "extended Euclidean algorithm" โ€” it returns not just the GCD but also the coefficients x and y such that aยทx + bยทy = gcd(a, b). That's the Bรฉzout identity, and it's the basis for modular inverses, which power RSA cryptography. It's the same algorithm with a bit more bookkeeping, and it's a natural next step.

๐Ÿ“– Related Tutorials

  • Introduction to Functions in C
  • Recursion in C
  • Function Definition
  • Function Declaration
  • Types of Functions
  • Next: LCM of Two Numbers Using a Function
  • All 33 Function Assignments

Previous Topic: -->> 6. Convert Temperature from Celsius to Fahrenheit Using a Function   ||   Next Topic: -->> 8. Find the LCM (Least Common Multiple) of Two Numbers Using a Function


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.