3.5.4. gcd.cpp

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.

Test Cases

u v GCD
6 8 2
9 27 9
23 3 1

Program

#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;
}
gcd.cpp (loop version). Euclid's Algorithm for finding the greatest common divisor of two numbers.
  1. Data input
  2. Loop until u becomes 0 or negative, which implies that u must change inside the loop
  3. u must never be larger than v; if u becomes larger than v then
  4. swap u and v
  5. To end the loop, u must decrease: u -= v; (recall that u -= v is a shorthand for u = u - v)
  6. At the end of the algorithm, v contains the GCD of the two entered numbers
Adapted from Algorithms, Robert Sedgewick, Addison-Wesley Publishing Co., Reading, MA, 1983, p. 10.