Find GCD in C

Beginner
⏱️ 10 min read
📚 Updated: Aug 2026
🎯 2 Code Examples
🚀 Live Preview
Euclid

What You’ll Learn

GCD is a classic interview warm-up: remainders, loops, and the Euclidean algorithm. This tutorial covers the definition of gcd(a, b), iterative and recursive C programs, a live preview, algorithm steps, worked C examples, edge cases, and complexity.

Definition

Largest divisor

Largest positive d that divides both a and b (when not both zero).

Euclid Rule

a mod b

gcd(a, b) = gcd(b, a % b) until the remainder is zero.

Iterative

O(1) space

A compact while loop is the interview default.

Recursive

Base b = 0

Same math as a one-line recursive call on (b, a % b).

Live Preview

Two inputs

Compute gcd of two integers instantly in the browser.

LCM Link

|ab|/gcd

Least common multiple follows once you have the gcd.

Introduction

GCD (greatest common divisor) of two integers that are not both zero is the largest positive integer that divides both. Euclid’s rule gcd(a, b) = gcd(b, a mod b) shrinks the pair until the remainder hits zero — the surviving value is the answer.

In C interviews you are usually asked to implement the Euclidean algorithm iteratively or recursively, discuss gcd(0, n), and note remainder-sign quirks with negatives.

Why it matters?

GCD underpins fraction reduction, LCM, modular inverses, and linear Diophantine equations — a small function with wide reach in number theory and crypto warm-ups.

Key Highlights

Last Nonzero Remainder

Stop when b = 0; return a.

gcd(0, n) = |n|

Every divisor of n divides zero.

Two Patterns

Iterative loop or recursive remainder chain.

Normalize Signs

Prefer nonnegative magnitudes before %.

In short: replace (a, b) with (b, a % b) until b is zero — the remaining a is gcd(a, b).

📝 Problem & Approach

Given two integers a and b, compute their greatest common divisor using the Euclidean algorithm.

c
/* Remainder chain for gcd(48, 18)
 * gcd(48, 18) = gcd(18, 12)
 *             = gcd(12,  6)
 *             = gcd( 6,  0)
 *             = 6
 */

Inputs & Outputs

ItemTypeDescription
a, bintTwo integers whose gcd to compute (interview demos often nonnegative).
Returned / printed gcdintLargest positive common divisor (or 0 for the (0, 0) convention).

Minimal workflow

Pseudocode
function gcd(a, b):  // assume nonnegative; define gcd(0,0) as needed
    while b != 0:
        (a, b) = (b, a mod b)
    return a

Method comparison

MethodIdeaExtra space
Iterative EuclidLoop while b != 0, swap with remainderO(1)
Recursive EuclidReturn gcd(b, a % b) with base b == 0O(log min(a,b)) stack

⚡ Quick Reference

GoalPattern
Euclid step(a, b) = (b, a % b)
Base caseif (b == 0) return a;
Iterative bodytemp = b; b = a % b; a = temp;
Zero partnergcd(0, n) = |n| for n ≠ 0
LCM from GCDlcm = |a / gcd * b| (order carefully to reduce overflow)

📋 Iterative vs Recursive vs Binary GCD

All compute gcd — pick based on clarity and constraints.

Iterative Euclid
while b != 0

Interview default — O(1) extra space

Recursive Euclid
gcd(b, a%b)

Matches the math line-for-line; uses call stack

Stein (binary)
shifts

Useful for big integers; overkill for plain int

Interview tip
mention LCM

Know gcd(0,n), signs, and lcm = |ab|/gcd

Context

When This Problem Shows Up

Reach for GCD when divisibility and modular math matter.

  1. Interview warm-ups

    Quick check of loops, remainders, and edge cases like zero.

  2. Fraction reduction

    Divide numerator and denominator by gcd to lowest terms.

  3. Modular inverses

    Inverse exists iff gcd(a, m) = 1; extended Euclid finds it.

  4. LCM & scheduling

    Combine periods or array sizes via lcm = |ab|/gcd.

  5. Not a substitute for factoring

    GCD finds the shared divisor; listing all common divisors is a different prompt.

Key benefit: a tiny algorithm that unlocks fractions, LCM, inverses, and Diophantine checks.

🔮 Live Preview

Enter two integers and compute gcd using the same Euclidean recurrence as the C samples.

Try (0, 21), (17, 13), or (48, 18). Magnitudes are used if you enter negatives.

Live result
Press “Compute gcd”.

Examples Gallery

Two complete C programs — iterative and recursive Euclidean — both for 48 and 18. Click View Output to reveal sample console results.

📚 Getting Started

Classic iterative Euclid for nonnegative interview inputs.

Example 1 — Iterative Euclidean Algorithm

Loop while the remainder is nonzero; when b becomes 0, a holds the gcd.

c
#include <stdio.h>

int find_gcd(int num1, int num2) {
    while (num2 != 0) {
        int temp = num2;
        num2 = num1 % num2;
        num1 = temp;
    }
    return num1;
}

