Umm, I need to write a class for this assignment. The class has to compute fractions. I know how to do it, however, the answer must be reduced to lowest terms and that I do not know how to accomplish with the compiler. If someone could tell me how to go about this I would be really really grateful. The compiler I am using complies to the new standard and it is for unix.
Well you want to reduce the numerator(N) and denominator(D) by finding a factor that is common to both. The number that you are looking for is between 2 and the the smaller of the N or D divided by 2.
fraction& reduce(fraction& f) {
for (int i = 2; i < min(f.numerator, f.denominator) / 2; i++) {
while (f.numerator % i == 0 && f.denominator % i == 0) {
f.numerator \= i;
f.denominator \= i;
}
}
}
Sorry. I saw a couple of mistakes. Here is the revised version.
void reduce(fraction& f) {
for (int i = 2; i <= __min(f.numerator, f.denominator); i++) {
while (f.numerator % i == 0 && f.denominator % i == 0) {
f.numerator /= i;
f.denominator /= i;
}
}
}
This assumes you have the __min function. It is in the stdlib.h header file. This mean you will need #include <stdlib.h>
About the return type and parameters...
If it is in a class create it as a member function and you will not need parameters. The function will modify the N and D of the class.
0
a_wilso1Author Commented:
Hey thanks. This really helped
0
The revolutionary project management tool is here! Plan visually with a single glance and make sure your projects get done.
That works, but there are much better (much faster) ways to find the greatest common factor (GCF) of two numbers. A good book on algorithms will suggest some.
Actually, that doesn't always work. Consider what it would do to 4/8. I would become 2/4 but not 1/2.
A quick fix would be to skip the increment of i whenever you find a common factor. That would make it work, but it still would be inneficient.
>> The number that you are looking for is
>> between 2 and the the smaller of the N
>> or D divided by 2
Actually, the GCF, which is what you want, woudl be between 1 and the positive difference (subtraction) between the N and D. That is the key to many GCF algorithms. So you might consider working backwards (not starting at the low value, like 1 or 2, but instead start at the high end and decrement i. This will yeld the solution faster, but there still are faster ways, I just don't remember them. (They usually involve subtraction rather than division and rapidly converge on a solution.)
fraction& reduce(fraction& f) {
for (int i = 2; i < min(f.numerator, f.denominator) / 2; i++) {
while (f.numerator % i == 0 && f.denominator % i == 0) {
f.numerator \= i;
f.denominator \= i;
}
}
}