C PROGRAM • FUNCTIONS & RECURSION
Find GCD of Two Numbers Using Recursion
Use Euclid's algorithm to repeatedly replace two numbers with the smaller problem gcd(b, a % b) until the remainder becomes zero.
PROBLEM UNDERSTANDING
What should the program do?
Read two positive integers and print their greatest common divisor. The GCD is the largest positive integer that divides both numbers without leaving a remainder.
48 18
Enter two positive integers: 48 18 GCD of 48 and 18 is 6.
C PROGRAM
GCD using recursion
CURRENT STEP
VARIABLES
| Scope | Name | Value |
|---|---|---|
| Not started | ||
CALL STACK
PROGRAM OUTPUT
Waiting to run…
PROGRAM EXPLANATION
How the recursive solution works
main()reads two positive integers.gcd(a, b)checks whetherbis zero.- If
b == 0, the current value ofais the GCD. - Otherwise, the function calls
gcd(b, a % b). - Each call creates a smaller remainder, so the recursion eventually reaches zero.
Dry run for 48 and 18
gcd(48, 18) → gcd(18, 12) → gcd(12, 6) → gcd(6, 0) → return 6
EFFICIENCY
Time and space complexity
O(log(min(a, b))) because each recursive call quickly reduces the remainder.
O(log(min(a, b))) because the recursive calls remain on the call stack.
DEBUGGING CHECKLIST
Common mistakes
Without if (b == 0), recursive calls may continue incorrectly and exhaust the call stack.
The recursive call must be gcd(b, a % b), not gcd(a, a % b).
Euclid's algorithm needs the remainder operator %, not the division operator /.
For this beginner example, use positive integers so that the recursive flow is easy to understand.