zoukankan      html  css  js  c++  java
  • 【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 = 
    
    " << 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 }
  • 相关阅读:
    installanywhere制作java installation
    长文件名处理
    Hibernate+ehcache二级缓存技术
    如何在JSP里添加删除cookie
    收集java精确截取字符串
    在什么情况下可以定义static 方法?
    Hibernate2 到 Hibernate3 的问题
    出现java.lang.UnsupportedClassVersionError 错误的原因
    DMI指标又叫动向指标或趋向指标
    Tomcat下log4j设置文件路径和temp目录
  • 原文地址:https://www.cnblogs.com/catnip/p/4345255.html
Copyright © 2011-2022 走看看