Easy Tutorial
❮ Home Cpp Examples Add Numbers ❯

C++ Example - Finding the Greatest Common Divisor (GCD) of Two Numbers

C++ Examples

The user inputs two numbers, and the program calculates the greatest common divisor of these two numbers.

Example

#include <iostream>
using namespace std;

int main()
{
    int n1, n2;

    cout << "Enter two integers: ";
    cin >> n1 >> n2;

    while(n1 != n2)
    {
        if(n1 > n2)
            n1 -= n2;
        else
            n2 -= n1;
    }

    cout << "GCD = " << n1;
    return 0;
}

The output of the above program is:

Enter two integers: 78
52
GCD = 26

Example

#include <iostream>
using namespace std;

int main() {
    int n1, n2, gcd;
    cout << "Enter two integers: ";
    cin >> n1 >> n2;

    // Swap if n2 is greater than n1
    if ( n2 > n1) {   
        int temp = n2;
        n2 = n1;
        n1 = temp;
    }

    for (int i = 1; i <=  n2; ++i) {
        if (n1 % i == 0 && n2 % i ==0) {
            gcd = i;
        }
    }

    cout << "GCD = " << gcd;
    return 0;
}

The output of the above program is:

Enter two integers: 78
52
GCD = 26

C++ Examples

❮ Home Cpp Examples Add Numbers ❯