递归之求幂

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_33054265/article/details/51405308

刚开始学习用递归实现x的n次方时,其思想(或者递推式)一般如下:
X^n = X * X^n-1(n > 0);
X^n = 1(n = 0);
C语言代码如下:
//__int64为有符号8字节整数
__int64 power(int x, int n){
if(n == 0){//递归结束条件
return 1;
}
return x * power(x, n -1);
}
这种简单的求幂算法的时间复杂度为O(n);

下面介绍速度更快的二分求幂算法,其思想(或者递推式)如下:
X^n = X^n/2 * X^n/2(当n为偶数时,即n%2 = 0时);
X^n = X^n/2 * X^n/2 * X(当n为奇数时,即n%2 = 1时);
C语言代码如下:
__int64 power(int x, int n){
__int64 res;
if(n == 0){//递归结束条件
return 1;
}
res = power(x, n / 2);
res *= res;
if(n % 2 == 1){//当n为奇数时,还需再乘一次x
res *= x;
}
return res;
}
二分求幂算法的时间复杂度为:O(logn)

文章若有不足处,还请大家指正!谢谢!

猜你喜欢

转载自blog.csdn.net/qq_33054265/article/details/51405308
今日推荐