Cover Image for C++ program to find the GCD of two numbers
123 views

C++ program to find the GCD of two numbers

You can find the greatest common divisor (GCD) of two numbers in C++ using the Euclidean algorithm, which is a widely used method for this purpose. Here’s a C++ program to find the GCD of two numbers:

C++
#include <iostream>

// Function to find the GCD of two numbers using the Euclidean algorithm
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;
}

In this program:

  1. We define a gcd function that takes two integers a and b as input and calculates their GCD using the Euclidean algorithm. The algorithm repeatedly calculates the remainder (b) when a is divided by b until b becomes zero. At that point, the GCD is found in a.
  2. In the main function, we input two numbers from the user using std::cin.
  3. We call the gcd function with the two input numbers and store the result in the result variable.
  4. Finally, we print the GCD of the two numbers to the console.

When you run this program, it will calculate and display the GCD of the two input numbers.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS