Skip to content

Commit a006205

Browse files
authored
Detect overflow in Pow.pow (#7752)
Use Math.multiplyExact for overflow handling in pow
1 parent 401e253 commit a006205

1 file changed

Lines changed: 2 additions & 1 deletion

File tree

  • src/main/java/com/thealgorithms/maths

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

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,14 +22,15 @@ private Pow() {
2222
* @param b the exponent to which the base {@code a} is raised. Must be a non-negative integer.
2323
* @return the result of {@code a}<sup>{@code b}</sup> as a {@code long}.
2424
* @throws IllegalArgumentException if {@code b} is negative.
25+
* @throws ArithmeticException if the result overflows a {@code long}.
2526
*/
2627
public static long pow(int a, int b) {
2728
if (b < 0) {
2829
throw new IllegalArgumentException("Exponent must be non-negative.");
2930
}
3031
long result = 1;
3132
for (int i = 1; i <= b; i++) {
32-
result *= a;
33+
result = Math.multiplyExact(result, (long) a);
3334
}
3435
return result;
3536
}

0 commit comments

Comments
 (0)