Simplifying a fraction

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • plasmastar
    New Member
    • Mar 2010
    • 9

    Simplifying a fraction

    I have to write a program in which I have two fractions. Each fraction has two variables, numerator and denominator. I have to add, subtract, multiply and divide with these fractions, and in the end the fraction has to be simplified. Can anyone here tell me what algorithm I can use to simplify these fractions? An example is if I have 5/10, in the end I need to show 1/2. I've thought of everything but I can't find a way. Thanks to those who help.
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    The easiest way to do this is to use the modulus operator.

    Let's say you've got 6/8. So you start with the smaller of 6 or 8 and then use the modulous operator:

    6%2

    this evaluates to 0 meaning the 6 is evenly divisible by 2. Now check 8 %2. This is also 0 meaning that 8 is evenly divisible by 2. Therefore, create a new fraction (6/2) / (8/2) or 3/4.

    Then proceed to reduce 3/4 by trying 3%2 (which is 1 so 3 is not divisble by 2) so your fraction is now simplified.

    Try 6/9:

    6%2 is 0 so try 9%2 which is 1. Therefore, 2 is not a factor.
    Next try:
    6%3 is 0 so try 9%3 which is also 0 so 3 is a common factor. Therefore, create a new fraction (6/3) / (9/3) or 2/3.

    Just remember that your common factors are between 2 and value of the smaller number minus 1. That means 6 has to be tried using 2 through 5 with the modulus operator.

    Comment

    • whodgson
      Contributor
      • Jan 2007
      • 542

      #3
      From the above you could write your own function which finds the greatest common divisor of the two numbers making up the numerator and denominator
      {
      if(m<n)swap(m,n ); // make n the smallest of the two
      while(n>0)
      ( long r =m%n;
      m=n;
      n=r;}
      return m; //m is the g.c.d.
      }

      Comment

      Working...