GCD of Two Numbers in C++

Last Updated : 25 May, 2026

The Greatest Common Divisor (GCD) of two numbers is the largest number that divides both numbers exactly without leaving a remainder. It is widely used in mathematics, cryptography, fractions, and competitive programming.

  • GCD is also called HCF (Highest Common Factor).
  • If the GCD of two numbers is 1, the numbers are called co-prime numbers.

Illustration

Find the GCD of 12 and 18

Factors of 12 -> 1, 2, 3, 4, 6, 12
Factors of 18 -> 1, 2, 3, 6, 9, 18
Common Factors -> 1, 2, 3, 6
Greatest Common Divisor (GCD) = 6

C++
#include <iostream>
#include <cmath>
using namespace std;

int main() {
    int a = 12, b = 18;

    a = abs(a);
    b = abs(b);

    if (a == 0 && b == 0) {
        cout << "Undefined";
        return 0;
    }

    while (b != 0) {
        int temp = b;
        b = a % b;
        a = temp;
    }

    cout << a;
    return 0;
}

Output
6

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.

C++
#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).

C++
#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;
}
Try It Yourself
redirect icon

Output
4
4
Comment