I've been making a program for an assignment that converts fractions to mixed numbers, and I'm done, but I was wondering if I could simplify it in any way, since it seems quite complicated right now.
Also, keep in mind that I am not allowed to use any Math
or String
methods to do this assignment, and I can only use +, -, *, and / as arithmetic operators. I also cannot use % or a modulus function.
I realize this is an assignment, and it's fine if you choose not to give me an answer. In fact, I'd actually prefer to have some tips or hints to help figure out how to solve it, rather than just telling me the answer.
Also, the 'c.print' is basically a print statement. I'm importing/using a different custom class, which is why it is different from the normal print statement.
int numerator = 0; //can change to any value
int denominator = -2; //can change to any value
public int[] reducedFraction (int numerator, int denominator)
{
int GCD = numerator;
int tempN = numerator;
int tempD = denominator;
int[] fractionParts = {0, numerator, denominator};
if (numerator == 0) //if the numerator is 0
{
return fractionParts;
}
//Making sure the program works with negative values by temporarily converting GCD and fractionParts[2] to positive values
GCD = (numerator < 0) ? -numerator:
numerator;
tempD = (denominator < 0) ? -denominator:
denominator;
//Finding the GCD of the numerator and denominator
while (GCD != tempD)
{
if (GCD > tempD)
GCD -= tempD;
else
tempD -= GCD;
}
//Simplfying numerator and denominator
fractionParts [1] /= GCD;
fractionParts [2] /= GCD;
//Temporarily making the numerator and denominator positive
tempN = (fractionParts [1] < 0) ? -fractionParts [1]:
fractionParts [1];
tempD = (fractionParts [2] < 0) ? -fractionParts [2]:
fractionParts [2];
//if the numerator is not greater than the denominator return the simplified fraction.
if (tempN < tempD)
{
return fractionParts;
}
//Finding value of whole number, numerator and possibly converting denominator to original sign
fractionParts [0] = fractionParts [1] / fractionParts [2];
fractionParts [1] = fractionParts [1] - (fractionParts [1] / fractionParts [2]) * fractionParts [2];
if (fractionParts [1] < 0 && fractionParts [2] < 0) //if the numerator and denominator are both negative
{
fractionParts [1] = (fractionParts [1] < 0) ? -fractionParts [1]:
fractionParts [1];
fractionParts [2] = (fractionParts [2] < 0) ? -fractionParts [2]:
fractionParts [2];
}
return fractionParts;
}
public void display ()
{
if (reducedFraction (numerator, denominator) [1] == 0)
c.print (reducedFraction (numerator, denominator) [0]);
else if (reducedFraction (numerator, denominator) [0] == 0)
c.print (reducedFraction (numerator, denominator) [1] + "/" + reducedFraction (numerator, denominator) [2]);
else
c.print (reducedFraction (numerator, denominator) [0] + " " + reducedFraction (numerator, denominator) [1] + "/" + reducedFraction (numerator, denominator) [2]);
}