TheAlgorithms-C-Plus-Plus/math/binary_exponent.cpp

32 lines
813 B
C++
Raw Normal View History

2020-04-02 06:58:03 +08:00
/// C++ Program to find Binary Exponent recursively.
2020-04-02 06:33:22 +08:00
#include<iostream>
/*
* 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).
*/
2020-04-02 06:58:03 +08:00
/// Function to calculate exponent in O(log(n)) using binary exponent.
2020-04-02 07:01:44 +08:00
int binExpo(int a, int b) {
2020-04-02 07:04:47 +08:00
if (b == 0) {
return 1;
}
2020-04-02 07:01:44 +08:00
int res = binExpo(a, b/2);
2020-04-02 07:04:47 +08:00
if (b%2) {
return res*res*a;
}
else {
return res*res;
}
2020-04-02 06:33:22 +08:00
}
int main() {
2020-04-02 07:01:44 +08:00
int a, b;
2020-04-02 06:40:26 +08:00
/// Give two nos as a^b (where '^' denotes power exponent operation)
2020-04-02 06:33:22 +08:00
std::cin >> a >> b;
2020-04-02 06:58:03 +08:00
/// Result of a^b
2020-04-02 07:01:44 +08:00
std::cout << binExpo(a, b) << std::endl;
2020-04-02 06:33:22 +08:00
}