GCD using Recursion in C++
Recursive GCD in C++ using Euclid's algorithm: why gcd(b, a % b) works, a dry run for 48 and 18, negatives, LCM from GCD, and the zero-input case.
1#include <iostream>2using namespace std;34// Recursive function to calculate GCD using Euclidean algorithm5int gcd(int a, int b) {6 // Base case7 if (b == 0) {8 return a;9 }1011 // Recursive case12 return gcd(b, a % b);13}1415int main() {16 int num1, num2;1718 cout << "Enter two numbers: ";19 cin >> num1 >> num2;2021 // Handle negative numbers22 num1 = abs(num1);23 num2 = abs(num2);2425 int result = gcd(num1, num2);2627 cout << "GCD of " << num1 << " and " << num2 << " = " << result << endl;2829 // Calculate LCM using GCD30 int lcm = (num1 * num2) / result;31 cout << "LCM of " << num1 << " and " << num2 << " = " << lcm << endl;3233 // Test with multiple pairs34 cout << "\nGCD of various pairs:" << endl;35 int pairs[][2] = {{48, 18}, {100, 25}, {17, 13}, {56, 42}};3637 for (int i = 0; i < 4; i++) {38 int a = pairs[i][0];39 int b = pairs[i][1];40 cout << "GCD(" << a << ", " << b << ") = " << gcd(a, b) << endl;41 }4243 return 0;44}
Sample Output
LCM of 48 and 18 = 144
48 × 18 ÷ 6.
GCD(17, 13) = 1
Coprime numbers.
In this one
- How Euclid's algorithm shrinks the problem
- Why the base case is b == 0
- How to get the LCM from the GCD
- How to avoid overflow in the LCM
How it works
- 1
Read two numbers and take abs.
- 2
gcd(a, b) returns a when b is 0.
- 3
Otherwise it returns gcd(b, a % b).
- 4
LCM = num1 × num2 ÷ GCD.
- 5
Print GCDs for four test pairs.
Dry run: GCD using Recursion
gcd(48, 18)
- 1.→ gcd(18, 48 % 18 = 12)
- 2.→ gcd(12, 18 % 12 = 6)
- 3.→ gcd(6, 12 % 6 = 0)
- 4.→ 6
gcd(48, 18) → gcd(18, 48 % 18 = 12) → gcd(12, 18 % 12 = 6) → gcd(6, 12 % 6 = 0) → 6
Edge cases
Both zero
Enter 0 0.
gcd returns 0, and the LCM line divides by 0, which is undefined behavior and usually crashes. Check for zero before computing the LCM.
One zero
Enter 0 5.
gcd(0, 5) → gcd(5, 0) = 5, and the LCM is 0.
Large inputs
Enter 100000 99999.
num1 * num2 overflows int before the division. Compute num1 / result * num2 instead.
What's going on
The greatest common divisor (GCD) of two numbers is the largest number that divides both. This program finds it with Euclid's algorithm, written as a two-line recursion.
The rule is gcd(a, b) = gcd(b, a % b), and gcd(a, 0) = a. It works because any number that divides both a and b also divides a % b, so the pair shrinks while the GCD stays the same.
For 48 and 18: gcd(48, 18) → gcd(18, 12) → gcd(12, 6) → gcd(6, 0) → 6. Each step the remainder drops quickly, so it takes only a handful of calls even for large numbers. The number of steps grows with the number of digits, not the size of the values.
If a < b, the first step swaps them automatically: gcd(18, 48) → gcd(48, 18 % 48) = gcd(48, 18).
main first takes abs() of both inputs, so negative numbers work. (abs comes from <cstdlib>; it compiles here because <iostream> happens to pull it in on common compilers, but including <cstdlib> is the portable choice.)
The LCM line uses the identity lcm(a, b) = a × b ÷ gcd(a, b), giving 144 for 48 and 18. Multiplying first can overflow int for large inputs; a / gcd * b gives the same result with a smaller intermediate value.
The test table checks four pairs, including 17 and 13, which are coprime, so their GCD is 1.
The headers come first. <iostream> is there because it provides cout and cin for input/output operations. Leave one out and the compiler stops at the first name it does not recognize.
Understanding GCD
GCD Definition:
Example:
Euclidean Algorithm
Mathematical Principle:
What happens here:
Base Case
Stopping Condition:
if (b == 0) {
return a;
}
What happens here:
Recursive Case
Function Calls Itself:
return gcd(b, a % b);
What happens here:
Recursion Flow
Example: gcd(48, 18):
Calculating LCM
Using GCD:
lcm(a, b) = (a * b) / gcd(a, b)
What happens here:
Time Complexity
Efficiency:
Why Efficient:
When to Use Recursive GCD
Good fits:
Example Scenarios:
Important Considerations
Efficiency:
Mathematical Foundation:
Recursive Elegance:
return 0;
return 0; closes main and tells the operating system the program finished without an error.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
What is gcd(56, 42)?
Pick an answer to check it.
Question 2
Why does gcd(18, 48) still work?
Pick an answer to check it.
Questions people ask
Is there a built-in GCD?
Yes, std::gcd and std::lcm in <numeric> since C++17.
How many steps does Euclid take?
At most about five times the number of digits of the smaller number.
Why not just try every number down from the smaller one?
That is O(min(a, b)); Euclid is O(log min(a, b)).