高效率的取幂运算

来源:互联网 发布:人工智能行业研究 编辑:程序博客网 时间:2024/05/03 06:24

计算X^N的常见算法是使用N-1次乘法自乘,时间复杂度为O(n)。使用下面的递归算法更好,时间复杂度为O(logn):

template<class T>T Pow(T x, unsigned int N){if (0==N){return 1;}else if (1==N){return x;}else if (0==N%2){return Pow(x*x, N/2);}else{return Pow(x*x, N/2)*x;}}


原创粉丝点击