Skip to main content

Modular Exponentiation

Problem statement

Find the value of (an)(a^n)%modmod.

Example

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

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 and do answer = answer % mod.

Time Complexity: log(n)log(n)

#include <iostream>
using namespace std;

int ModularExponent(int a, int n, int mod) {
int ans = 1;
while (n > 0) {
int bit = n & 1;
if (bit) {
ans = (ans * a) % mod;
}
n >>= 1;
a = (a * a) % mod;
}
return ans;
}

int main() {

int a = 2;
int n = 3;
int mod = 3
cout << ModularExponent(a, n, mod) << "\n";
}

Output

2