The Greatest Common Divisor (GCD) of two numbers is the largest number that divides both numbers without leaving a remainder. For example, the GCD of 48 and 18 is 6 because 6
is the largest number that divides both evenly.
One of the most efficient ways to compute the GCD is using recursion, specifically Euclid’s Algorithm:
b == 0
, then GCD(a, b) = a
(base case).GCD(a, b) = GCD(b, a % b)
(recursive case).This algorithm repeatedly reduces the problem size until reaching the base case.
public class GCDRecursion {
// Recursive method to find GCD using Euclidean Algorithm
public static int findGCD(int a, int b) {
if (b == 0) {
return a; // Base case: when the second number becomes zero
}
return findGCD(b, a % b); // Recursive case: call GCD with (b, remainder of a/b)
}
public static void main(String[] args) {
int num1 = 48, num2 = 18;
System.out.println("GCD of " + num1 + " and " + num2 + " is: " + findGCD(num1, num2));
}
}
GCD of 48 and 18 is: 6
b == 0
, return a
as the GCD.a % b
to get the remainder.findGCD(b, a % b)
, reducing the problem size with each call.findGCD(48, 18) → findGCD(18, 48 % 18) → findGCD(18, 12)
findGCD(18, 12) → findGCD(12, 18 % 12) → findGCD(12, 6)
findGCD(12, 6) → findGCD(6, 12 % 6) → findGCD(6, 0)
findGCD(6, 0) → Return 6 (Base case reached)
✅ Efficient Approach – Euclidean Algorithm runs in O(log(min(a, b)))
time.
✅ Recursive Simplicity – Reduces problem size at each step until base case.
✅ Real-World Usage – Common in number theory, cryptography, and computing least common multiples (LCM).