1

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);
        }   
}
Juha Syrjälä
  • 33,425
  • 31
  • 131
  • 183
user759630
  • 679
  • 2
  • 8
  • 11

2 Answers2

7

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

Roman Pietrzak
  • 635
  • 3
  • 15
  • I aleady know that, what's the algorithm for the gcd? since I want to get the numerator and denominator on it's lowest form – user759630 Jul 30 '11 at 15:26
0

You could have a look at these links, they can be helpful

  1. http://www.daniweb.com/software-development/java/threads/13663
  2. http://www.dreamincode.net/forums/topic/64342-reducing-a-fraction/
  3. simplifying fractions in Java

and many more..

Community
  • 1
  • 1
DaMainBoss
  • 2,035
  • 1
  • 19
  • 26