【Weiss】【第03章】练习3.8:有序多项式求幂

【练习3.8】

编写一个程序,输入一个多项式F(X),计算出(F(X))P。你程序的时间复杂度是多少?

 

Answer:

(特例:P==0时,返回1。)

如果P是偶数,那么就递归计算((F(X))P/2)*((F(X))P/2),

如果P是基数,那么就递归计算((F(X))P/2)*((F(X))P/2)*F(X)。

直到P==1时,直接返回F(X)结束递归。

时间复杂度计算为O(N)=2O((N/2)log(N/2))+O(1)

则时间复杂度O(logN)

 

因为一开始Poly的系数那里用的是int,所以系数太大会溢出囧…………

测试代码:

 

 1 #include <iostream>
 2 #include "linklist.h"
 3 using linklist::List;
 4 using namespace std;
 5 int main(void)
 6 {
 7     //测试多项式加法
 8     List<Poly> a;
 9     a.additem(Poly(1, 0));
10     a.additem(Poly(1, 1));
11     cout << "  ( " << flush;
12     a.traverse();
13     cout << ") ^ 30 = \n\n" << flush;
14     
15     List<Poly> answer;
16     answer = linklist::polypower(a, 30);
17     cout << "  ( " << flush;
18     answer.traverse();
19     cout << ")" << flush;
20     system("pause");
21 }
View Code

 

实现代码:

 1 List<Poly> polypower(const List<Poly> &inorder, int times)
 2 {
 3     List<Poly> answer;
 4     if (times == 0)
 5     {
 6         answer.additem(Poly(1, 0));
 7         return answer;
 8     }
 9     else if (times == 1)
10         return answer = inorder;
11     else if (times % 2 == 0)
12         return polymulti_sort(polypower(inorder, times / 2), polypower(inorder, times / 2));
13     //结果非整数自动向下取整,不需要(times - 1) / 2
14     else if (times % 2 != 0)
15         return polymulti_sort(polymulti_sort(polypower(inorder, times / 2), polypower(inorder, times / 2)), inorder);
16 }

 

posted @ 2015-03-17 19:19  猫薄荷喂狗  阅读(449)  评论(0编辑  收藏  举报