From 1b828269dc6dbde8009b0177d15ba8433c6a16b2 Mon Sep 17 00:00:00 2001 From: Lakhan Nad Date: Mon, 16 Nov 2020 07:10:16 +0530 Subject: [PATCH] Added Binary Exponentiation Fixes:#1943 (#1945) * Added Binary Exponentiation Fixes:#1943 * tests added in Binary Exponentation #1945 * Assertion Added --- Maths/BinaryPow.java | 46 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 Maths/BinaryPow.java diff --git a/Maths/BinaryPow.java b/Maths/BinaryPow.java new file mode 100644 index 000000000..d3224c8bc --- /dev/null +++ b/Maths/BinaryPow.java @@ -0,0 +1,46 @@ +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); + } +}