- Notifications
You must be signed in to change notification settings - Fork 19.9k
/
Copy pathPow.java
36 lines (34 loc) · 1.35 KB
/
Pow.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
packagecom.thealgorithms.maths;
/**
* A utility class for computing exponentiation (power) of integers.
* <p>
* This class provides a method to calculate the value of a base raised to a given exponent using a simple iterative approach.
* For example, given a base {@code a} and an exponent {@code b}, the class computes {@code a}<sup>{@code b}</sup>.
* </p>
*/
publicfinalclassPow {
privatePow() {
}
/**
* Computes the value of the base raised to the power of the exponent.
* <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.
* </p>
*
* @param a the base of the exponentiation. Must be a non-negative integer.
* @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.
*/
publicstaticlongpow(inta, intb) {
if (b < 0) {
thrownewIllegalArgumentException("Exponent must be non-negative.");
}
longresult = 1;
for (inti = 1; i <= b; i++) {
result *= a;
}
returnresult;
}
}