求多项式特定值的最快方法

Fastest way of evaluating a polynomial at a particular value

本文关键字:方法 多项式      更新时间:2023-10-16

对于给定度和已知系数(按顺序)的多项式,已知最快的算法是什么?我试着这样做:

long long int evaluatepoly(long long int* coeffa0,long long int degree,long long int x)
{
/*coeffa0 is the coeffecient array in order x^0,x^1,x^2....degree->degree of polynomial
  and x is the value where the polynomial is to be evaluated*/
  if(degree==1)
  {
    return (coeffa0[0] + (coeffa0[1])*x);
  }
  else if(degree==0)
    return coeffa0[0];
  else{
    long long int odd,even,n=degree;
    if(degree%2==0){
      odd=(n/2);
      even=(n/2)+1;
    }
    else{
      odd=(n+1)/2;
      even=(n+1)/2;
    }
    long long int oddcoeff[odd],evencoeff[even];
    int i=0;
    while(i<=degree)
    {
      if(i%2==0)
        evencoeff[i/2]=coeffa0[i];
      else
        oddcoeff[i/2]=coeffa0[i];
      i++;
    }
    int y=x*x;
    return (evaluatepoly(evencoeff,(even-1),y) + x*(evaluatepoly(oddcoeff,(odd-1),y)));
  }
}

我是一个初学者,所以也欢迎改进以上代码的建议(在C/c++中)。

您的计算具有递归复杂性

T(2n)=2*T(n)+2

如果只计算乘法,再加上构建子数组的一些开销,导致总的T(n)=2n-2次乘法(对于2的n次幂)。

(不恰当的)Horner方法使用n-1乘法。

计算多项式的一个非常简单,相对快速的方法是使用每项增加指数的事实:

int polynomial(int* coefs, int deg, int x) {
    int factor = 1, result = 0; 
    for(int term = 0; term <= deg; term++) {
        result += coefs[term] * factor;
        factor *= x;
    }
    return result;
}

以上代码在多项式的程度上具有线性时间复杂度。考虑这个伪代码,我还没有编译它。希望能有所帮助!

有更快的方法,但是更复杂。