目录
1、分治求x的n次方思路
2、c++代码实现
内容
1、分治求x的n次方思路T(n)=Θ(lgn)
为了计算乘方数a^n,传统的做法(所谓的Naive algorithm)就是循环相乘n次,算法效率为Θ(n)。但是如果采用分治法的思想,算法效率可以提高到Θ(lgn),如下图所示。
![]()
2、c++代码实现
Power.h
1 #ifndef POWER_HH
2 #define POWER_HH
3 template<typename T>
4 class Power
5 {
6 public:
7 T Power_Compute(T x,int n);
8 };
9 template<typename T>//带模板
10 T Power<T>::Power_Compute(T x,int n)
11 {
12 if (1==n)
13 return x;
14 else if(n>1)
15 {
16 int m=n/2; //取中间数
17 T s=Power_Compute(x,m);//递归求x的n/2次方
18 if (0==n%2) //若n为偶数
19 return s*s;
20 else //若n为奇数
21 return s*s*x;
22 }
23 }
24 #endif
主函数 Power.cpp
1 #include <iostream>
2 #include "Power.h"
3 using namespace std;
4 int main()
5 {
6 Power<int> pow1;//x为整数
7 Power<double> pow2;//x为小数
8 cout<<pow1.Power_Compute(3,4)<<endl;
9 cout<<pow2.Power_Compute(3.2,4)<<endl;
10 system("PAUSE");
11 return 0;
12 }
Output(输出):
![]()