快速乘方

a= an/2*an/2   , n为even

a= a(n-1)/2*a(n-1)/2 *a  , n为odd

 

double powerWithUnsignedExponent(double base, unsigned int exponent)
{
      if(0 == exponent)
          return 1;
      if(1 == exponent)
          return base;
      double result = powerWithUnsignedExponent(base, exponnet >> 1);
          result *= result;
      if(1 == exponent & 0x1)     //二进制末尾为1,一定是奇数
          result *= base;
 
      return result;
}

 

借助位运算判断奇偶性:

a & 0x1 == 0;    //even偶数

a & 0x1 != 0;     //odd奇数

 

posted @ 2016-10-05 17:29  Lunais  阅读(483)  评论(0编辑  收藏  举报