算法分析
First, it is required that the exponent e be converted to binary notation. That is, e can be written as:
In such notation, the length of e is n bits. ai can take the value 0 or 1 for any i such that 0 ≤ i < n. By definition, an − 1 = 1.
The value be can then be written as:
The solution c is therefore:
C++实现
int pow_mod(int a, int n, int mod){
int r = 1 % mod;
while (n) {
if (n&1)
r = (ll)r*a%mod;
a = (ll)a*a%mod;
n >>= 1;
}
return r;
}
Reference
1. http://www.dragonwins.com/domains/getteched/crypto/modular_exponentiation.htm
2. https://www.khanacademy.org/computing/computer-science/cryptography/modarithmetic/a/fast-modular-exponentiation
3. https://en.wikipedia.org/wiki/Modular_exponentiation