C# GCD of Two Numbers Program

Beginner
6 min read
Updated: Oct 2026
3 programs
Live preview

What Is GCD?

The GCD (Greatest Common Divisor), also called HCF, is the largest positive integer that divides both numbers with no remainder.

Remember
gcd(a, b) = largest d > 0 such that
            a % d == 0 and b % d == 0

Example: gcd(48, 18) = 6
  48 = 6 * 8
  18 = 6 * 3
  No larger positive integer divides both
abgcd(a, b)
48186
17131
02121
-12186

How to Find GCD in C#

Four clear steps — Euclid’s remainder loop is the interview default.

  1. Take absolute values of a and b so the result is nonnegative.
  2. While b != 0, replace (a, b) with (b, a % b).
  3. When b becomes 0, return a — that is the GCD.
  4. Optionally derive LCM with |a * b| / gcd(a, b).
MethodIdeaTimeBest for
Iterative EuclidLoop with a % b until b == 0O(log min)Interviews, production default
Recursive Euclidgcd(b, a % b) until base caseO(log min)Showing the recurrence
LCM via GCD|a * b| / gcd(a, b)O(log min)Follow-up questions

Pseudocode

Pseudocode
function Gcd(a, b):
    a = abs(a)
    b = abs(b)

    while b != 0:
        temp = b
        b = a mod b
        a = temp

    return a

function Lcm(a, b):
    if a == 0 or b == 0:
        return 0
    return abs(a / Gcd(a, b) * b)

Cheat Sheet

Keep these facts handy while writing the program.

TopicDetail
Core step(a, b) ← (b, a % b)
Stop whenb == 0; answer is a
SignsUse Math.Abs first
gcd(0, n)|n| for n != 0
gcd(0, 0)Usually defined as 0
LCM linklcm = |a * b| / gcd
Classic checkgcd(48, 18) = 6

Live Preview

Enter two integers to see the Euclidean remainder chain and the GCD.

Whole numbers only. Tap a chip or type a pair.

Result
a = 48, b = 18
Chain: (48, 18) → (18, 12) → (12, 6) → (6, 0)
gcd = 6

Worked Walkthrough — gcd(48, 18)

Apply Euclid’s step until the remainder is zero.

Calculation
Start: a = 48, b = 18

Step 1: 48 % 18 = 12  → (18, 12)
Step 2: 18 % 12 = 6   → (12, 6)
Step 3: 12 % 6  = 0   → (6, 0)

Stop (b == 0)
gcd(48, 18) = 6

Check: 48 / 6 = 8,  18 / 6 = 3

C# Programs

Start with the iterative loop — it is the clearest interview answer. Then show the recursive form, and finish with LCM built from GCD.

Example 1 — Iterative Euclidean Algorithm

Loop with remainders until the second value becomes zero.

C#
using System;

class Program
{
    static int Gcd(int a, int b)
    {
        a = Math.Abs(a);
        b = Math.Abs(b);

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

        return a;
    }

    static void Main()
    {
        int number1 = 48;
        int number2 = 18;
        Console.WriteLine("GCD of " + number1 + " and " + number2 + " is: " + Gcd(number1, number2));
    }
}

How It Works

  1. Take absolute values so negatives do not break the remainder chain.
  2. While b != 0, store b, set b = a % b, then set a to the old b.
  3. For (48, 18) the pairs become (18, 12), (12, 6), then (6, 0).
  4. When b is 0, return a — here 6.
  5. Extra space is O(1); time is logarithmic in the smaller number.

Example 2 — Recursive Euclidean Algorithm

Same remainder idea, written as a recurrence with a clear base case.

C#
using System;

class Program
{
    static int Gcd(int a, int b)
    {
        a = Math.Abs(a);
        b = Math.Abs(b);

        if (b == 0)
        {
            return a;
        }

        return Gcd(b, a % b);
    }

    static void Main()
    {
        int number1 = 48;
        int number2 = 18;
        Console.WriteLine("GCD of " + number1 + " and " + number2 + " is: " + Gcd(number1, number2));
    }
}

How It Works

  1. Base case: if b == 0, return a.
  2. Otherwise recurse on Gcd(b, a % b).
  3. Calls for (48, 18): (18, 12) → (12, 6) → (6, 0) → return 6.
  4. Same answer as the loop; stack depth is about O(log min(a, b)).
  5. Prefer the iterative version when you must mention space carefully.

Example 3 — LCM via GCD

Use the identity lcm(a, b) = |a / gcd * b| after finding the GCD.

C#
using System;

class Program
{
    static int Gcd(int a, int b)
    {
        a = Math.Abs(a);
        b = Math.Abs(b);

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

        return a;
    }

    static long Lcm(int a, int b)
    {
        if (a == 0 || b == 0)
        {
            return 0;
        }

        int g = Gcd(a, b);
        return Math.Abs((long)a / g * b);
    }

    static void Main()
    {
        int a = 48;
        int b = 18;
        Console.WriteLine("gcd = " + Gcd(a, b));
        Console.WriteLine("lcm = " + Lcm(a, b));
    }
}

How It Works

  1. Reuse the same iterative Gcd helper.
  2. If either input is 0, LCM is defined as 0 here.
  3. Divide one value by the GCD first: a / g * b reduces overflow risk.
  4. Cast to long before multiplying for a safer product.
  5. Check: 48 / 6 * 18 = 8 * 18 = 144, and 144 / 48 = 3, 144 / 18 = 8.

Edge Cases & Pitfalls

Check these before calling the solution done.

Zero

gcd(0, n)

For n != 0, the answer is |n|. Euclid already handles this.

Both zero

gcd(0, 0)

Conventionally return 0. Say your choice out loud in interviews.

Negatives

Use Math.Abs

C# % keeps the dividend’s sign. Normalize first for a nonnegative GCD.

LCM

Divide before multiply

Compute a / gcd * b (with a wider type) instead of a * b / gcd when values are large.

Time and Space Complexity

ProgramTimeExtra space
Iterative EuclidO(log min(a, b))O(1)
Recursive EuclidO(log min(a, b))O(log min(a, b))
LCM via GCDO(log min(a, b))O(1)

Worst-case Euclid pairs are consecutive Fibonacci numbers, but the step count still grows logarithmically.

Key Takeaways

  • Definition: largest positive integer that divides both values.
  • Euclid: replace (a, b) with (b, a % b) until b == 0.
  • LCM: |a / gcd * b| after finding the GCD.
  • Test set: (48, 18) → 6; (17, 13) → 1; (0, 21) → 21.

One line: keep taking remainders — when the remainder hits zero, the other value is the GCD.

Frequently Asked Questions

The greatest common divisor (also called HCF) is the largest positive integer that divides both numbers without a remainder.
Replace (a, b) with (b, a % b) until b becomes 0. Then a is the GCD. Always take absolute values first.
For n != 0, gcd(0, n) equals |n|. By convention, many libraries define gcd(0, 0) as 0.
Both are correct. Prefer the iterative loop in interviews for O(1) extra space; recursion uses O(log min(a,b)) stack depth.
For nonzero a and b: lcm(a, b) = |a * b| / gcd(a, b). Compute GCD first to avoid overflow when possible.

Next: Happy Number

Check whether repeated digit-square sums reach 1.

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.

12 people found this page helpful