//
//
//  GCD.cc
//
//      AUTHOR: Russell Lowke
//         T.F: Francis Crick
//  CSCIE-s111: Unit Four, Hard Supp - question 9 [worth 2pts],  7/12/2002
//
//  Write a recursive function to compute the Greatest Common Divisor(GCD)
//  of two numbers
//

#include <iostream>
#include <iomanip>
#include <values.h>

//
//  reads an integer from the keyboard,
//  uses error checking to ensure value is between minValue and maxValue
//
int getInt(char askStr[], int minValue, int maxValue)
{
	int mVar;
	bool inputOK = false;
	
	while (! inputOK) { 
	
		cout << askStr;						// ask query
		cin >> mVar;						// get input
		
		if ( (mVar >= minValue && mVar <= maxValue) )
			inputOK = true;					// input OK, exit loop
		else {
			cout << "Bad input: please enter a value between "
			     << minValue << " and " << maxValue << endl;
			cin.clear();					// clear error
			cin.ignore(80, '\n');			// empty buffer
		}
	}
	
	return mVar;
}


//
//  Compute the Greatest Common Divisor (GCD) of two numbers
// 
int gcd(int firstNum, int secondNum)
{
	int higher, lower, gcd;
	
	if (firstNum > secondNum) {
		higher = firstNum;
		lower  = secondNum;
	} else {
		higher = secondNum;
		lower  = firstNum;
	}
	
	gcd = lower;							// start gcd at lower
	
	// loop while MOD is > 0
	while ( (higher % gcd) > 0 || (lower % gcd) > 0 ) {
		gcd--;								// decrement gcd
	}
	
	return gcd;
}


void main()
{
	int firstNum  = getInt(" First Number: ", 1, MAXINT);
	int secondNum = getInt("Second Number: ", 1, MAXINT);
    
    cout << "Greatest common divisor of " << firstNum 
         << " and " << secondNum << " is " << gcd(firstNum, secondNum) << endl;

	exit( 0 );
}