Adding first method check from Math's MathUtils.gcd method; and unit tests showing that this was needed. Bug reported and solved by Christian Semrau [LANG-662]

git-svn-id: https://svn.apache.org/repos/asf/commons/proper/lang/trunk@1059749 13f79535-47bb-0310-9956-ffa450edef68
This commit is contained in:
Henri Yandell 2011-01-17 04:30:05 +00:00
parent 7e8d044b7b
commit 2270d830fd
2 changed files with 19 additions and 2 deletions

View File

@ -579,8 +579,15 @@ public final class Fraction extends Number implements Comparable<Fraction> {
* @return the greatest common divisor, never zero
*/
private static int greatestCommonDivisor(int u, int v) {
//if either op. is abs 0 or 1, return 1:
if (Math.abs(u) <= 1 || Math.abs(v) <= 1) {
// From Commons Math:
if ((u == 0) || (v == 0)) {
if ((u == Integer.MIN_VALUE) || (v == Integer.MIN_VALUE)) {
throw new ArithmeticException("overflow: gcd is 2^31");
}
return Math.abs(u) + Math.abs(v);
}
//if either operand is abs 1, return 1:
if (Math.abs(u) == 1 || Math.abs(v) == 1) {
return 1;
}
// keep u and v negative, as negative integers range down to

View File

@ -330,6 +330,11 @@ public class FractionTest extends TestCase {
f = Fraction.getReducedFraction(-7, Integer.MIN_VALUE);
fail("Expecting ArithmeticException");
} catch (ArithmeticException ex) {}
// LANG-662
f = Fraction.getReducedFraction(Integer.MIN_VALUE, 2);
assertEquals(Integer.MIN_VALUE / 2, f.getNumerator());
assertEquals(1, f.getDenominator());
}
public void testFactory_double() {
@ -643,6 +648,11 @@ public class FractionTest extends TestCase {
assertEquals(0, result.getNumerator());
assertEquals(1, result.getDenominator());
assertSame(result, Fraction.ZERO);
f = Fraction.getFraction(Integer.MIN_VALUE, 2);
result = f.reduce();
assertEquals(Integer.MIN_VALUE / 2, result.getNumerator());
assertEquals(1, result.getDenominator());
}
public void testInvert() {