greatest common divisor c++
To find the greatest common divisor (GCD) of two numbers in C++, you can use the Euclidean algorithm. Here's an explanation of each step involved in finding the GCD:
Step 1: Accept two numbers from the user. Let's call them
num1
andnum2
.Step 2: Use a while loop to iterate until
num2
becomes 0. Inside the loop, perform the following steps:Step 2.1: Calculate the remainder of
num1
divided bynum2
. This can be done using the modulus operator%
. Assign the result to a variable, let's call itremainder
.Step 2.2: Assign the value of
num2
tonum1
.Step 2.3: Assign the value of
remainder
tonum2
.Step 3: Once the while loop terminates (when
num2
becomes 0), the value ofnum1
will be the GCD of the original two numbers.
Here is an example code snippet that implements the above steps:
#include <iostream>
int main() {
int num1, num2;
std::cout << "Enter the first number: ";
std::cin >> num1;
std::cout << "Enter the second number: ";
std::cin >> num2;
while (num2 != 0) {
int remainder = num1 % num2;
num1 = num2;
num2 = remainder;
}
std::cout << "The greatest common divisor is: " << num1 << std::endl;
return 0;
}
In this code, the user is prompted to enter two numbers. The while loop performs the Euclidean algorithm until num2
becomes 0. Finally, the GCD is displayed as the value of num1
.