Java Program to Find GCD Using Recursion
gcd(int a, int b) that returns b == 0 ? a : gcd(b, a % b).Examples
How to Think About It
Algorithm
Code
public class GCD { public static int gcd(int a, int b) { if (b == 0) { return a; } return gcd(b, a % b); } public static void main(String[] args) { int num1 = 48, num2 = 18; System.out.println("GCD of " + num1 + " and " + num2 + " is " + gcd(num1, num2)); } }
Dry Run
Let's trace gcd(48, 18) through the code
Initial call
gcd(48, 18) checks if 18 == 0 (false), calls gcd(18, 48 % 18)
Second call
gcd(18, 12) checks if 12 == 0 (false), calls gcd(12, 18 % 12)
Third call
gcd(12, 6) checks if 6 == 0 (false), calls gcd(6, 12 % 6)
Fourth call
gcd(6, 0) checks if 0 == 0 (true), returns 6
Return values
Each call returns 6 back up the chain
| Call | a | b | a % b | Return |
|---|---|---|---|---|
| 1 | 48 | 18 | 12 | gcd(18, 12) |
| 2 | 18 | 12 | 6 | gcd(12, 6) |
| 3 | 12 | 6 | 0 | gcd(6, 0) |
| 4 | 6 | 0 | - | 6 |
Why This Works
Step 1: Base case
When the second number b becomes zero, the first number a is the GCD, so the recursion stops.
Step 2: Recursive call
If b is not zero, the function calls itself with b and the remainder of a % b, reducing the problem size.
Step 3: Mathematical property
This works because the GCD of two numbers also divides their remainder, so the problem simplifies each time.
Alternative Approaches
public class GCD { public static int gcd(int a, int b) { while (b != 0) { int temp = b; b = a % b; a = temp; } return a; } public static void main(String[] args) { int num1 = 48, num2 = 18; System.out.println("GCD of " + num1 + " and " + num2 + " is " + gcd(num1, num2)); } }
public class GCD { public static int gcd(int a, int b) { if (a == b) { return a; } if (a > b) { return gcd(a - b, b); } else { return gcd(a, b - a); } } public static void main(String[] args) { int num1 = 48, num2 = 18; System.out.println("GCD of " + num1 + " and " + num2 + " is " + gcd(num1, num2)); } }
Complexity: O(log(min(a, b))) time, O(log(min(a, b))) space
Time Complexity
Each recursive call reduces the problem size roughly by the remainder, so the number of calls is proportional to the logarithm of the smaller number.
Space Complexity
The recursion stack grows with each call, so space used is proportional to the number of recursive calls, which is O(log(min(a, b))).
Which Approach is Fastest?
The iterative approach avoids recursion overhead and uses constant space, making it faster and more memory efficient for large inputs.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Recursive (modulus) | O(log(min(a,b))) | O(log(min(a,b))) | Simple code, small inputs |
| Iterative (modulus) | O(log(min(a,b))) | O(1) | Large inputs, performance |
| Recursive (subtraction) | O(min(a,b)) | O(min(a,b)) | Educational, simple math |
% in recursion to reduce the problem size quickly.