Fraction: test for zero in add/subtract int
Added test cases with Integer.MIN_VALUE as this requires special
handling for subtract.
diff --git a/commons-numbers-fraction/src/main/java/org/apache/commons/numbers/fraction/Fraction.java b/commons-numbers-fraction/src/main/java/org/apache/commons/numbers/fraction/Fraction.java
index a2ba424..e9b7199 100644
--- a/commons-numbers-fraction/src/main/java/org/apache/commons/numbers/fraction/Fraction.java
+++ b/commons-numbers-fraction/src/main/java/org/apache/commons/numbers/fraction/Fraction.java
@@ -481,6 +481,12 @@
* cannot be represented in an {@code int}.
*/
public Fraction add(final int value) {
+ if (value == 0) {
+ return this;
+ }
+ if (isZero()) {
+ return new Fraction(value);
+ }
// Convert to numerator with same effective denominator
final long num = (long) value * denominator;
return of(Math.toIntExact(numerator + num), denominator);
@@ -510,6 +516,15 @@
* cannot be represented in an {@code int}.
*/
public Fraction subtract(final int value) {
+ if (value == 0) {
+ return this;
+ }
+ if (isZero()) {
+ // Special case for min value
+ return value == Integer.MIN_VALUE ?
+ new Fraction(Integer.MIN_VALUE, -1) :
+ new Fraction(-value);
+ }
// Convert to numerator with same effective denominator
final long num = (long) value * denominator;
return of(Math.toIntExact(numerator - num), denominator);
diff --git a/commons-numbers-fraction/src/test/java/org/apache/commons/numbers/fraction/FractionTest.java b/commons-numbers-fraction/src/test/java/org/apache/commons/numbers/fraction/FractionTest.java
index ff085c0..04ac063 100644
--- a/commons-numbers-fraction/src/test/java/org/apache/commons/numbers/fraction/FractionTest.java
+++ b/commons-numbers-fraction/src/test/java/org/apache/commons/numbers/fraction/FractionTest.java
@@ -322,6 +322,11 @@
}
Assertions.assertThrows(NullPointerException.class, () -> Fraction.ONE.add((Fraction) null));
+
+ // Edge case
+ assertFraction(Integer.MIN_VALUE, -1, Fraction.ZERO.add(Fraction.of(Integer.MIN_VALUE, -1)));
+ assertFraction(Integer.MIN_VALUE, 1, Fraction.ZERO.add(Fraction.of(Integer.MIN_VALUE, 1)));
+ assertFraction(Integer.MIN_VALUE, 1, Fraction.ZERO.add(Integer.MIN_VALUE));
}
@Test
@@ -417,6 +422,11 @@
}
Assertions.assertThrows(NullPointerException.class, () -> Fraction.ONE.add((Fraction) null));
+
+ // Edge case
+ assertFraction(Integer.MIN_VALUE, 1, Fraction.ZERO.subtract(Fraction.of(Integer.MIN_VALUE, -1)));
+ assertFraction(Integer.MIN_VALUE, -1, Fraction.ZERO.subtract(Fraction.of(Integer.MIN_VALUE, 1)));
+ assertFraction(Integer.MIN_VALUE, -1, Fraction.ZERO.subtract(Integer.MIN_VALUE));
}
@Test