Reputation: 368
I have made a console app that adds and subtracts fractions, I have added a function to simplify:
public static Numbers Add(Numbers n1, Numbers n2)
{
int den1;
int num1;
int num2;
int dsimp;
int nsimp;
int numtop;
num1 = n1.Numerator * n2.Denominator;
num2 = n2.Numerator * n1.Denominator;
den1 = n1.Denominator * n2.Denominator;
numtop = num2 + num1;
if (numtop == 0)
{
return new Numbers(0);
}
if (numtop % n1.Denominator == 0)
{
nsimp = numtop / n1.Denominator;
dsimp = den1 / n1.Denominator;
return new Numbers(nsimp, dsimp);
}
else
{
return new Numbers(numtop, den1);
}
}
When I put in 1/2 + 4/8 it simplifies it all perfectly the way I tell it to, but, it gives me 8/8. This needs to be simplified to 1/1. How do I get it to simplify what has already been simplified to the lowest possible fraction?
Upvotes: 4
Views: 2846
Reputation: 117290
Divide the numerator and denominator by the GCD (greatest common divisor) of the numerator and denominator.
Eg:
Start with say 12/8. The GCD is 4. Thus 3/2.
Upvotes: 8