Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 5 additions & 2 deletions src/main/java/com/thealgorithms/maths/Pow.java
Original file line number Diff line number Diff line change
Expand Up @@ -16,20 +16,23 @@ private Pow() {
* <p>
* The method calculates {@code a}<sup>{@code b}</sup> by iteratively multiplying the base {@code a} with itself {@code b} times.
* If the exponent {@code b} is negative, an {@code IllegalArgumentException} is thrown.
* If the exact result does not fit in a {@code long}, an {@code ArithmeticException} is thrown
* instead of silently returning a wrapped-around value.
* </p>
*
* @param a the base of the exponentiation. Must be a non-negative integer.
* @param a the base of the exponentiation.
* @param b the exponent to which the base {@code a} is raised. Must be a non-negative integer.
* @return the result of {@code a}<sup>{@code b}</sup> as a {@code long}.
* @throws IllegalArgumentException if {@code b} is negative.
* @throws ArithmeticException if the result overflows a {@code long}.
*/
public static long pow(int a, int b) {
if (b < 0) {
throw new IllegalArgumentException("Exponent must be non-negative.");
}
long result = 1;
for (int i = 1; i <= b; i++) {
result *= a;
result = Math.multiplyExact(result, a);
}
return result;
}
Expand Down
12 changes: 12 additions & 0 deletions src/test/java/com/thealgorithms/maths/PowTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -33,4 +33,16 @@ void testPowHandlesZeroBase() {
void testPowHandlesOneBase() {
assertEquals(1, Pow.pow(1, 100));
}

@ParameterizedTest
@CsvSource({"2, 62, 4611686018427387904", "-2, 63, -9223372036854775808", "-3, 3, -27", "-2, 4, 16", "10, 18, 1000000000000000000"})
void testPowAtAndNearLongBounds(int base, int exponent, long expected) {
assertEquals(expected, Pow.pow(base, exponent));
}

@ParameterizedTest
@CsvSource({"2, 63", "2, 64", "-2, 64", "10, 19", "2147483647, 3"})
void testPowThrowsOnOverflow(int base, int exponent) {
assertThrows(ArithmeticException.class, () -> Pow.pow(base, exponent));
}
}