MCPcopy Create free account
hub / github.com/TheAlgorithms/Java / binPow

Method binPow

src/main/java/com/thealgorithms/maths/BinaryPow.java:15–25  ·  view source on GitHub ↗

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

(int a, int p)

Source from the content-addressed store, hash-verified

13 * @return a^p
14 */
15 public static int binPow(int a, int p) {
16 int res = 1;
17 while (p > 0) {
18 if ((p & 1) == 1) {
19 res = res * a;
20 }
21 a = a * a;
22 p >>>= 1;
23 }
24 return res;
25 }
26}

Callers 6

testBinPowMethod · 0.95
testZeroExponentMethod · 0.95
testZeroBaseMethod · 0.95
testOneBaseMethod · 0.95
testNegativeBaseMethod · 0.95
testLargeExponentMethod · 0.95

Calls

no outgoing calls

Tested by 6

testBinPowMethod · 0.76
testZeroExponentMethod · 0.76
testZeroBaseMethod · 0.76
testOneBaseMethod · 0.76
testNegativeBaseMethod · 0.76
testLargeExponentMethod · 0.76