Efficient method for finding GCD.
- Prime Factorization Method:
GCD.cpp
#include <iostream>
int gcd(int a, int b) {
int result = 1;
for (int i = 2; i <= std::min(a, b); ++i) {
while (a % i == 0 && b % i == 0) {
result *= i;
a /= i;
b /= i;
}
}
return result;
}
int main() {
int num1, num2;
std::cout << "Enter two numbers: ";
std::cin >> num1 >> num2;
std::cout << "GCD: " << gcd(num1, num2) << std::endl;
return 0;
}
- Euclidean Algorithm
GCD.cpp
#include <iostream>
int gcd(int a, int b) {
while (b != 0) {
int temp = b;
b = a % b;
a = temp;
}
return a;
}
int main() {
int num1, num2;
std::cout << "Enter two numbers: ";
std::cin >> num1 >> num2;
int result = gcd(num1, num2);
std::cout << "GCD of " << num1 << " and " << num2 << " is: " << result << std::endl;
return 0;
}