# Simplifying fractions in c++

• 09-01-2002
Unregistered
Simplifying fractions in c++
Gday,
Just a quick question for anyone who knows.
How do u simplify fractions. For example. If the output is 40/ 160 how do i get the compiler to print out 1/4???
Thanx
• 09-01-2002
skipper
Since this smells of a homework problem, I'm going to put your mind back to work. :)

What common arithmetic operator can be used to determine if two values are multiples of one another? (Think zero remainder.)

Okay? Now, how could you create a loop to run through the possibilities until you've reduced both the numerator and denominator to their lowest values?

Hint: create a FOR loop that initializes the counter to the value of the numerator and decrement, testing each successive value as a potential common multiple of both the numerator and denominator. Note that you will want to stop your loop before you reach '0' i.e. x > 0, lest you blow up the program!

(The loop is trivial in that it requires only about five lines of code. I leave it to you to refine it to reduce execution time. That is, suppose your example were 40000/160000?)

Good luck!

-Skipper
• 09-01-2002
Crimpy
Quote:

How do u simplify fractions. For example. If the output is 40/ 160 how do i get the compiler to print out 1/4???
Wouldn't there be a quick way of perfoming a division and then converting the result to a fraction? Because 1/4 and 40/160 both result in 0.25.
• 09-01-2002
Nick
Just write a gcd algorithm and then divide the numerator
and denomerator by it.