cpp code for euclids GCD
#include <iostream>
int euclideanGcd(int a, int b) {
while (b != 0) {
int temp = b;
b = a % b;
a = temp;
}
return a;
}
int main() {
int a, b;
std::cout << "Enter two numbers: ";
std::cin >> a >> b;
std::cout << "GCD of " << a << " and " << b << " is " << euclideanGcd(a, b) << std::endl;
return 0;
}
Step-by-Step Explanation:
The code begins with the inclusion of the
iostream
library, which provides input and output capabilities.The function
euclideanGcd
is defined, which takes two integer parametersa
andb
and returns an integer.Inside the function, a
while
loop is used to calculate the GCD using the Euclidean algorithm. The loop continues untilb
becomes 0.Inside the loop, the value of
b
is stored in a temporary variabletemp
to avoid losing its value during the calculation.The value of
b
is updated to the remainder ofa
divided byb
using the modulo operator%
.The value of
a
is updated to the value stored intemp
, which is the original value ofb
.Once the loop ends, the function returns the value of
a
, which is the calculated GCD.In the
main
function, two integer variablesa
andb
are declared.The user is prompted to enter two numbers using the
std::cout
andstd::cin
statements.The GCD of the entered numbers is calculated by calling the
euclideanGcd
function witha
andb
as arguments.The result is displayed using the
std::cout
statement.Finally, the
main
function returns 0 to indicate successful execution of the program.