Ruby Program to Find GCD Using Recursion
def gcd(a, b); b == 0 ? a : gcd(b, a % b); end which calls itself until the remainder is zero.Examples
How to Think About It
Algorithm
Code
def gcd(a, b) return a if b == 0 gcd(b, a % b) end puts gcd(48, 18)
Dry Run
Let's trace gcd(48, 18) through the code
Initial call
gcd(48, 18) checks if 18 == 0 (false), so calls gcd(18, 48 % 18) which is gcd(18, 12)
Second call
gcd(18, 12) checks if 12 == 0 (false), so calls gcd(12, 18 % 12) which is gcd(12, 6)
Third call
gcd(12, 6) checks if 6 == 0 (false), so calls gcd(6, 12 % 6) which is gcd(6, 0)
Base case
gcd(6, 0) returns 6 because second number is zero
| Call | a | b | a % b |
|---|---|---|---|
| 1 | 48 | 18 | 12 |
| 2 | 18 | 12 | 6 |
| 3 | 12 | 6 | 0 |
| 4 | 6 | 0 | - |
Why This Works
Step 1: Check if second number is zero
The function stops when the second number is zero because the first number at that point is the GCD.
Step 2: Recursive call with remainder
Each recursive call reduces the problem by replacing the first number with the second, and the second with the remainder of the first divided by the second.
Step 3: Eventually reach base case
This process repeats until the remainder is zero, ensuring the GCD is found.
Alternative Approaches
def gcd_iterative(a, b) while b != 0 a, b = b, a % b end a end puts gcd_iterative(48, 18)
puts 48.gcd(18)
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, which decreases quickly, leading to logarithmic time complexity.
Space Complexity
Recursive calls add to the call stack, so space complexity is proportional to the number of calls, which is logarithmic.
Which Approach is Fastest?
The built-in Ruby method is fastest and most optimized, followed by the iterative approach, then recursion due to call stack overhead.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Recursive | O(log(min(a,b))) | O(log(min(a,b))) | Learning recursion and elegant code |
| Iterative | O(log(min(a,b))) | O(1) | Performance and avoiding stack overflow |
| Built-in method | O(log(min(a,b))) | O(1) | Fastest and simplest for production |