XenoAmess commented on a change in pull request #83:
URL: https://github.com/apache/commons-numbers/pull/83#discussion_r476632088
##########
File path:
commons-numbers-fraction/src/main/java/org/apache/commons/numbers/fraction/Fraction.java
##########
@@ -775,19 +778,45 @@ public Fraction divide(Fraction value) {
*/
@Override
public Fraction pow(final int exponent) {
+ if (exponent == 1) {
+ return this;
+ }
if (exponent == 0) {
return ONE;
}
- if (isZero()) {
- return ZERO;
+ if (exponent == -1) {
+ return this.reciprocal();
}
-
- if (exponent < 0) {
- return new Fraction(ArithmeticUtils.pow(denominator, -exponent),
- ArithmeticUtils.pow(numerator, -exponent));
+ if (this.denominator == 0) {
+ if (exponent > 0) {
+ throw new
ArithmeticException(STRING_THE_DENOMINATOR_MUST_NOT_BE_ZERO);
+ } else {
+ return ZERO;
+ }
+ }
+ if (this.numerator == 0) {
+ if (exponent < 0) {
+ throw new
ArithmeticException(STRING_THE_DENOMINATOR_MUST_NOT_BE_ZERO);
+ } else {
+ return ZERO;
+ }
}
- return new Fraction(ArithmeticUtils.pow(numerator, exponent),
- ArithmeticUtils.pow(denominator, exponent));
+ if (exponent > 0) {
+ return new Fraction(
+ ArithmeticUtils.pow(this.numerator, exponent),
+ ArithmeticUtils.pow(this.denominator, exponent)
+ );
+ }
+ if (exponent == Integer.MIN_VALUE) {
+ return new Fraction(
+ ArithmeticUtils.pow(this.denominator, Integer.MAX_VALUE) *
this.denominator,
Review comment:
@aherbert
No need to use Math.multipyExact here.
Because:
If this.denominator be 0,1,or -1, then it will never overflow.
Other wise, any other int do pow with Integer.MAX_VALUE will overflow, it
will overflow in ArithmeticUtils.pow, and thus before we do the raw multiply.
So it is a tricky but correct implement.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
[email protected]