C++中的power函数

在cmath头文件中存在函数pow,在stl_numeric.h中存在对于power的具体实现

只看一下对于power的具体实现,之前不知道有没有听说过快速幂,power可以说就是快速幂的实现

函数原型如下:


template <class T, class Integer>
inline T power(T x, Integer n) {
  return power(x, n, multiplies<T>());      //默认使用乘法的仿函数
}
template <class T>
struct multiplies : public binary_function<T, T, T> {
    T operator()(const T& x, const T& y) const { return x * y; }
};

发现power中默认实现x^n操作,那么具体实现如下:

template <class T, class Integer, class MonoidOperation>
T power(T x, Integer n, MonoidOperation op) {
  if (n == 0)
    return identity_element(op);
  else {
    while ((n & 1) == 0) {        //这里发现n一直为偶数,那么直接原数相乘,n缩小2倍
      n >>= 1;
      x = op(x, x);
    }

    T result = x;                //这里result保存一个x,n可以理解为变回奇数
    n >>= 1;                     //缩小2倍,继续指向下面的操作
    while (n != 0) {
      x = op(x, x);
      if ((n & 1) != 0)          //发现是奇数        将奇数去除,即乘一个x
        result = op(result, x);
      n >>= 1;
    }
    return result;               //最终结果result
  }
}

感觉这样的实现相对于之前的一直在写的快速幂,逻辑性更好一些,并且这里支持泛型以及仿函数操作操作,可以不使用默认的乘法仿函数,改用自己定义的仿函数!

猜你喜欢

转载自blog.csdn.net/li1615882553/article/details/83449409