The greatest common divisor (GCD) is the largest integer that can divide two given integers without a remainder. For example, the GCD of 6 and 8 is 2: 6/2=3 and 8/2=4. Euclid's Algorithm is an efficient way of calculating the GCD of two numbers. The following program uses a while loop to implement Euclid's Algorithm to find the GCD of two numbers a user enters.
u | v | GCD |
---|---|---|
6 | 8 | 2 |
9 | 27 | 9 |
23 | 3 | 1 |
#include <iostream> using namespace std; int main() { int u; cout << "Please enter u: "; // (a) cin >> u; int v; cout << "Please enter v: "; // (a) cin >> v; if (u <= 0 || v <= 0) { cerr << "u and v must be positive" << endl; exit(1); } while (u > 0) // (b) { if (u < v) // (c) { int t = u; // (d) u = v; v = t; } u -= v; // (e) } cout << "The GCD is " << v << endl; // (f) return 0; }
u -= v;
(recall that u -= v is a shorthand for u = u - v)