// Adaptado de http://aleph0.clarku.edu/~djoyce/cs101/Resources/Fraction.java
public class Fraction {
    private int numerator;
    private int denominator;
    Fraction(int num, int den) {
        numerator = num;
        denominator = den;
    }
    public int getNumerator() {
        return numerator;
    }
    public int getDenominator() {
        return denominator;
    }
    public void setNumerator(int num) {
        numerator = num;
    }
    public void setDenominator(int den) {
        denominator = den;
    }
    // Les funcions que no es criden des de fora la clase son private
    // Aquestes son static perque no utilizen Fraction
    // Preconditions: denom1 and denom2 must be non-zero integer values
    private static int mcm(int a, int b) { // Minim Comu Multiple
        return a * b / mcd(a, b);
    }
    private static int mcd(int a, int b) { // Maxim Comu Divisor
        int aux;
        while (b != 0) {
            aux = b;
            b = a % b;
            a = aux;
        }
        return a;
    }
    // I aquestes dos no poden ser static (denominator i numerator d'un this)
    private Fraction reduce() {
        int common;
        // get absolute values for numerator and denominator
        int num = Math.abs(numerator);
        int den = Math.abs(denominator);
        common = mcd(num, den);
        return new Fraction(numerator / common, denominator / common);
    }
    private Fraction convert(int common) {
        int factor = common / denominator;
        return new Fraction(numerator * factor, common);
    }
    public Fraction add(Fraction b) {
        int common = mcm(denominator, b.denominator);
        // convert fractions to MCD
        Fraction commonA = this.convert(common);
        Fraction commonB = b.convert(common);
        Fraction sum = new Fraction(commonA.numerator + commonB.numerator, common);
        // reduce the resulting fraction
        return sum.reduce();
    }
    public Fraction substract(Fraction b) {
        int common = mcm(denominator, b.denominator);
        // convertir fractions to MCD
        Fraction commonA = convert(common); // "this." implicit
        Fraction commonB = b.convert(common);
        Fraction diff = new Fraction(commonA.numerator - commonB.numerator, common);
        return diff.reduce();
    }
    public Fraction multiply(Fraction b) {
        Fraction product = new Fraction(numerator * b.numerator,
                denominator * b.denominator);
        return product.reduce();
    }
    public Fraction divide(Fraction b) {
        Fraction result = new Fraction(numerator * b.denominator,
                denominator * b.numerator);
        return result.reduce();
    }
    @Override
    public String toString() {
        return numerator + "/" + denominator;
    }
}
