155 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:
- We define a
gcd
function that takes two integersa
andb
as input and calculates their GCD using the Euclidean algorithm. The algorithm repeatedly calculates the remainder (b
) whena
is divided byb
untilb
becomes zero. At that point, the GCD is found ina
. - In the
main
function, we input two numbers from the user usingstd::cin
. - We call the
gcd
function with the two input numbers and store the result in theresult
variable. - 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.