Untitled

mail@pastecode.io avatar
unknown
plain_text
6 months ago
2.9 kB
3
Indexable
Never
public class Fraction {
   int numerator;
   int denominator;

    public Fraction(int numerator, int denominator) {
        if (denominator == 0) {
            throw new IllegalArgumentException("Denominator cannot be zero");
        }
        this.numerator = numerator;
        this.denominator = denominator;
      
    }

    public int getNumerator() {
        return numerator;
    }

    public int getDenominator() {
        return denominator;
    }

    public void setNumerator(int numerator) {
        this.numerator = numerator;
     
    }

    public void setDenominator(int denominator) {
        if (denominator == 0) {
            throw new IllegalArgumentException("Denominator cannot be zero");
        }
        this.denominator = denominator;
 
    }

    private void simplify() {
        int gcd = gcd(numerator, denominator);
        numerator /= gcd;
        denominator /= gcd;
    }

    private int gcd(int a, int b) {
        if (b == 0) {
            return a;
        }
        return gcd(b, a % b);
    }

    public void add(Fraction fraction) {
        int newNumerator = numerator * fraction.denominator + fraction.numerator * denominator;
        int newDenominator = denominator * fraction.denominator;
        numerator = newNumerator;
        denominator = newDenominator;
 
    }

    public void subtract(Fraction fraction) {
        int newNumerator = numerator * fraction.denominator - fraction.numerator * denominator;
        int newDenominator = denominator * fraction.denominator;
        numerator = newNumerator;
        denominator = newDenominator;
       
    }

    public void multiply(Fraction fraction) {
        numerator *= fraction.numerator;
        denominator *= fraction.denominator;

    }

    public void divide(Fraction fraction) {
        if (fraction.numerator == 0) {
            throw new IllegalArgumentException("Cannot divide by zero");
        }
        numerator *= fraction.denominator;
        denominator *= fraction.numerator;
        simplify();
    }


    public String toString() {
        return numerator + " / " + denominator;
    }

    public static void main(String[] args) {
        Fraction fraction1 = new Fraction(4, 5);
        Fraction fraction2 = new Fraction(3, 5);

        System.out.println("Fraction 1: " + fraction1);
        System.out.println("Fraction 2: " + fraction2);

        fraction1.add(fraction2);
        System.out.println("After addition: " + fraction1);

        Fraction fraction3 = new Fraction(1, 2);
        Fraction fraction4 = new Fraction(3, 4);

        System.out.println("Fraction 3: " + fraction3);
        System.out.println("Fraction 4: " + fraction4);

        fraction3.multiply(fraction4);
        System.out.println("After multiplication: " + fraction3);
    }
}