Modular Exponentiation
Problem statement
Find the value of %.
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:
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 and do answer = answer % mod.
Time Complexity:
- C++
- Python
#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";
}
def ModularExponent(a, n, mod):
ans = 1
while (n > 0):
bit = n & 1
if bit:
ans = (ans * a) % mod
n >>= 1
a *= a
a %= mod
return ans
print(ModularExponent(2, 3, 3))
Output
2