JavaAlgorithms/Maths/BinaryPow.java

49 lines
1.0 KiB
Java
Raw Normal View History

package Maths;
public class BinaryPow {
/**
* Calculate a^p using binary exponentiation
* [Binary-Exponentiation](https://cp-algorithms.com/algebra/binary-exp.html)
*
* @param a the base for exponentiation
* @param p the exponent - must be greater than 0
* @return a^p
*/
public static int binPow(int a, int p) {
int res = 1;
while (p > 0) {
if ((p & 1) == 1) {
res = res * a;
}
a = a * a;
p >>>= 1;
}
return res;
}
2020-11-16 09:40:56 +08:00
/**
* Function for testing binary exponentiation
2020-11-16 09:40:56 +08:00
*
* @param a the base
* @param p the exponent
*/
2020-11-16 09:40:56 +08:00
public static void test(int a, int p) {
int res = binPow(a, p);
assert res == (int) Math.pow(a, p) : "Incorrect Implementation";
System.out.println(a + "^" + p + ": " + res);
}
2020-11-16 09:40:56 +08:00
/**
* Main Function to call tests
*
* @param args System Line Arguments
*/
public static void main(String[] args) {
// prints 2^15: 32768
2020-11-16 09:40:56 +08:00
test(2, 15);
// prints 3^9: 19683
2020-11-16 09:40:56 +08:00
test(3, 9);
}
}