【练习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

相关文章:

  • 2021-07-24
  • 2022-02-18
  • 2021-10-26
  • 2021-11-25
  • 2021-05-29
  • 2021-11-23
  • 2021-11-24
猜你喜欢
  • 2021-06-04
  • 2021-08-02
  • 2022-01-19
  • 2022-02-04
  • 2022-01-25
  • 2021-07-08
  • 2021-10-16
相关资源
相似解决方案