# 【原】模幂运算(Modular Exponentiation)算法

已知b, e, m, 求c。形如：

其中，b<m (若b>m，可转换b为b%=m)

，得到 c = 445。

   1: int Power(int b, int e)
   2: {
   3:     if (0 == b || 1 == b || 0 == e)
   4:         return 1;
   5:     if (1 == e)
   6:         return b;
   7:     int n = e>>1;
   8:     int tmp = Power(b, n);
   9:     if (0 == (e&1))
  10:         return tmp*tmp;
  11:     else
  12:         return tmp*tmp*b;
  13: }

   1: typedef __int64 BigInt;
   2:
   3: //modular exponentiation
   4: BigInt modexp(BigInt b,BigInt e,BigInt m)
   5: {
   6:     b%=m;
   7:     BigInt result=1;
   8:     while(e>0)
   9:     {
  10:         if( e&1 == 1 )
  11:             result = (result*b)%m;
  12:         // multiply in this bit's contribution while using modulus to keep result small
  13:         // move to the next bit of the exponent, square (and mod) the base accordingly
  14:         e >>= 1;
  15:         b = (b*b)%m;
  16:     }
  17:     return result;
  18: }

posted @ 2011-01-30 13:06  Allen Sun  阅读(6504)  评论(0编辑  收藏  举报