|
| 1 | +packageMaths; |
| 2 | + |
| 3 | +publicclassBinaryPow { |
| 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 | +publicstaticintbinPow(inta,intp) { |
| 13 | +intres =1; |
| 14 | +while (p >0) { |
| 15 | +if ((p &1) ==1) { |
| 16 | +res =res *a; |
| 17 | + } |
| 18 | +a =a *a; |
| 19 | +p >>>=1; |
| 20 | + } |
| 21 | +returnres; |
| 22 | + } |
| 23 | + |
| 24 | +/** |
| 25 | + * Function for testing binary exponentiation |
| 26 | + * @param a the base |
| 27 | + * @param p the exponent |
| 28 | + */ |
| 29 | +publicstaticvoidtest(inta,intp) { |
| 30 | +intres =binPow(a,p); |
| 31 | +assertres == (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 | +publicstaticvoidmain(String[]args) { |
| 40 | +// prints 2^15: 32768 |
| 41 | +test(2,15); |
| 42 | + |
| 43 | +// prints 3^9: 19683 |
| 44 | +test(3,9); |
| 45 | + } |
| 46 | +} |