Modular Exponentiation
Problem statement
Section titled “Problem statement”Find the value of %.
Example
Section titled “Example”Input: a = 2, n = 3, mod = 3Output: 22 raise to the power 3 is 8 and 8%3 = 2.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 and do answer = answer % mod.
Time Complexity:
#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
Section titled “Output”2