Go Program to Find GCD Using Recursion
func gcd(a, b int) int { if b == 0 { return a } return gcd(b, a % b) } which calls itself until the remainder is zero.Examples
How to Think About It
Algorithm
Code
package main import "fmt" func gcd(a, b int) int { if b == 0 { return a } return gcd(b, a%b) } func main() { fmt.Println(gcd(48, 18)) }
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 chain
Returns 6 back through all previous calls
| Call | a | b | a % b | Return Value |
|---|---|---|---|---|
| 1 | 48 | 18 | 12 | calls gcd(18,12) |
| 2 | 18 | 12 | 6 | calls gcd(12,6) |
| 3 | 12 | 6 | 0 | calls gcd(6,0) |
| 4 | 6 | 0 | - | returns 6 |
Why This Works
Step 1: Base Case
The function stops calling itself when the second number b becomes zero, returning the first number a as the GCD.
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 Principle
This works because the GCD of two numbers also divides their remainder, so the problem simplifies until the remainder is zero.
Alternative Approaches
package main import "fmt" func gcdIterative(a, b int) int { for b != 0 { a, b = b, a%b } return a } func main() { fmt.Println(gcdIterative(48, 18)) }
package main import "fmt" func gcdSubtraction(a, b int) int { if a == b { return a } if a > b { return gcdSubtraction(a-b, b) } return gcdSubtraction(a, b-a) } func main() { fmt.Println(gcdSubtraction(48, 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 recursive modulus method is generally faster and cleaner than subtraction. Iterative avoids recursion overhead but is similar in speed.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Recursive modulus | O(log(min(a,b))) | O(log(min(a,b))) | Clean code, teaching recursion |
| Iterative modulus | O(log(min(a,b))) | O(1) | Performance-critical code avoiding recursion |
| Subtraction method | O(min(a,b)) | O(min(a,b)) | Simple logic but slower for large inputs |