- Share
- Both divisible by 4
Find GCD (HCF) in C#
What you’ll learn
- What GCD (greatest common divisor / HCF) means and why it matters in fractions and number theory.
- The classic Euclidean algorithm with a
whileloop — the standard C# interview answer. - A recursive version of the same idea, plus how GCD connects to LCM and common divisors.
Overview
GCD is a staple interview math problem. The Euclidean algorithm replaces repeated subtraction with modulo steps, finishing in logarithmic time. You will also see when to use Math.Abs and how to handle zeros.
Two programs
Iterative Euclidean loop and recursive gcd for comparison.
Live preview
Type two integers and watch the Euclidean steps compute GCD.
Real uses
Simplify fractions, find LCM, and list all common divisors efficiently.
Prerequisites
Integer division, modulo (%), and while loops in C#.
- C# basics:
staticmethods,Console.WriteLine, string interpolation. - Know that
a % bis the remainder after dividingabyb.
What is GCD?
The greatest common divisor (GCD) — also called the highest common factor (HCF) — of two integers is the largest positive whole number that divides both without a remainder.
For 48 and 18, the common divisors are 1, 2, 3, and 6. The largest is 6, so gcd(48, 18) = 6.
Euclidean definition
For integers a and b with b ≠ 0: gcd(a, b) = gcd(b, a mod b). Repeat until the second argument is 0; the GCD is the remaining first argument. Example trace for 48 and 18:
gcd(48,18) → gcd(18,12) → gcd(12,6) → gcd(6,0) = 6
Quick examples
- Name
- Coprime (relatively prime)
Takeaway: GCD finds the biggest shared factor — useful to reduce 12/18 to 2/3 by dividing top and bottom by 6.
Live preview
Enter two integers. The widget runs the Euclidean algorithm and shows each step.
Algorithm
Goal: compute gcd(a, b) for integers using the Euclidean method.
Normalize
Work with a = Math.Abs(a) and b = Math.Abs(b). Handle (0,0) separately if needed.
Loop while b ≠ 0
Save temp = b, set b = a % b, set a = temp.
Return a
When b becomes 0, a holds the GCD.
📜 Pseudocode
function gcd(a, b):
a = absolute value of a
b = absolute value of b
while b != 0:
temp = b
b = a mod b
a = temp
return a Iterative Euclidean GCD
Classic reference solution: FindGCD uses a while loop with modulo. Sample inputs 48 and 18 print GCD 6.
using System;
class Program
{
static int FindGCD(int num1, int num2)
{
num1 = Math.Abs(num1);
num2 = Math.Abs(num2);
while (num2 != 0)
{
int temp = num2;
num2 = num1 % num2;
num1 = temp;
}
return num1;
}
static void Main()
{
int number1 = 48;
int number2 = 18;
int gcd = FindGCD(number1, number2);
Console.WriteLine($"GCD of {number1} and {number2} is: {gcd}");
}
} Explanation
Each loop iteration shrinks the problem: gcd(48,18) becomes gcd(18,12), then gcd(12,6), then gcd(6,0)=6.
num2 = num1 % num2;Remainder step. This is the heart of the Euclidean algorithm.
Recursive Euclidean GCD
Same math, expressed recursively: gcd(a,b) = gcd(b, a % b) until b == 0.
using System;
class Program
{
static int GcdRecursive(int a, int b)
{
a = Math.Abs(a);
b = Math.Abs(b);
if (b == 0)
return a;
return GcdRecursive(b, a % b);
}
static void Main()
{
int number1 = 48;
int number2 = 18;
Console.WriteLine($"GCD of {number1} and {number2} is: {GcdRecursive(number1, number2)}");
}
} Explanation
The base case b == 0 returns a. Otherwise the method delegates to a smaller pair — elegant, but uses call-stack depth proportional to the number of steps.
Beyond the basics
Binary GCD (Stein). Uses shifts and subtraction; can be faster for very large integers on some hardware.
LCM. lcm(a,b) = Math.Abs(a / gcd(a,b) * b) — divide first by gcd to reduce overflow risk when computing LCM.
Interview: write the modulo loop first, mention recursion as an alternative, then link GCD to simplifying fractions or finding LCM.
❓ FAQ
🔄 Input / output examples
Change number1 and number2 in Main, or read from console after validation.
| a | b | gcd(a,b) |
|---|---|---|
48 | 18 | 6 |
12 | 8 | 4 |
9 | 10 | 1 |
0 | 7 | 7 |
Edge cases and pitfalls
GCD is forgiving once you normalize signs — except the all-zero corner case.
gcd(0, n)
Returns |n|. gcd(0,0) is undefined — return 0 or throw with a comment.
gcd(-48, 18)
Use Math.Abs so the answer stays positive (6).
gcd(n, n)
Returns |n| — both numbers share all of their divisors.
gcd(a,b) vs gcd(b,a)
Same result — GCD is commutative.
⏱️ Time and space complexity
| Version | Time | Extra space |
|---|---|---|
| Iterative Euclidean | O(log min(|a|,|b|)) | O(1) |
| Recursive Euclidean | O(log min(|a|,|b|)) | O(log min(|a|,|b|)) stack |
| Naive scan 1..min | O(min(|a|,|b|)) | O(1) |
The Euclidean algorithm is the efficient standard; naive divisor scanning is only for tiny teaching examples.
Summary
- Definition: GCD is the largest positive integer dividing both inputs.
- C#: Euclidean
while (b != 0)loop witha % b— addMath.Absfor negatives. - Next step: list all common divisors via common divisors or compute LCM from GCD.
The Euclidean algorithm for GCD is one of the oldest algorithms still in daily use — Euclid described the idea around 300 BCE. In interviews, the iterative while (b != 0) version is what most hiring pairs expect first.
7 people found this page helpful
