-
need help
WHat is the best way to go about simplifying a fraction? I am working with 2 integers, numerator and denominator. if the fraction is in the form of 0/N then it will be set to 0/1. that is easy to code. I need this function to simplify all other fractions for example 2/4 --> 1/2 or 300/1000 --> 3/10. Should I use the modulus operator somehow?
-
Find the greatest common divisor of both integers & divide.
There are simple (inefficient) ways to do that, or you can read about
Euclid's algorithm
-
Heres code for finding the GCD. My school wrote this for us so using it shouldnt be to difficult. You just have to divide each of the fractions by GCD.
Code:
int greatestCommonDivisor(int x, int y) {
while (y != 0) {
int temp = x % y;
x = y;
y = temp;
}
return x;
}
So for example made a function called Simplify and in it first i called the GCD function above by passing the numerator and denomator. GCD function retuns the GCD and i divide the numerator and denominator by GCd in the simplify function.
Hope that helps