Exponentiation
Problem statement
Section titled “Problem statement”Find the value of .
Example
Section titled “Example”Input: a = 2, n = 3Output: 82 raise to the power 3 is 8.Maths, bitmask
Solution
Section titled “Solution”Expected Time Complexity:
Solution:
Section titled “Solution:”Lets take and .
Further in binary representation can be written as
5^6 = 5^($$^4$$^+$$^2$$^+$$^0$$^) = 5^4*5^2*5^0
To compute iterate over bits of , if the bit is set then multiple with answer.
Time Complexity:
#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
Section titled “Output”8