GCD (Greatest Common Divisor) or HCF (Highest Common Factor) of two numbers is the largest number that exactly divides both numbers. For example, gcd of 12 and 16 is 4.
In this article, we will learn to write a C++ program to find the GCD of two numbers.
Example:
#include <bits/stdc++.h>
using namespace std;
int main() {
int a = 12, b = 16;
int res = min(a, b);
while (res > 1) {
if (a % res == 0 && b % res == 0)
break;
res--;
}
cout <<res;
return 0;
}
Output
4
Explanation: The idea is to find the common divisor by checking the divisibility of both numbers using the (%) modulo operator with all the numbers starting from the minimum number to 1.
Below are some other ways to calculating GCD in C++:
Using Euclidean Algorithm
The Euclidean algorithm is an efficient method to find the GCD of two numbers. It works on the principle that the GCD of two numbers remains the same if the greater number is replaced by the difference between the two numbers.
#include <bits/stdc++.h>
using namespace std;
int gcd(int a, int b) {
if (a == 0)
return b;
if (b == 0)
return a;
if (a == b)
return a;
if (a > b)
return gcd(a - b, b);
return gcd(a, b - a);
}
int main() {
int a = 12, b = 16;
cout << gcd(a, b);
return 0;
}
Output
4
Using Library Functions
In C++ Standard Library, there are two standard library functions: __gcd() and gcd() which is used for calculating the GCD of two numbers but they are present since C++ 14 and C++ 17 standard only. __gcd() is defined inside <algorithm> header file and gcd() is defined inside <numeric> header file.
Syntax
__gcd(a, b) // Since C++ 14
gcd(a, b) // Since C++ 17
Parameters
- a: First number.
- b: Second number.
Return Value: return an "int" (gcd of both numbers).
Code Implementation
#include <bits/stdc++.h>
using namespace std;
int main() {
int a = 12, b = 16;
cout << __gcd(a, b) << endl;
cout << gcd(a, b);
return 0;
}
Output
4 4