模幂 modular exponentiation 的计算方法

643阅读 0评论2010-04-08 wqfhenanxc_cu
分类:WINDOWS


所谓模幂,就是计算(b^e) mod m的值。这里b、e、m都为给定的某个值。
比如计算(5^3) mod 13  或者计算 (4^13) mod 497。

这里介绍三种计算模幂的方法:效率当然是越来越高效。
方法一、straightforward method
   直接先计算b^e, 然后再mod m。
方法二、
  
按如下步骤计算:
  1. Set c = 1, e' = 0.
  2. Increase e' by 1.
  3. Set c \equiv (b \cdot c) \pmod{m}.
  4. If e' < e, goto step 2. Else, c contains the correct solution to c \equiv b^e \pmod{m}.
其实就是乘一次模一次;比如按这种方法计算 (4^13) mod 497的过程如下:
    
方法三、Right-to-left binary method
     这种方法需要根据e的二进制形式进行计算。
   
e = \sum_{i=0}^{n-1} a_i 2^i 
b^e = b^{\left( \sum_{i=0}^{n-1} a_i 2^i 
\right)} = \prod_{i=0}^{n-1} \left( b^{2^i} \right) ^ {a_i} 
c \equiv \prod_{i=0}^{n-1} \left( b^{2^i} 
\right) ^ {a_i}\ (\mbox{mod}\ m)
写成C代码来描述计算过程如下:
//这里的参数base、 exponent、 modulus 分别代表上面的b、e、m。
Bignum modpow(Bignum base, Bignum exponent, Bignum modulus) {

Bignum result = 1;

while (exponent > 0) {
if (exponent & 1) {
// multiply in this bit's contribution while using modulus to keep result small
result = (result * base) % modulus;
}
// move to the next bit of the exponent, square (and mod) the base accordingly
exponent >>= 1;
base = (base * base) % modulus;
}

return result;
}
This code
 

上一篇:转载 trie数据结构
下一篇:转载 最长递增字串LIS问题