File tree Expand file tree Collapse file tree 1 file changed +46
-0
lines changed Expand file tree Collapse file tree 1 file changed +46
-0
lines changed Original file line number Diff line number Diff line change 1+ package Maths ;
2+
3+ public class BinaryPow {
4+ /**
5+ * Calculate a^p using binary exponentiation
6+ * [Binary-Exponentiation](https://cp-algorithms.com/algebra/binary-exp.html)
7+ *
8+ * @param a the base for exponentiation
9+ * @param p the exponent - must be greater than 0
10+ * @return a^p
11+ */
12+ public static int binPow (int a , int p ) {
13+ int res = 1 ;
14+ while (p > 0 ) {
15+ if ((p & 1 ) == 1 ) {
16+ res = res * a ;
17+ }
18+ a = a * a ;
19+ p >>>= 1 ;
20+ }
21+ return res ;
22+ }
23+
24+ /**
25+ * Function for testing binary exponentiation
26+ * @param a the base
27+ * @param p the exponent
28+ */
29+ public static void test (int a , int p ) {
30+ int res = binPow (a , p );
31+ assert res == (int ) Math .pow (a , p ) : "Incorrect Implementation" ;
32+ System .out .println (a + "^" + p + ": " + res );
33+ }
34+
35+ /** Main Function to call tests
36+ *
37+ * @param args System Line Arguments
38+ */
39+ public static void main (String [] args ) {
40+ // prints 2^15: 32768
41+ test (2 , 15 );
42+
43+ // prints 3^9: 19683
44+ test (3 ,9 );
45+ }
46+ }
You can’t perform that action at this time.
0 commit comments