算法導論-求x的n次方


目錄                                                        

          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(輸出):        

     

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM