Skip to main content

Exponentiation

Problem statement

Find the value of ana^n.

Example

Input: a = 2,  n = 3
Output: 8
2 raise to the power 3 is 8.

Tages

Maths, bitmask

Solution

Expected Time Complexity: Log(n)Log(n)

Click - to see solution

Solution:

Lets take a=5a = 5 and b=6b = 6.

Further bb in binary representation can be written as (110)2(110)_2

b=6=22+21+200=4+2+0b = 6 = 2^2 + 2^1 + 2^0*0 = 4 + 2 + 0

56=5(5^6 = 5^(4^4+^+2^2+^+0^0)=545250^) = 5^4*5^2*5^0

To compute ana^n iterate over bits of nn, if the ithith bit is set then multiple 2i2^i with answer.

Time Complexity: log(n)log(n)

#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";
}

Output

8