Exponentiation
Problem statement
Find the value of .
Example
Input: a = 2, n = 3
Output: 8
2 raise to the power 3 is 8.
Tages
Maths
, bitmask
Solution
Expected Time Complexity:
Click - to see solution
Solution:
Lets take and .
Further in binary representation can be written as
To compute iterate over bits of , if the bit is set then multiple with answer.
Time Complexity:
- C++
- Python
#include <iostream>
using namespace std;
int Exponent(int a, int n) {
int ans = 1;
while (n > 0) {
int bit = n & 1;
if (bit) {
ans = (ans * a);
}
n >>= 1;
a *= a;
}
return ans;
}
int main() {
int a = 2;
int n = 3;
cout << Exponent(a, n) << "\n";
}
def Exponent(a, n):
ans = 1
while (n > 0):
bit = n & 1
if bit:
ans = (ans * a)
n >>= 1
a *= a
return ans
print(Exponent(2, 3))
Output
8