Here are two classes named Fraction.java and Util.java. As an example you can create the fractional number 7/8 using the constructor Fraction("8", "7"). There are many other constructors too in the Fraction class. If you want to get 10 as a fractional number, i.e. 10/1, you can use the contructor new Fraction("10").

In order to add two fractional numbers a and b, you can use Util.add(a, b) method. Likewise you can to subtraction, multiplication and division. Please refer the code, it might be useful to understand the usage.

Fraction.java

public class Fraction { private Long denominator; private Long numerator; /** Creates a new instance of Fraction */ public Fraction(String denominator, String numerator) { this(new Long(denominator), new Long(numerator)); } public Fraction(Long denominator, Long numerator) { long gcd = Util.gcd(denominator, numerator); this.denominator = denominator / gcd; this.numerator = numerator /gcd; } public Fraction(String number) { this.denominator = new Long("1"); this.numerator = new Long(number); } public Fraction(long number) { this.denominator = new Long("1"); this.numerator = new Long(number); } public Long getDenominator() { return denominator; } public Long getNumerator() { return numerator; } }Util.java

public class Util { /** Creates a new instance of Util */ public Util() { } public static long gcd(Long a, Long b) { if (b==0) return a; else return gcd(b, a % b); } public static long lcm(Long a, Long b) { return (a/gcd(a, b))*b; } // (a + b) public static Fraction add(Fraction a, Fraction b) { Long denominator = lcm(a.getDenominator(), b.getDenominator()); Long numerator = a.getNumerator()*(denominator/a.getDenominator()) + b.getNumerator()*(denominator/b.getDenominator()); return new Fraction(denominator, numerator); } // (a - b) public static Fraction substract(Fraction a, Fraction b) { Long denominator = lcm(a.getDenominator(), b.getDenominator()); Long numerator = a.getNumerator()*(denominator/a.getDenominator()) - b.getNumerator()*(denominator/b.getDenominator()); return new Fraction(denominator, numerator); } // (a * b) public static Fraction multiply(Fraction a, Fraction b) { return new Fraction(a.getDenominator() * b.getDenominator(), a.getNumerator() * b.getNumerator()); } // (a / b) public static Fraction divide(Fraction a, Fraction b) { return new Fraction(a.getDenominator() * b.getNumerator(), a.getNumerator() * b.getDenominator()); } }

## No comments:

## Post a Comment