int main(void) {
    int number1 = 48;
    int number2 = 18;
    int g;

    g = find_gcd(number1, number2);
    printf("GCD of %d and %d is: %d\n", number1, number2, g);

    return 0;
}

How It Works

Each iteration stores the old b in num1 and replaces b by a % b. When b becomes 0, num1 holds the gcd.

📈 Practical Patterns

Same result with a recursive remainder chain.

Example 2 — Recursive Euclidean Algorithm

Base case gcd(a, 0) = a; otherwise recurse on (b, a % b).

c
#include <stdio.h>

int gcd_recursive(int a, int b) {
    if (b == 0) {
        return a;
    }
    return gcd_recursive(b, a % b);
}

int main(void) {
    int number1 = 48;
    int number2 = 18;

    printf("GCD of %d and %d is: %d\n", number1, number2,
           gcd_recursive(number1, number2));

    return 0;
}

How It Works

The call stack mirrors the manual remainder sequence. Depth is O(log min(|a|, |b|)) in typical cases — fine for interview-sized integers.

🧠 How the Algorithm Finds GCD

1

Normalize (optional)

Take absolute values if you want a nonnegative gcd; define (0, 0) separately if needed.

Guard
2

Reduce with %

While b ≠ 0, set (a, b) ← (b, a % b).

Euclid
3

Stop at zero

When b == 0, the remaining a is the gcd.

Base
=

Answer ready

For (48, 18) the result is 6.

🔎 Worked Walkthrough — gcd(48, 18)

Trace the Euclidean remainder chain until the remainder is zero.

StepPair (a, b)a % bNext pair
1(48, 18)12(18, 12)
2(18, 12)6(12, 6)
3(12, 6)0(6, 0)
4(6, 0)return 6

So gcd(48, 18) = 6. Reducing 18/48 by dividing by 6 yields 3/8.

Use Cases

Where gcd shows up beyond the interview prompt.

1. Fraction Reduction

Divide numerator and denominator by their gcd.

Example: 18/48 → 3/8.

2. LCM

Compute least common multiple via |ab|/gcd.

Example: schedule alignment, array tiling.

3. Modular Inverse

Exists when gcd(a, m) = 1; extended Euclid finds it.

Example: modular arithmetic, crypto warm-ups.

4. Diophantine Equations

ax + by = c is solvable iff gcd(a, b) | c.

Example: coin problems, linear constraints.

5. Coprimality Checks

RSA and CRT setups need gcd = 1 in places.

Example: choose e coprime to φ(n).

6. Common Divisors

All common divisors divide the gcd — the max is gcd itself.

Example: list divisors of gcd(a, b).

Pro Tip: if the interviewer asks for LCM, compute gcd first and form |a / gcd * b| carefully to reduce overflow risk.

Advantages

Why Euclid’s algorithm earns interview points.

  1. 1. Tiny and Fast

    A few lines of code with logarithmic steps for fixed-width ints.

  2. 2. Matches the Math

    Easy to prove and explain: common divisors survive the remainder step.

  3. 3. Beats Trial Division

    No need to scan all divisors up to min(a, b).

  4. 4. Extends Cleanly

    Extended Euclid and LCM build directly on the same loop.

Pro Tip: lead with iterative Euclid; offer the recursive form as the mathematical twin if asked.

Usage Tips

Small habits that keep GCD code clean in interviews.

  1. 1. Prefer Nonnegative Inputs

    Take absolute values before the loop so remainder signs stay simple.

  2. 2. Document gcd(0, 0)

    State your convention (often return 0) in library-style code.

  3. 3. Use Iteration by Default

    Same math as recursion with O(1) auxiliary space.

  4. 4. Form LCM Carefully

    Compute a / gcd * b (not a * b / gcd first) when overflow is a risk.

  5. 5. Test Coprime and Zero Cases

    Verify (17, 13), (0, 21), and (48, 18) before claiming done.

Pro Tip: dry-run gcd(48, 18) on paper (table above) before coding — it locks in the remainder chain.

Common Pitfalls

Mistakes that commonly break GCD solutions in C.

  1. 1. Ignoring Negative Remainders

    C’s % follows toward-zero division; signs can surprise you.

    → Normalize to nonnegative magnitudes first.

  2. 2. Undefined gcd(0, 0)

    The loop returns 0, but some specs leave it undefined.

    → Document your convention in comments or docs.

  3. 3. abs(INT_MIN) Hazard

    Absolute value of INT_MIN is undefined for int in C.

    → Use wider types or unsigned magnitude tricks when normalizing.

  4. 4. Trial Division Instead of Euclid

    Scanning all candidates up to min(a,b) is slower and noisier.

    → Prefer the remainder loop unless the prompt demands otherwise.

  5. 5. Overflow When Forming LCM

    a * b may overflow before dividing by gcd.

    → Compute a / gcd * b with care (and wider types if needed).

Edge Cases

Check these inputs before calling the solution done.

