// Tony Zulani's Extra Credit
// Program Algorithm determines the greatest common divisor of two positive
// integers. It works out according to Euclid's algorithm. The data is taken
// from a file of values, and the output is also written to a file.
#include
#include
int FindGCD(int, int);
// Determines the GCD of two numbers
int main()
{
int value1; //the first value of a pair of numbers
int value2; //the second value of a pair of numbers
ifstream dataFile; //input file stream
ofstream gcdList; //output file stream
dataFile.open("data.in");
gcdList.open("data.out");
dataFile >> value1 >> value2; //priming read of two values
while(dataFile)
{
gcdList << "The GCD of the numbers " << value1 << " and " << value2
<< " is " << FindGCD(value1, value2) << endl;
dataFile >> value1 >> value2; //read next two values
}
return 0;
}
// **************************************************************************
int FindGCD(int num1, int num2)
//Pre: Two numbers have been input from a file stream
//Post: The greatest common divisor of the two numbers is found and returned
// to main.
{
int r; //remainder from division of the two numbers
int GCD; //greatest common divisor returned to main
int temp; //temporary variable in case num1 > num2
if (num1 > num2)
{
temp = num1; //num1 copied into temp;
num1 = num2; //num2 copied into num1;
num2 = temp; //temp copied into num2; now, num1 <= num2
}
r = num2 % num1; //determine the remainder
if (r == 0)
GCD = num1; //num1 is GCD
else
{
while (r != 0)
{
num2 = num1;
num1 = r;
r = num2 % num1;
}
GCD = num1; //num1 is GCD
}
return GCD;
}