Skip to content

Commit b595fda

Browse files
authored
fix: reduce ADTFraction to canonical form and avoid int overflow (#7801)
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>
1 parent 9918769 commit b595fda

2 files changed

Lines changed: 269 additions & 7 deletions

File tree

‎src/main/java/com/thealgorithms/maths/ADTFraction.java‎

Lines changed: 109 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -5,25 +5,47 @@ public record ADTFraction(int numerator, int denominator) {
55
* Initializes a newly created {@code ADTFraction} object so that it represents
66
* a fraction with the {@code numerator} and {@code denominator} provided as arguments.
77
*
8+
* <p>The fraction is stored in its canonical form so that mathematically equal fractions are
9+
* also equal objects: both parts are divided by their greatest common divisor and the sign is
10+
* kept in the numerator, which makes the denominator positive. For example, {@code 2/-4} is
11+
* stored as {@code -1/2}.
12+
*
813
* @param numerator The fraction numerator
914
* @param denominator The fraction denominator
15+
* @throws IllegalArgumentException if {@code denominator} is 0
16+
* @throws ArithmeticException if the canonical form of the fraction does not fit into an
17+
* {@code int}, which happens for {@code Integer.MIN_VALUE}
18+
* denominators that cannot be reduced
1019
*/
1120
public ADTFraction {
1221
if (denominator == 0) {
1322
throw new IllegalArgumentException("Denominator cannot be 0");
1423
}
24+
CanonicalForm form = canonicalForm(numerator, denominator);
25+
numerator = (int) form.numerator();
26+
denominator = (int) form.denominator();
1527
}
1628

1729
/**
1830
* Add two fractions.
1931
*
32+
* <p>The denominators are replaced by their least common multiple before the numerators are
33+
* added, so the intermediate values stay small and a sum that has a small canonical form is not
34+
* lost to {@code int} overflow on the way.
35+
*
2036
* @param fraction the {@code ADTFraction} to add
2137
* @return A new {@code ADTFraction} containing the result of the operation
38+
* @throws ArithmeticException if the canonical form of the sum does not fit into an {@code int}
2239
*/
2340
public ADTFraction plus(ADTFraction fraction) {
24-
var numerator = this.denominator * fraction.numerator + this.numerator * fraction.denominator;
25-
var denominator = this.denominator * fraction.denominator;
26-
return new ADTFraction(numerator, denominator);
41+
long thisDenominator = denominator;
42+
long otherDenominator = fraction.denominator;
43+
long divisor = gcd(thisDenominator, otherDenominator);
44+
long thisMultiplier = otherDenominator / divisor;
45+
long otherMultiplier = thisDenominator / divisor;
46+
long sumNumerator = this.numerator * thisMultiplier + fraction.numerator * otherMultiplier;
47+
long commonDenominator = thisDenominator * thisMultiplier;
48+
return of(sumNumerator, commonDenominator);
2749
}
2850

2951
/**
@@ -39,22 +61,36 @@ public ADTFraction times(int number) {
3961
/**
4062
* Multiply two fractions.
4163
*
64+
* <p>Each numerator is cancelled against the opposite denominator before the multiplication, so
65+
* the factors that would only be reduced away again never reach the product.
66+
*
4267
* @param fraction the {@code ADTFraction} to multiply
4368
* @return A new {@code ADTFraction} containing the result of the operation
69+
* @throws ArithmeticException if the canonical form of the product does not fit into an
70+
* {@code int}
4471
*/
4572
public ADTFraction times(ADTFraction fraction) {
46-
var numerator = this.numerator * fraction.numerator;
47-
var denominator = this.denominator * fraction.denominator;
48-
return new ADTFraction(numerator, denominator);
73+
long thisNumerator = numerator;
74+
long otherNumerator = fraction.numerator;
75+
long thisDenominator = denominator;
76+
long otherDenominator = fraction.denominator;
77+
long numeratorDivisor = gcd(Math.abs(thisNumerator), otherDenominator);
78+
long denominatorDivisor = gcd(Math.abs(otherNumerator), thisDenominator);
79+
long productNumerator = thisNumerator / numeratorDivisor * (otherNumerator / denominatorDivisor);
80+
long productDenominator = thisDenominator / denominatorDivisor * (otherDenominator / numeratorDivisor);
81+
return of(productNumerator, productDenominator);
4982
}
5083

5184
/**
5285
* Generates the reciprocal of the fraction.
5386
*
5487
* @return A new {@code ADTFraction} with the {@code numerator} and {@code denominator} switched
88+
* @throws IllegalArgumentException if this fraction is 0
89+
* @throws ArithmeticException if the canonical form of the reciprocal does not fit into an
90+
* {@code int}
5591
*/
5692
public ADTFraction reciprocal() {
57-
return new ADTFraction(this.denominator, this.numerator);
93+
return of(denominator, numerator);
5894
}
5995

6096
/**
@@ -77,4 +113,70 @@ public float value() {
77113
public String toString() {
78114
return String.format("%d/%d", this.numerator, this.denominator);
79115
}
116+
117+
/**
118+
* Reduces a fraction to its canonical form and checks that it still fits into an {@code int}.
119+
*
120+
* <p>The parts are handled as {@code long} values because neither the absolute value nor the
121+
* sign change of {@link Integer#MIN_VALUE} is representable as an {@code int}.
122+
*
123+
* @param numerator the numerator to reduce
124+
* @param denominator the denominator to reduce, which must not be 0
125+
* @return the reduced fraction with a positive denominator
126+
* @throws ArithmeticException if the reduced parts do not fit into an {@code int}
127+
*/
128+
private static CanonicalForm canonicalForm(long numerator, long denominator) {
129+
long divisor = gcd(Math.abs(numerator), Math.abs(denominator));
130+
long reducedNumerator = numerator / divisor;
131+
long reducedDenominator = denominator / divisor;
132+
if (reducedDenominator < 0) {
133+
reducedNumerator = -reducedNumerator;
134+
reducedDenominator = -reducedDenominator;
135+
}
136+
if (reducedNumerator < Integer.MIN_VALUE || reducedNumerator > Integer.MAX_VALUE || reducedDenominator > Integer.MAX_VALUE) {
137+
throw new ArithmeticException(String.format("The fraction %d/%d does not fit into an int", reducedNumerator, reducedDenominator));
138+
}
139+
return new CanonicalForm(reducedNumerator, reducedDenominator);
140+
}
141+
142+
/**
143+
* Creates a fraction from parts that may exceed the {@code int} range.
144+
*
145+
* @param numerator the numerator of the new fraction
146+
* @param denominator the denominator of the new fraction, which must not be 0
147+
* @return the fraction in its canonical form
148+
* @throws ArithmeticException if the canonical form does not fit into an {@code int}
149+
*/
150+
private static ADTFraction of(long numerator, long denominator) {
151+
CanonicalForm form = canonicalForm(numerator, denominator);
152+
return new ADTFraction((int) form.numerator(), (int) form.denominator());
153+
}
154+
155+
/**
156+
* Calculates the greatest common divisor of two non negative numbers.
157+
*
158+
* @param first a non negative number
159+
* @param second a non negative number
160+
* @return the greatest common divisor of both arguments, or 0 only if both are 0
161+
*/
162+
private static long gcd(long first, long second) {
163+
long left = first;
164+
long right = second;
165+
while (right != 0) {
166+
long remainder = left % right;
167+
left = right;
168+
right = remainder;
169+
}
170+
return left;
171+
}
172+
173+
/**
174+
* A reduced fraction with a positive denominator whose parts may still be wider than an
175+
* {@code int}.
176+
*
177+
* @param numerator the reduced numerator
178+
* @param denominator the reduced denominator, which is positive
179+
*/
180+
private record CanonicalForm(long numerator, long denominator) {
181+
}
80182
}

‎src/test/java/com/thealgorithms/maths/ADTFractionTest.java‎

Lines changed: 160 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package com.thealgorithms.maths;
22

33
import static org.junit.jupiter.api.Assertions.assertEquals;
4+
import static org.junit.jupiter.api.Assertions.assertNotEquals;
45
import static org.junit.jupiter.api.Assertions.assertThrows;
56
import static org.junit.jupiter.api.Assertions.assertTrue;
67

@@ -17,27 +18,186 @@ void testConstructorWithDenominatorEqualToZero() {
1718
assertEquals("Denominator cannot be 0", exception.getMessage());
1819
}
1920

21+
@Test
22+
void testConstructorReducesFractionToLowestTerms() {
23+
ADTFraction fraction = new ADTFraction(6, 8);
24+
assertEquals(3, fraction.numerator());
25+
assertEquals(4, fraction.denominator());
26+
assertEquals("3/4", fraction.toString());
27+
}
28+
29+
@Test
30+
void testConstructorReducesFractionWithLargeCommonDivisor() {
31+
assertEquals(new ADTFraction(1, 1), new ADTFraction(Integer.MAX_VALUE, Integer.MAX_VALUE));
32+
assertEquals(new ADTFraction(1, 3), new ADTFraction(715827882, 2147483646));
33+
}
34+
35+
@Test
36+
void testConstructorNormalizesZeroNumerator() {
37+
ADTFraction fraction = new ADTFraction(0, -5);
38+
assertEquals(0, fraction.numerator());
39+
assertEquals(1, fraction.denominator());
40+
assertEquals("0/1", fraction.toString());
41+
}
42+
43+
@Test
44+
void testConstructorMovesSignToNumerator() {
45+
ADTFraction fraction = new ADTFraction(1, -2);
46+
assertEquals(-1, fraction.numerator());
47+
assertEquals(2, fraction.denominator());
48+
assertEquals("-1/2", fraction.toString());
49+
}
50+
51+
@Test
52+
void testConstructorNormalizesTwoNegatives() {
53+
assertEquals(new ADTFraction(1, 2), new ADTFraction(-1, -2));
54+
assertEquals("1/2", new ADTFraction(-2, -4).toString());
55+
}
56+
57+
@Test
58+
void testEquivalentFractionsAreEqual() {
59+
assertEquals(new ADTFraction(1, 2), new ADTFraction(2, 4));
60+
assertEquals(new ADTFraction(1, 2).hashCode(), new ADTFraction(2, 4).hashCode());
61+
assertEquals(new ADTFraction(-1, 2), new ADTFraction(1, -2));
62+
assertEquals(new ADTFraction(-1, 2).hashCode(), new ADTFraction(1, -2).hashCode());
63+
assertNotEquals(new ADTFraction(1, 2), new ADTFraction(1, 3));
64+
}
65+
66+
@Test
67+
void testFractionEquivalenceAndSignNormalizationFromIssue() {
68+
ADTFraction half = new ADTFraction(1, 2);
69+
ADTFraction twoQuarters = new ADTFraction(2, 4);
70+
assertEquals(half, twoQuarters, "Equivalent fractions should be equal");
71+
72+
ADTFraction neg1 = new ADTFraction(-1, 2);
73+
ADTFraction neg2 = new ADTFraction(1, -2);
74+
assertEquals(neg1, neg2, "Fractions with negative signs in numerator or denominator should be equal");
75+
}
76+
77+
@Test
78+
void testConstructorHandlesIntegerMinValueDenominatorWhenReducible() {
79+
ADTFraction fraction = new ADTFraction(2, Integer.MIN_VALUE);
80+
assertEquals(-1, fraction.numerator());
81+
assertEquals(1 << 30, fraction.denominator());
82+
}
83+
84+
@Test
85+
void testConstructorHandlesIntegerMinValueNumeratorWhenReducible() {
86+
ADTFraction fraction = new ADTFraction(Integer.MIN_VALUE, 2);
87+
assertEquals(Integer.MIN_VALUE / 2, fraction.numerator());
88+
assertEquals(1, fraction.denominator());
89+
}
90+
91+
@Test
92+
void testConstructorRejectsCanonicalFormOutsideIntegerRange() {
93+
assertThrows(ArithmeticException.class, () -> new ADTFraction(1, Integer.MIN_VALUE));
94+
assertThrows(ArithmeticException.class, () -> new ADTFraction(Integer.MIN_VALUE, -3));
95+
}
96+
2097
@Test
2198
public void testPlus() {
2299
assertEquals(new ADTFraction(59, 40), fraction1.plus(fraction2));
23100
}
24101

102+
@Test
103+
void testPlusReducesResult() {
104+
assertEquals(new ADTFraction(1, 1), new ADTFraction(1, 2).plus(new ADTFraction(1, 2)));
105+
assertEquals(new ADTFraction(1, 1), new ADTFraction(1, 3).plus(new ADTFraction(2, 3)));
106+
assertEquals(new ADTFraction(5, 12), new ADTFraction(1, 6).plus(new ADTFraction(1, 4)));
107+
assertEquals(new ADTFraction(-1, 2), new ADTFraction(1, 2).plus(new ADTFraction(-1, 1)));
108+
}
109+
110+
@Test
111+
void testPlusWithZero() {
112+
assertEquals(fraction1, fraction1.plus(new ADTFraction(0, 7)));
113+
assertEquals(fraction1, new ADTFraction(0, 7).plus(fraction1));
114+
}
115+
116+
@Test
117+
void testPlusDoesNotOverflowForReducibleDenominators() {
118+
ADTFraction tenthOfThousandth = new ADTFraction(1, 100000);
119+
assertEquals(new ADTFraction(1, 50000), tenthOfThousandth.plus(tenthOfThousandth));
120+
}
121+
122+
@Test
123+
void testPlusWithOppositeFractionsGivesZero() {
124+
assertEquals(new ADTFraction(0, 1), new ADTFraction(Integer.MAX_VALUE, 3).plus(new ADTFraction(-Integer.MAX_VALUE, 3)));
125+
}
126+
127+
@Test
128+
void testPlusThrowsWhenResultDoesNotFitIntoInteger() {
129+
ADTFraction largest = new ADTFraction(Integer.MAX_VALUE, 1);
130+
assertThrows(ArithmeticException.class, () -> largest.plus(largest));
131+
}
132+
25133
@Test
26134
public void testTimes() {
27135
assertEquals(new ADTFraction(12, 5), fraction1.times(4));
28136
assertEquals(new ADTFraction(21, 40), fraction1.times(fraction2));
29137
}
30138

139+
@Test
140+
void testTimesReducesResult() {
141+
assertEquals(new ADTFraction(1, 2), new ADTFraction(2, 3).times(new ADTFraction(3, 4)));
142+
assertEquals(new ADTFraction(1, 2), new ADTFraction(-2, 3).times(new ADTFraction(-3, 4)));
143+
assertEquals(new ADTFraction(-1, 2), new ADTFraction(-2, 3).times(new ADTFraction(3, 4)));
144+
assertEquals(new ADTFraction(-6, 5), new ADTFraction(-3, 5).times(2));
145+
}
146+
147+
@Test
148+
void testTimesByZero() {
149+
assertEquals(new ADTFraction(0, 1), fraction1.times(0));
150+
assertEquals(new ADTFraction(0, 1), new ADTFraction(0, 7).times(fraction1));
151+
assertEquals(new ADTFraction(0, 1), fraction1.times(new ADTFraction(0, 7)));
152+
}
153+
154+
@Test
155+
void testTimesDoesNotOverflowWhenFactorsCancel() {
156+
assertEquals(new ADTFraction(1, 1), new ADTFraction(Integer.MAX_VALUE, 3).times(new ADTFraction(3, Integer.MAX_VALUE)));
157+
assertEquals(new ADTFraction(1, 1), new ADTFraction(46368, 75025).times(new ADTFraction(75025, 46368)));
158+
}
159+
160+
@Test
161+
void testTimesThrowsWhenResultDoesNotFitIntoInteger() {
162+
assertThrows(ArithmeticException.class, () -> new ADTFraction(Integer.MAX_VALUE, 1).times(2));
163+
}
164+
165+
@Test
166+
void testRepeatedAdditionStaysExact() {
167+
ADTFraction sum = new ADTFraction(0, 1);
168+
for (int i = 0; i < 1000; i++) {
169+
sum = sum.plus(new ADTFraction(1, 1000));
170+
}
171+
assertEquals(new ADTFraction(1, 1), sum);
172+
}
173+
31174
@Test
32175
public void testReciprocal() {
33176
assertEquals(new ADTFraction(5, 3), fraction1.reciprocal());
34177
}
35178

179+
@Test
180+
void testReciprocalOfNegativeFraction() {
181+
assertEquals(new ADTFraction(-5, 3), new ADTFraction(3, -5).reciprocal());
182+
}
183+
184+
@Test
185+
void testReciprocalOfZeroThrows() {
186+
ADTFraction zero = new ADTFraction(0, 1);
187+
Exception exception = assertThrows(IllegalArgumentException.class, zero::reciprocal);
188+
assertEquals("Denominator cannot be 0", exception.getMessage());
189+
}
190+
36191
@Test
37192
public void testValue() {
38193
assertEquals(0.6F, fraction1.value());
39194
}
40195

196+
@Test
197+
void testValueOfNegativeFraction() {
198+
assertEquals(-0.5F, new ADTFraction(1, -2).value());
199+
}
200+
41201
@Test
42202
public void testEqualsAndHashCode() {
43203
ADTFraction fraction3 = new ADTFraction(3, 5);

0 commit comments

Comments
 (0)