From c0e959a486b0fbda6d502e8787868f512f0d2289 Mon Sep 17 00:00:00 2001 From: HadiSharifi Date: Mon, 27 Apr 2026 17:34:26 +0330 Subject: [PATCH] implement all methods in Rational file --- src/main/java/Rational/Rational.java | 41 +++++++++++----------------- 1 file changed, 16 insertions(+), 25 deletions(-) diff --git a/src/main/java/Rational/Rational.java b/src/main/java/Rational/Rational.java index 7bd840e..b9fd677 100644 --- a/src/main/java/Rational/Rational.java +++ b/src/main/java/Rational/Rational.java @@ -51,48 +51,39 @@ public class Rational { return r1.add(r2); } - // TODO: Instance method - this - other - // Formula: a/b - c/d = (a*d - c*b) / (b*d) public Rational subtract(Rational other) { - // YOUR CODE HERE - return null; // Remove this line when implemented + int newNumerator = this.numerator * other.denominator - other.numerator * this.denominator; + int newDenominator = this.denominator * other.denominator; + return new Rational(newNumerator, newDenominator); } - // TODO: Static method - r1 - r2 public static Rational subtract(Rational r1, Rational r2) { - // YOUR CODE HERE - return null; // Remove this line when implemented + return r1.subtract(r2); } - // TODO: Instance method - this * other - // Formula: (a/b) * (c/d) = (a*c) / (b*d) public Rational multiply(Rational other) { - // YOUR CODE HERE - return null; // Remove this line when implemented + int newNumerator = this.numerator * other.numerator; + int newDenominator = this.denominator * other.denominator; + return new Rational(newNumerator, newDenominator); } - // TODO: Static method - r1 * r2 public static Rational multiply(Rational r1, Rational r2) { - // YOUR CODE HERE - return null; // Remove this line when implemented + return r1.multiply(r2); } - // TODO: Instance method - this / other - // Formula: (a/b) รท (c/d) = (a*d) / (b*c) public Rational divide(Rational other) { - // YOUR CODE HERE - // HINT: Division is multiplication by reciprocal - // Don't forget to check if other.numerator is zero! - return null; // Remove this line when implemented + if (other.denominator == 0) { + throw new IllegalArgumentException("Denominator cannot be zero"); + } + int newNumerator = this.numerator * other.denominator; + int newDenominator = this.denominator * other.numerator; + return new Rational(newNumerator, newDenominator); } - // TODO: Static method - r1 / r2 public static Rational divide(Rational r1, Rational r2) { - // YOUR CODE HERE - return null; // Remove this line when implemented + return r1.divide(r2); } - // PROVIDED - String representation @Override public String toString() { if (denominator == 1) { @@ -101,7 +92,7 @@ public class Rational { return numerator + "/" + denominator; } - // PROVIDED - Decimal value + public double toDouble() { return (double) numerator / denominator; }