码迷,mamicode.com
首页 > 其他好文 > 详细

SGI STL的 power 函数之个人理解

时间:2015-03-28 18:42:28      阅读:155      评论:0      收藏:0      [点我收藏+]

标签:

SGI STL的power函数用于计算某数的n次方

例如求 x的n次幂   n = 20 (20 二进制 10100)

                          1    0   1   0   0
                   20 =   2^4  +  2^2
                   
                   x^20 = x^((2^4) + (2^2))  = x^( 2^4 )  *   x ^( 2^2)
                                                 part2          part1

template <class _Tp, class _Integer, class _MonoidOperation>
_Tp __power(_Tp __x, _Integer __n, _MonoidOperation __opr)
{
  if (__n == 0)
    return identity_element(__opr);
  else {
    while ((__n & 1) == 0) {               //
      __n >>= 1;                           //    此while循环是part1求出来
      __x = __opr(__x, __x);              //
    }                                      
    _Tp __result = __x;     // 当前x的值是part1
    __n >>= 1;              //  这里有_result记录了 part1 所以这里n直接向右移一位
    
    while (__n != 0) {                     // 
      __x = __opr(__x, __x);               //   求part2  (如果有更多part也在这个循环里面计算,这里的说明只针对20次幂)
      if ((__n & 1) != 0)                  //          
        __result = __opr(__result, __x);   //  result =  result * part2 只有遇到 值为1的位才记录(此时result = part1)
                                           //  因为只有遇到位为1才能求出下一个part
      __n >>= 1;                           //  n = n / 2;
    }
    return __result;
  }
}


template<typename T>
   struct multiplies
   {
     typedef T first_argument_type;
   
     typedef T second_argument_type;
   
     typedef T result_type;
   
   __host__ __device__ T operator()(const T &lhs, const T &rhs) const {return lhs * rhs;}
 }; // end multiplies

 

SGI STL的 power 函数之个人理解

标签:

原文地址:http://www.cnblogs.com/elang/p/4374533.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!