求幂运算的不同发法之间的时间复杂度比较
求幂运算有多种方法其中每种方法时间复杂度不尽相同
其中递归解法的数学原理为:
\(k^n\) = \(k^{(2) * (\frac{n}{2})}\)
详解如下:
void test(){
long long result = calculatePower(2, 4);
printf("the result is %lld\n", result);
}
long long calculatePower(int x, int n){
#if 0 - 此方法最慢
//O(N)
int power = x;
if (n >= 1) {
for (int i = 0; i < n - 1; i++) {
power *= x;
static int calculateCount = 0;
printf("calculate count is %d\n", calculateCount++);
}
}
NSLog(@"the power is %d", power);
return power;
#endif
#if 0 - 此方法并没有加快运算速度
//此做法相当于是个for循环
//O(N)
static int calculateCount = 0;
printf("calculate count is %d\n", calculateCount++);
if (n == 1) {
return x;
}else if(n > 1){
if (n % 2 == 0) {
return calculatePower(x, n/2) * calculatePower(x, n/2);
}else{
//return calculatePower(x, n/2) * calculatePower(x, n/2) * x;
return calculatePower(x, n -1) * x;
}
}
return 0;
#endif
#if 1 - 递归处理
//此方法 OlogN
static int calculateCount = 0;
printf("calculate count is %d\n", calculateCount++);
if (n == 1) {
return x;
}else if(n > 1){
if (n % 2 == 0) {
return calculatePower(x * x, n/2);
}else{
return calculatePower(x, n -1) * x;
}
}
return 0;
#endif
#if 0 - 不使用递归
//此方法 OlogN
int power = 1;
static int calculateCount = 0;
for (int i = 0; i < n/2; i++) {
power *= x * x;
printf("calculate count is %d\n", calculateCount++);
}
if (n % 2 != 0) {
power *= x;
}
return power;
#endif
}