c++ Greatest common divisor

To find the greatest common divisor (GCD) of two numbers in C++, you can use the Euclidean algorithm. The Euclidean algorithm is an efficient method for finding the GCD of two numbers.

Here is an example of how to implement the Euclidean algorithm in C++:

#include <iostream>

int gcd(int a, int b) {
    if (b == 0) {
        return a;
    }
    return gcd(b, a % b);
}

int main() {
    int num1, num2;
    std::cout << "Enter two numbers: ";
    std::cin >> num1 >> num2;

    int result = gcd(num1, num2);

    std::cout << "The GCD of " << num1 << " and " << num2 << " is " << result << std::endl;

    return 0;
}

Let's go through each step of the algorithm:

  1. We include the <iostream> library to use input and output stream operations.

  2. We define a function gcd that takes two integers a and b as parameters and returns an integer. This function calculates the GCD using the Euclidean algorithm.

  3. Inside the gcd function, we check if b is equal to 0. If it is, we return a because the GCD of a and 0 is a.

  4. If b is not equal to 0, we recursively call the gcd function with b as the first argument and a % b as the second argument. This step calculates the GCD of a and b by repeatedly dividing a by b and taking the remainder until b becomes 0.

  5. In the main function, we declare two integer variables num1 and num2 to store the user input.

  6. We prompt the user to enter two numbers using the cout object and read the input using the cin object.

  7. We call the gcd function with num1 and num2 as arguments and store the result in the result variable.

  8. Finally, we display the result using the cout object.

This implementation of the Euclidean algorithm in C++ will give you the greatest common divisor of two numbers.