-
Notifications
You must be signed in to change notification settings - Fork 7.8k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #1247 from saurabhpal007/master
Create BinaryPow.java
- Loading branch information
Showing
1 changed file
with
48 additions
and
0 deletions.
There are no files selected for viewing
48 changes: 48 additions & 0 deletions
48
Program's_Contributed_By_Contributors/Java_Programs/Misc/BinaryPow.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,48 @@ | ||
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; | ||
} | ||
|
||
/** | ||
* Function for testing binary exponentiation | ||
* | ||
* @param a the base | ||
* @param p the exponent | ||
*/ | ||
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); | ||
} | ||
|
||
/** | ||
* Main Function to call tests | ||
* | ||
* @param args System Line Arguments | ||
*/ | ||
public static void main(String[] args) { | ||
// prints 2^15: 32768 | ||
test(2, 15); | ||
|
||
// prints 3^9: 19683 | ||
test(3, 9); | ||
} | ||
} |