Binary Exponentiation
Overview
Binary Exponentiation is a method for efficiently calculating large powers of a number, such as . Instead of using the naive approach of repeatedly multiplying the base number by itself, which has a time complexity of , binary exponentiation uses a technique called "exponentiation by squaring" to accomplish the same task in time complexity.
The basic idea behind binary exponentiation is that we can express as but it is not efficient for a large and . If we display the exponent in binary representation, says , then we have Supposing we have a sequence , we can see the an element in the sequence is the square of previous element, i.e. . Therefore, to calculate , we just need to calculate times, i.e. ( -> -> ). We skip here because the bit is not set. This approach gives us complexity.
To generalise it, for a positive integer , we have
Implementation
- C++
long long fastpow(long long base, long long exp) {
long long res = 1;
while (exp > 0) {
// if n is odd, a ^ n can be seen as a ^ (n / 2) * a ^ (n / 2) * a
if (exp & 1) res *= base;
// if n is even, a ^ n can be seen as a ^ (n / 2) * a ^ (n / 2)
base *= base;
// shift 1 bit to the right
exp >>= 1;
}
return res;
}
In case you need to take mod during the calculation, we can do as follows.
- C++
long long modpow(long long base, long long exp, long long mod) {
base %= mod;
long long res = 1;
while (exp > 0) {
if (exp & 1) res = (res * base) % mod;
base = (base * base) % mod;
exp >>= 1;
}
return res;
}
Suggested Problems
Problem Name | Difficulty | Solution Link |
---|---|---|
0050 - Pow(x, n) | Medium | View Solutions |