Hi I was wondering how I could re write this code so it will make my program more efficient and it will also be able to account for negative numerators (my program does not allow negative denominators or zero). My program takes a really long time when I start to enter large fractions because the loop has to go through so many times. If anyone could help me rewrite this so I don't have to wait so long and it will make my code more efficient I would greatly appreciate it!
1 2 3 4 5 6 7 8 9
void fraction::reduce()
for(int i = numer * denom; i > 1; i--)
{
if((numer % i) == 0 && (denom % i) == 0)
{
numer = numer / i;
denom = denom / i;
}
}
That seems to be the most efficient way. You are finding the greatest common factor. Now what you need to do is make sure you break the for loop. Once you have found the greatest common factor you don't need to keep looking for more common factors. Stick a break; after the two numer and denom statements and that should increase the efficiency in the long run.
Why are you starting a numer*denom and going down? % will never equal 0 unless the second argument is <= the first, which will not happen for quite some time. Just start at the smallest of the number or denominator.
On the other hand, you seem to be trying to implement gcd; go look at Wikipedia for a better implementation.
it works with this one, but the only thing is when i enter a negative integer for one of them then it automatically does not reduce because the gcd is a negative number. And it does take forever for it to run my program completely when I am printing out my array of fractions. That is why I need to know how to rewrite it so it is better and negatives will still make it reduce as well. But i should start at say the denominator maybe since it will always be positive?
Take a look at the program I modified based off of your premise.
Notice the clock, run it with a few different sized values for your numerator and denominator. You will notice that as your values get larger, so does the time to compute the reduced value for each.
Yes, what I asked you to try was editing the size of the numerator and denominator, and checking the difference in time.
If you had done it you would have found that the time it takes for the reduce() function to run increases as the size of your numerator and denominator. This is because of the efficiency of the function. The efficiency of your function reduce is O(n).
SO the answer to your first question is Yes, it will take longer to run the larger the numbers are.