Simplifying Fractions With java

user759630 picture user759630 · Jul 30, 2011 · Viewed 15.8k times · Source

Hey guys I am working on a SW here I am kinda in need of help, you see we need to make a method where we are gonna simplify fractions. any idea how? here's my code as of now (don't mind the dvalue Method it is already finsih all I need is the simplify method)

public class Fraction {

    public int num;
    public int den;
    public double dValue;

    public void display()
    {
        System.out.println("Numerator: "+num);
        System.out.println("Denominator: "+den);
    }

    public double dValue()
    {
        dValue = (double)num/den;
        return dValue;
    }


}

public class FractionTest {

        public static void main(String args[])
        {
            Fraction f = new Fraction();
            f.num = 50;
            f.den = 100;
            f.display();

            double d = f.dValue();
            System.out.println(d);
        }   
}

Answer

Roman Pietrzak picture Roman Pietrzak · Jul 30, 2011

Simplifying fractions is easy if you can folow the steps:

  1. find gcd of both num and den, so you have gcd=GCDFind(gcd, num);
  2. now, if gcd==1, then the fraction cannot be simplified (it is already in simplified form).
  3. if gcd > 1, then newNum = num/gcd; and newDen = den/gcd;

It's all you need I think.

The gcd stands for Greates Common Divisor... Code easily findable, and I just googled JavaScript implentation working this way in few seconds: http://www.calculla.com/en/fraction