From 301a7f19555df102485be6486af66b7aed92a60d Mon Sep 17 00:00:00 2001 From: TAEHEON KIM <104629952+KTH1007@users.noreply.github.com> Date: Sun, 6 Dec 2026 01:49:08 +0900 Subject: [PATCH] fix: reduce ADTFraction to canonical form and avoid int overflow on arithmetic The compact constructor only rejected a zero denominator, so mathematically equal fractions were unequal objects (1/2 and 2/4), a negative denominator printed as "1/-2", and plus() and times() multiplied the parts as ints without cancelling, which overflowed even when the reduced result was small. Divide both parts by their greatest common divisor and keep the sign in the numerator, so the denominator is always positive. Build sums from the least common multiple and products with cross cancellation in long, and raise an ArithmeticException only when the reduced result really does not fit into an int. Integer.MIN_VALUE parts are handled as long values, which keeps the sign change and the absolute value out of the int range. Add tests for reduction, sign normalization, equals/hashCode, the Integer.MIN_VALUE corner cases and for sums and products that overflow when the parts are multiplied without reduction. Signed-off-by: TAEHEON KIM <104629952+KTH1007@users.noreply.github.com> --- .../com/thealgorithms/maths/ADTFraction.java | 116 ++++++++++++- .../thealgorithms/maths/ADTFractionTest.java | 160 ++++++++++++++++++ 2 files changed, 269 insertions(+), 7 deletions(-) diff --git a/src/main/java/com/thealgorithms/maths/ADTFraction.java b/src/main/java/com/thealgorithms/maths/ADTFraction.java index a85ef09079c9..5dc6dd199296 100644 --- a/src/main/java/com/thealgorithms/maths/ADTFraction.java +++ b/src/main/java/com/thealgorithms/maths/ADTFraction.java @@ -5,25 +5,47 @@ public record ADTFraction(int numerator, int denominator) { * Initializes a newly created {@code ADTFraction} object so that it represents * a fraction with the {@code numerator} and {@code denominator} provided as arguments. * + *

The fraction is stored in its canonical form so that mathematically equal fractions are + * also equal objects: both parts are divided by their greatest common divisor and the sign is + * kept in the numerator, which makes the denominator positive. For example, {@code 2/-4} is + * stored as {@code -1/2}. + * * @param numerator The fraction numerator * @param denominator The fraction denominator + * @throws IllegalArgumentException if {@code denominator} is 0 + * @throws ArithmeticException if the canonical form of the fraction does not fit into an + * {@code int}, which happens for {@code Integer.MIN_VALUE} + * denominators that cannot be reduced */ public ADTFraction { if (denominator == 0) { throw new IllegalArgumentException("Denominator cannot be 0"); } + CanonicalForm form = canonicalForm(numerator, denominator); + numerator = (int) form.numerator(); + denominator = (int) form.denominator(); } /** * Add two fractions. * + *

The denominators are replaced by their least common multiple before the numerators are + * added, so the intermediate values stay small and a sum that has a small canonical form is not + * lost to {@code int} overflow on the way. + * * @param fraction the {@code ADTFraction} to add * @return A new {@code ADTFraction} containing the result of the operation + * @throws ArithmeticException if the canonical form of the sum does not fit into an {@code int} */ public ADTFraction plus(ADTFraction fraction) { - var numerator = this.denominator * fraction.numerator + this.numerator * fraction.denominator; - var denominator = this.denominator * fraction.denominator; - return new ADTFraction(numerator, denominator); + long thisDenominator = denominator; + long otherDenominator = fraction.denominator; + long divisor = gcd(thisDenominator, otherDenominator); + long thisMultiplier = otherDenominator / divisor; + long otherMultiplier = thisDenominator / divisor; + long sumNumerator = this.numerator * thisMultiplier + fraction.numerator * otherMultiplier; + long commonDenominator = thisDenominator * thisMultiplier; + return of(sumNumerator, commonDenominator); } /** @@ -39,22 +61,36 @@ public ADTFraction times(int number) { /** * Multiply two fractions. * + *

Each numerator is cancelled against the opposite denominator before the multiplication, so + * the factors that would only be reduced away again never reach the product. + * * @param fraction the {@code ADTFraction} to multiply * @return A new {@code ADTFraction} containing the result of the operation + * @throws ArithmeticException if the canonical form of the product does not fit into an + * {@code int} */ public ADTFraction times(ADTFraction fraction) { - var numerator = this.numerator * fraction.numerator; - var denominator = this.denominator * fraction.denominator; - return new ADTFraction(numerator, denominator); + long thisNumerator = numerator; + long otherNumerator = fraction.numerator; + long thisDenominator = denominator; + long otherDenominator = fraction.denominator; + long numeratorDivisor = gcd(Math.abs(thisNumerator), otherDenominator); + long denominatorDivisor = gcd(Math.abs(otherNumerator), thisDenominator); + long productNumerator = thisNumerator / numeratorDivisor * (otherNumerator / denominatorDivisor); + long productDenominator = thisDenominator / denominatorDivisor * (otherDenominator / numeratorDivisor); + return of(productNumerator, productDenominator); } /** * Generates the reciprocal of the fraction. * * @return A new {@code ADTFraction} with the {@code numerator} and {@code denominator} switched + * @throws IllegalArgumentException if this fraction is 0 + * @throws ArithmeticException if the canonical form of the reciprocal does not fit into an + * {@code int} */ public ADTFraction reciprocal() { - return new ADTFraction(this.denominator, this.numerator); + return of(denominator, numerator); } /** @@ -77,4 +113,70 @@ public float value() { public String toString() { return String.format("%d/%d", this.numerator, this.denominator); } + + /** + * Reduces a fraction to its canonical form and checks that it still fits into an {@code int}. + * + *

The parts are handled as {@code long} values because neither the absolute value nor the + * sign change of {@link Integer#MIN_VALUE} is representable as an {@code int}. + * + * @param numerator the numerator to reduce + * @param denominator the denominator to reduce, which must not be 0 + * @return the reduced fraction with a positive denominator + * @throws ArithmeticException if the reduced parts do not fit into an {@code int} + */ + private static CanonicalForm canonicalForm(long numerator, long denominator) { + long divisor = gcd(Math.abs(numerator), Math.abs(denominator)); + long reducedNumerator = numerator / divisor; + long reducedDenominator = denominator / divisor; + if (reducedDenominator < 0) { + reducedNumerator = -reducedNumerator; + reducedDenominator = -reducedDenominator; + } + if (reducedNumerator < Integer.MIN_VALUE || reducedNumerator > Integer.MAX_VALUE || reducedDenominator > Integer.MAX_VALUE) { + throw new ArithmeticException(String.format("The fraction %d/%d does not fit into an int", reducedNumerator, reducedDenominator)); + } + return new CanonicalForm(reducedNumerator, reducedDenominator); + } + + /** + * Creates a fraction from parts that may exceed the {@code int} range. + * + * @param numerator the numerator of the new fraction + * @param denominator the denominator of the new fraction, which must not be 0 + * @return the fraction in its canonical form + * @throws ArithmeticException if the canonical form does not fit into an {@code int} + */ + private static ADTFraction of(long numerator, long denominator) { + CanonicalForm form = canonicalForm(numerator, denominator); + return new ADTFraction((int) form.numerator(), (int) form.denominator()); + } + + /** + * Calculates the greatest common divisor of two non negative numbers. + * + * @param first a non negative number + * @param second a non negative number + * @return the greatest common divisor of both arguments, or 0 only if both are 0 + */ + private static long gcd(long first, long second) { + long left = first; + long right = second; + while (right != 0) { + long remainder = left % right; + left = right; + right = remainder; + } + return left; + } + + /** + * A reduced fraction with a positive denominator whose parts may still be wider than an + * {@code int}. + * + * @param numerator the reduced numerator + * @param denominator the reduced denominator, which is positive + */ + private record CanonicalForm(long numerator, long denominator) { + } } diff --git a/src/test/java/com/thealgorithms/maths/ADTFractionTest.java b/src/test/java/com/thealgorithms/maths/ADTFractionTest.java index 938c7d558841..a49a2b6583a2 100644 --- a/src/test/java/com/thealgorithms/maths/ADTFractionTest.java +++ b/src/test/java/com/thealgorithms/maths/ADTFractionTest.java @@ -1,6 +1,7 @@ package com.thealgorithms.maths; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -17,27 +18,186 @@ void testConstructorWithDenominatorEqualToZero() { assertEquals("Denominator cannot be 0", exception.getMessage()); } + @Test + void testConstructorReducesFractionToLowestTerms() { + ADTFraction fraction = new ADTFraction(6, 8); + assertEquals(3, fraction.numerator()); + assertEquals(4, fraction.denominator()); + assertEquals("3/4", fraction.toString()); + } + + @Test + void testConstructorReducesFractionWithLargeCommonDivisor() { + assertEquals(new ADTFraction(1, 1), new ADTFraction(Integer.MAX_VALUE, Integer.MAX_VALUE)); + assertEquals(new ADTFraction(1, 3), new ADTFraction(715827882, 2147483646)); + } + + @Test + void testConstructorNormalizesZeroNumerator() { + ADTFraction fraction = new ADTFraction(0, -5); + assertEquals(0, fraction.numerator()); + assertEquals(1, fraction.denominator()); + assertEquals("0/1", fraction.toString()); + } + + @Test + void testConstructorMovesSignToNumerator() { + ADTFraction fraction = new ADTFraction(1, -2); + assertEquals(-1, fraction.numerator()); + assertEquals(2, fraction.denominator()); + assertEquals("-1/2", fraction.toString()); + } + + @Test + void testConstructorNormalizesTwoNegatives() { + assertEquals(new ADTFraction(1, 2), new ADTFraction(-1, -2)); + assertEquals("1/2", new ADTFraction(-2, -4).toString()); + } + + @Test + void testEquivalentFractionsAreEqual() { + assertEquals(new ADTFraction(1, 2), new ADTFraction(2, 4)); + assertEquals(new ADTFraction(1, 2).hashCode(), new ADTFraction(2, 4).hashCode()); + assertEquals(new ADTFraction(-1, 2), new ADTFraction(1, -2)); + assertEquals(new ADTFraction(-1, 2).hashCode(), new ADTFraction(1, -2).hashCode()); + assertNotEquals(new ADTFraction(1, 2), new ADTFraction(1, 3)); + } + + @Test + void testFractionEquivalenceAndSignNormalizationFromIssue() { + ADTFraction half = new ADTFraction(1, 2); + ADTFraction twoQuarters = new ADTFraction(2, 4); + assertEquals(half, twoQuarters, "Equivalent fractions should be equal"); + + ADTFraction neg1 = new ADTFraction(-1, 2); + ADTFraction neg2 = new ADTFraction(1, -2); + assertEquals(neg1, neg2, "Fractions with negative signs in numerator or denominator should be equal"); + } + + @Test + void testConstructorHandlesIntegerMinValueDenominatorWhenReducible() { + ADTFraction fraction = new ADTFraction(2, Integer.MIN_VALUE); + assertEquals(-1, fraction.numerator()); + assertEquals(1 << 30, fraction.denominator()); + } + + @Test + void testConstructorHandlesIntegerMinValueNumeratorWhenReducible() { + ADTFraction fraction = new ADTFraction(Integer.MIN_VALUE, 2); + assertEquals(Integer.MIN_VALUE / 2, fraction.numerator()); + assertEquals(1, fraction.denominator()); + } + + @Test + void testConstructorRejectsCanonicalFormOutsideIntegerRange() { + assertThrows(ArithmeticException.class, () -> new ADTFraction(1, Integer.MIN_VALUE)); + assertThrows(ArithmeticException.class, () -> new ADTFraction(Integer.MIN_VALUE, -3)); + } + @Test public void testPlus() { assertEquals(new ADTFraction(59, 40), fraction1.plus(fraction2)); } + @Test + void testPlusReducesResult() { + assertEquals(new ADTFraction(1, 1), new ADTFraction(1, 2).plus(new ADTFraction(1, 2))); + assertEquals(new ADTFraction(1, 1), new ADTFraction(1, 3).plus(new ADTFraction(2, 3))); + assertEquals(new ADTFraction(5, 12), new ADTFraction(1, 6).plus(new ADTFraction(1, 4))); + assertEquals(new ADTFraction(-1, 2), new ADTFraction(1, 2).plus(new ADTFraction(-1, 1))); + } + + @Test + void testPlusWithZero() { + assertEquals(fraction1, fraction1.plus(new ADTFraction(0, 7))); + assertEquals(fraction1, new ADTFraction(0, 7).plus(fraction1)); + } + + @Test + void testPlusDoesNotOverflowForReducibleDenominators() { + ADTFraction tenthOfThousandth = new ADTFraction(1, 100000); + assertEquals(new ADTFraction(1, 50000), tenthOfThousandth.plus(tenthOfThousandth)); + } + + @Test + void testPlusWithOppositeFractionsGivesZero() { + assertEquals(new ADTFraction(0, 1), new ADTFraction(Integer.MAX_VALUE, 3).plus(new ADTFraction(-Integer.MAX_VALUE, 3))); + } + + @Test + void testPlusThrowsWhenResultDoesNotFitIntoInteger() { + ADTFraction largest = new ADTFraction(Integer.MAX_VALUE, 1); + assertThrows(ArithmeticException.class, () -> largest.plus(largest)); + } + @Test public void testTimes() { assertEquals(new ADTFraction(12, 5), fraction1.times(4)); assertEquals(new ADTFraction(21, 40), fraction1.times(fraction2)); } + @Test + void testTimesReducesResult() { + assertEquals(new ADTFraction(1, 2), new ADTFraction(2, 3).times(new ADTFraction(3, 4))); + assertEquals(new ADTFraction(1, 2), new ADTFraction(-2, 3).times(new ADTFraction(-3, 4))); + assertEquals(new ADTFraction(-1, 2), new ADTFraction(-2, 3).times(new ADTFraction(3, 4))); + assertEquals(new ADTFraction(-6, 5), new ADTFraction(-3, 5).times(2)); + } + + @Test + void testTimesByZero() { + assertEquals(new ADTFraction(0, 1), fraction1.times(0)); + assertEquals(new ADTFraction(0, 1), new ADTFraction(0, 7).times(fraction1)); + assertEquals(new ADTFraction(0, 1), fraction1.times(new ADTFraction(0, 7))); + } + + @Test + void testTimesDoesNotOverflowWhenFactorsCancel() { + assertEquals(new ADTFraction(1, 1), new ADTFraction(Integer.MAX_VALUE, 3).times(new ADTFraction(3, Integer.MAX_VALUE))); + assertEquals(new ADTFraction(1, 1), new ADTFraction(46368, 75025).times(new ADTFraction(75025, 46368))); + } + + @Test + void testTimesThrowsWhenResultDoesNotFitIntoInteger() { + assertThrows(ArithmeticException.class, () -> new ADTFraction(Integer.MAX_VALUE, 1).times(2)); + } + + @Test + void testRepeatedAdditionStaysExact() { + ADTFraction sum = new ADTFraction(0, 1); + for (int i = 0; i < 1000; i++) { + sum = sum.plus(new ADTFraction(1, 1000)); + } + assertEquals(new ADTFraction(1, 1), sum); + } + @Test public void testReciprocal() { assertEquals(new ADTFraction(5, 3), fraction1.reciprocal()); } + @Test + void testReciprocalOfNegativeFraction() { + assertEquals(new ADTFraction(-5, 3), new ADTFraction(3, -5).reciprocal()); + } + + @Test + void testReciprocalOfZeroThrows() { + ADTFraction zero = new ADTFraction(0, 1); + Exception exception = assertThrows(IllegalArgumentException.class, zero::reciprocal); + assertEquals("Denominator cannot be 0", exception.getMessage()); + } + @Test public void testValue() { assertEquals(0.6F, fraction1.value()); } + @Test + void testValueOfNegativeFraction() { + assertEquals(-0.5F, new ADTFraction(1, -2).value()); + } + @Test public void testEqualsAndHashCode() { ADTFraction fraction3 = new ADTFraction(3, 5);