95 lines
2.7 KiB
Java
95 lines
2.7 KiB
Java
package Rational;
|
|
|
|
public class Rational {
|
|
private int numerator;
|
|
private int denominator;
|
|
|
|
public Rational(int numerator, int denominator) {
|
|
if (denominator == 0) {
|
|
throw new IllegalArgumentException("Denominator cannot be zero");
|
|
}
|
|
this.numerator = numerator;
|
|
this.denominator = denominator;
|
|
simplify();
|
|
}
|
|
|
|
private int gcd(int a, int b) {
|
|
a = Math.abs(a);
|
|
b = Math.abs(b);
|
|
while (b != 0) {
|
|
int temp = b;
|
|
b = a % b;
|
|
a = temp;
|
|
}
|
|
return a;
|
|
}
|
|
|
|
private void simplify() {
|
|
int gcd = gcd(numerator, denominator);
|
|
numerator /= gcd;
|
|
denominator /= gcd;
|
|
if (denominator < 0) {
|
|
numerator = -numerator;
|
|
denominator = -denominator;
|
|
}
|
|
}
|
|
|
|
public Rational add(Rational other) {
|
|
int newNumerator = this.numerator * other.denominator + other.numerator * this.denominator;
|
|
int newDenominator = this.denominator * other.denominator;
|
|
return new Rational(newNumerator, newDenominator);
|
|
}
|
|
|
|
public static Rational add(Rational r1, Rational r2) {
|
|
return r1.add(r2);
|
|
}
|
|
|
|
// a/b - c/d = (a*d - c*b) / (b*d)
|
|
public Rational subtract(Rational other) {
|
|
int newNumerator = this.numerator * other.denominator - other.numerator * this.denominator;
|
|
int newDenominator = this.denominator * other.denominator;
|
|
return new Rational(newNumerator, newDenominator);
|
|
}
|
|
|
|
public static Rational subtract(Rational r1, Rational r2) {
|
|
return r1.subtract(r2);
|
|
}
|
|
|
|
// (a/b) * (c/d) = (a*c) / (b*d)
|
|
public Rational multiply(Rational other) {
|
|
int newNumerator = this.numerator * other.numerator;
|
|
int newDenominator = this.denominator * other.denominator;
|
|
return new Rational(newNumerator, newDenominator);
|
|
}
|
|
|
|
public static Rational multiply(Rational r1, Rational r2) {
|
|
return r1.multiply(r2);
|
|
}
|
|
|
|
// (a/b) ÷ (c/d) = (a*d) / (b*c)
|
|
public Rational divide(Rational other) {
|
|
if (other.numerator == 0) {
|
|
throw new IllegalArgumentException("Cannot divide by zero");
|
|
}
|
|
int newNumerator = this.numerator * other.denominator;
|
|
int newDenominator = this.denominator * other.numerator;
|
|
return new Rational(newNumerator, newDenominator);
|
|
}
|
|
|
|
public static Rational divide(Rational r1, Rational r2) {
|
|
return r1.divide(r2);
|
|
}
|
|
|
|
@Override
|
|
public String toString() {
|
|
if (denominator == 1) {
|
|
return numerator + "";
|
|
}
|
|
return numerator + "/" + denominator;
|
|
}
|
|
|
|
public double toDouble() {
|
|
return (double) numerator / denominator;
|
|
}
|
|
}
|