计算x^n,用普通的算法就是x乘n次的话,时间复杂度就是O(n)
利用分治法
x ^ n = x^(n/2) *x(n/2) ( n是偶数)
= x^((n-1)/2)*x^((n-1)/2)*x (x是奇数)
这样的话 T(n) = O(1) if x = 1
= T(n/2)+O(1) (此处原来是2*T(n/2)+O(1) ,但是可以只计算一次)
根据主定理: T(n) = O(lgn)
代码如下
#include <iostream>
#include <math.h>
#include <time.h>
using namespace std;
float fast_pow ( float x, float y ) {
int temp;
if ( y == 1 )
return x;
else if ( (int)y % 2 == 0 ) {
temp = fast_pow(x,y/2); // 用临时变量减少重复的运算
return temp*temp;
}
else {
temp = fast_pow(x,(y-1)/2);
return temp*temp*x;
}
}
floa