From 70ac13f4a0fc15f987d3874112dfdeab0af388ac Mon Sep 17 00:00:00 2001 From: Mann Mehta <44433995+mann2108@users.noreply.github.com> Date: Thu, 2 Apr 2020 04:03:22 +0530 Subject: [PATCH] added binary_exponent.cpp --- math/binary_exponent.cpp | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 math/binary_exponent.cpp diff --git a/math/binary_exponent.cpp b/math/binary_exponent.cpp new file mode 100644 index 000000000..0f9d442a5 --- /dev/null +++ b/math/binary_exponent.cpp @@ -0,0 +1,25 @@ +/// C++ Program to find Binary Exponent recursively. + +#include +/* + * Calculating a^b in O(log(b)) by converting b in binary no. + * Binary exponentiation (also known as exponentiation by squaring) + * is a trick which allows to calculate an using only O(logn) multiplications + * (instead of O(n) multiplications required by the naive approach). +*/ + +int binExpo(int a,int b) { + if (b == 0) return 1; + int res = binExpo(a,b/2); + if (b%2) return res*res*a; + else return res*res; +} + +int main() { + int a,b; + /// Give two nos as a^b (where '^' denotes power exponent operation + std::cin >> a >> b; + ///Result of a^b + std::cout << binExpo(a,b) << endl; +} +