# Untitled

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);
}

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);