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:
We include the
<iostream>
library to use input and output stream operations.We define a function
gcd
that takes two integersa
andb
as parameters and returns an integer. This function calculates the GCD using the Euclidean algorithm.Inside the
gcd
function, we check ifb
is equal to 0. If it is, we returna
because the GCD ofa
and 0 isa
.If
b
is not equal to 0, we recursively call thegcd
function withb
as the first argument anda % b
as the second argument. This step calculates the GCD ofa
andb
by repeatedly dividinga
byb
and taking the remainder untilb
becomes 0.In the
main
function, we declare two integer variablesnum1
andnum2
to store the user input.We prompt the user to enter two numbers using the
cout
object and read the input using thecin
object.We call the
gcd
function withnum1
andnum2
as arguments and store the result in theresult
variable.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.