Zero

gcd(0, n)

For n > 0, result is n (or |n| after normalizing).

Zero pair

gcd(0, 0)

Loop returns 0; some definitions leave this undefined.

Coprime

gcd = 1

E.g. (17, 13) — still a valid, important outcome.

Sign

Negative inputs

Mathematical gcd is nonnegative — normalize before %.

INT_MIN

abs hazard

abs(INT_MIN) is undefined for int; use wider types carefully.

Order

gcd(a,b)=gcd(b,a)

Either argument order is fine after the first Euclid step.

🔄 Sample Values

Known results for common interview pairs.

(a, b)gcd
(48, 18)6
(17, 13)1
(0, 21)21
(12, 18)6

🎯 Practice Problems

Try these variations to lock in the pattern.

1. Read two ints from stdin

  • Use scanf and print the gcd
  • Normalize negatives before Euclid

2. Compute LCM

  • Reuse find_gcd, then form LCM safely
  • Test with (48, 18) → LCM 144

3. GCD of an array

  • Fold gcd across all elements
  • Handle empty / all-zero carefully

4. Extended Euclid sketch

  • Track coefficients for Bézout identity
  • Useful modular-inverse follow-up

Notes

  • Worst case. Fibonacci-adjacent pairs maximize Euclid steps (Lamé’s theorem).
  • gcd(0, n) = |n| for nonzero n; decide what gcd(0, 0) should return.
  • For plain int, iterative Euclid is already optimal in practice; Stein helps more with big integers.
  • Extended Euclid finds Bézout coefficients while computing the same remainder chain.

Quick Takeaway: gcd(a, b) = gcd(b, a % b) until b = 0 — iterative Euclid is fast, tiny, and interview-ready.

⏱️ Time and Space Complexity

VersionTimeExtra space
Iterative EuclidO(log min(a, b)) steps (worst Fibonacci pair)O(1)
Recursive EuclidsameO(log min(a, b)) stack frames

Lamé’s theorem bounds the number of division steps for inputs with a fixed number of digits.

Wrap Up

🎉 Conclusion

GCD via Euclid is a small remainder-loop exercise with big payoff: fractions, LCM, modular inverses, and Diophantine checks all build on it. Master both the iterative and recursive forms so you can explain either in an interview.

Practice the two examples above, then continue to happy numbers for another classic digit-iteration warm-up.

Replace (a, b) with (b, a % b) until b = 0, normalize signs, and remember gcd(0, n) = |n|.

💡 Best Practices

✅ Do

  • Explain gcd(a,b)=gcd(b,a%b) before coding
  • Prefer iterative Euclid for O(1) space
  • Normalize negatives; document gcd(0,0)
  • Test coprime, zero-partner, and classic pairs
  • Mention LCM and extended Euclid as follow-ups

❌ Don’t

  • Scan all divisors when Euclid works
  • Ignore C remainder signs on negatives
  • Call abs(INT_MIN) carelessly
  • Form LCM as raw a * b / gcd without overflow care
  • Skip the (0, n) edge case

Key Takeaways

Knowledge Unlocked

Five things to remember about GCD in C

Compute gcd the interview-friendly way.

5
Core concepts
0 02

Stop

When b = 0, return a

Base
L 03

Iterative

O(1) space loop

Code
R 04

Recursive

Same math, stack depth

Code
O 05

Complexity

O(log min(a,b))

Analysis

❓ Frequently Asked Questions

The greatest common divisor d of a and b is the largest positive integer that divides both a and b (when at least one is nonzero). Often written gcd(a,b) or (a,b).
For n > 0, gcd(0, n) = n because every positive divisor of n divides 0 as well. gcd(0, 0) is sometimes left undefined; many libraries return 0.
Repeatedly replace (a, b) with (b, a mod b) until b is 0. The gcd is then a—the last nonzero remainder from the previous step.
C99 defines a/b truncating toward zero and a % b so that (a/b)*b + a%b == a. Euclidean gcd is cleaner if you first reduce to nonnegative magnitudes.
It avoids expensive division on some hardware by using shifts and subtraction; asymptotics are similar for word-sized integers, but it is a useful alternative for very large integers in specialized libraries.
Euclid's algorithm on L-bit inputs takes O(L) arithmetic steps in the worst case (Lamé/Fibonacci bound); each step dominates at O(1) for fixed-width int.
For nonnegative a and b not both zero, lcm(a,b) = |a*b| / gcd(a,b). Compute gcd first to avoid overflow when forming the product carelessly.
When gcd(a,b) = 1. That is the condition for a modular inverse of a modulo b to exist (when b > 1).

Did you Know? 🔊

Bézout’s identity: for integers a, b not both zero, there exist integers x, y with gcd(a,b) = a x + b y. The extended Euclidean algorithm finds such coefficients while computing the gcd.

Continue to Happy Number

Learn how to check whether a number reaches 1 under repeated digit-square sums.

Happy number tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

8 people found this page helpful