Write a C++ program that computes the GCD of two given numbers using the Euclidean algorithm.
Input and Output Examples
- Input: 56, 98 Output: The GCD is 14.
- Input: 22, 131 Output: The GCD is 1.
Algorithm to calculate the GCD of two numbers:
- Prompt the user to enter two integers.
- Use the Euclidean algorithm to find the GCD:
- Continue finding the remainder of the division of the two numbers until the remainder is zero.
- The divisor at this step will be the GCD.
- Display the GCD to the user.
Below is the C++ code to find the GCD of two numbers using the Euclidean algorithm:
#include <iostream>
using namespace std;
int main() {
int a, b;
// Step 1: Get two integers from the user
cout << "Enter two integers: ";
cin >> a >> b;
// Step 2: Apply the Euclidean algorithm to find the GCD
while (b != 0) {
int remainder = a % b;
a = b;
b = remainder;
}
// Step 3: The GCD is stored in 'a' after the loop completes
cout << "The GCD is " << a << ".";
return 0; // Successful completion of the program
}
Testing with Different Input Values
The above program is efficient and works correctly for all integer inputs, including negative numbers. The Euclidean algorithm inherently handles negative inputs, as the modulus operation consistently reduces the absolute values.
Input and Output Examples for the Modified Program:
- Input: 18, -84 Output: The GCD is 6.
- Input: -270, 192 Output: The GCD is 6.