C++ Implementation
Standard Library Solution
C++ provides built-in GCD functionality through the <numeric>
header in modern C++ standards.
Standard Library Method
#include <numeric>
#include <iostream>
int main() {
int a = 48, b = 18;
int result = std::gcd(a, b);
std::cout << "GCD of " << a << " and " << b << " is: " << result << std::endl;
return 0;
}
Custom Template Implementation
Generic GCD Function
template <typename T>
T gcd(T a, T b) {
while (b != 0) {
T temp = b;
b = a % b;
a = temp;
}
return a;
}
Advanced Implementation Techniques
Compile-Time GCD Calculation
template <int A, int B>
struct CompileTimeGCD {
static constexpr int value =
B == 0 ? A : CompileTimeGCD<B, A % B>::value;
};
template <int A>
struct CompileTimeGCD<A, 0> {
static constexpr int value = A;
};
Error Handling and Validation
template <typename T>
T safeGCD(T a, T b) {
// Handle potential overflow
if (a == std::numeric_limits<T>::min() &&
b == std::numeric_limits<T>::min()) {
throw std::overflow_error("GCD overflow");
}
// Ensure positive inputs
a = std::abs(a);
b = std::abs(b);
return gcd(a, b);
}
graph TD
A[GCD Implementation] --> B[Recursive]
A --> C[Iterative]
A --> D[Template Metaprogramming]
B --> E[Simple]
C --> F[Efficient]
D --> G[Compile-Time]
Practical Usage Patterns
Use Case |
Description |
Example |
Fraction Reduction |
Simplify fractions |
12/18 โ 2/3 |
Cryptography |
Key generation |
RSA algorithm |
Number Theory |
Mathematical computations |
Prime factorization |
Optimization Strategies
- Use references to avoid unnecessary copying
- Implement inline functions
- Leverage compiler optimizations
LabEx Recommended Approach
class GCDCalculator {
public:
template <typename T>
static T calculate(T a, T b) {
// Robust implementation
return std::gcd(std::abs(a), std::abs(b));
}
};
Complete Example
#include <iostream>
#include <numeric>
#include <stdexcept>
class GCDSolver {
public:
template <typename T>
static T solve(T a, T b) {
try {
return std::gcd(std::abs(a), std::abs(b));
} catch (const std::exception& e) {
std::cerr << "GCD Calculation Error: " << e.what() << std::endl;
return T{0};
}
}
};
int main() {
std::cout << "GCD of 48 and 18: "
<< GCDSolver::solve(48, 18) << std::endl;
return 0;
}
By mastering these implementation techniques, developers can create robust and efficient GCD solutions in C++.