// Fraction.cpp contains the definitions of the Fraction operations,
// as well as any auxillary functions they utilize.
//
// Begun by: Joel C. Adams, for Hands On C++.
// Completed by:
// Date:
//*****************************************************************
// replace this line with a #include of the Fraction header file
// Read() code
void Fraction::Read(istream & in)
{
char ch; // for reading a slash
in >> myNumerator // read Numerator
>> ch // read the slash
>> myDenominator; // read Denominator
}
//***********************************************************
// GreatestCommonDivisor finds the greatest common divisor *
// of two integers, using Euclid's (recursive) algorithm. *
// *
// Receive: alpha, beta, two integers. *
// Return: the greatest common divisor of alpha and beta. *
//***********************************************************
#include <cstdlib> // abs()
using namespace std;
int GreatestCommonDivisor(int alpha, int beta)
{
alpha = abs(alpha); // take absolute values of operands
beta = abs(beta);
if (beta == 0) // base case
return alpha;
else // induction step
{
int remainder = alpha % beta;
return GreatestCommonDivisor(beta, remainder);
}
}
//***********************************************************
// Simplify finds the simplest form of a fraction *
// *
// Receive: a fraction. *
// Return: the simplest form of the fraction. *
//***********************************************************
// Simplify() code
void Fraction::Simplify()
{
int num(myNumerator);
int denom(myDenominator);
int gcd;
while(true)
{
gcd = GreatestCommonDivisor(num, denom);
if (gcd == 1) break;
num = num / gcd;
denom = denom / gcd;
}
myNumerator = num;
myDenominator = denom;
return;
}