Formula for obtaining GCF

Recently I had this nack to make a program that does fraction operations like adding, subtracting, etc. But I can't seem to figure out how to reduce a fraction into it's simplest form. What codes should I use to reduce the fractions into simplest form?
you can probably use modulo to detect the GCF you'd most likely have to convert it to a string for output or it would show up as decimal. Maybe something like.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
     float firstFraction      =  1/2;  // arbitrary value assign a fraction you want.
     float secondFraction = 3/16 ;// assign another fraction.

     // convert decimal to whole number to get numerator of result
     int numerator     = (firstFraction + secondFraction) * 100;
     int denominator = 100;
         
    // start from value of numerator and move down to 1.
    // starting from the highest possible divisor would be faster to get to
    // the Greatest Common Factor
     for(int divisor = numerator; divisor > 0; divisor--)
     {
           // found the GCF
          if(numerator % divisor == 0 && denominator % divisor == 0)
          {
               // simplify numerator and denominator
               numerator /= divisor;
               denominator /= divisor;
               break;
           }  
     }

     cout << numerator << "/" << denominator;


something like that probably. It would be better if you make a class for it though. Then overload the arithmetic operators.
Last edited on
Google "GCD" and look at the Wikipedia page. It contains a very simple GCD algorithm which is much faster than the above (but not the fastest).
Topic archived. No new replies allowed.