2016-07-04 41 views
1

评估给定度数的多项式和已知系数(按顺序)的最快已知算法是什么? 我试着做以下方式:在特定值处评估多项式的​​最快方法

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++)。

+0

快速还是精确?有时你不能同时获得 – user463035818

+0

一个“常用”的方法是从最高度的系数开始,然后乘以“x”并添加下一个系数:“res = a [n]; res = x * res + a [n - 1]; res = x * res + a [n - 2]; ...; res = x * res + a [0];'。有了这个,你有n次乘法和n次加法。 – Holt

+0

这是霍纳的方法吧?...... – yobro97

回答

1

你的评价具有递归复杂

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

如果只计算乘法,再加上一些开销子阵列的结构,从而在整体上T(N)= 2N-2个乘法(对于n次幂2)。 (错误命名的)Horner方法使用n-1次乘法运算。

0

一个非常简单的,以评估多项式比较快的方法是使用的事实,你增加指数与每个术语:

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; 
} 

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

Faster方法存在,但更复杂。

+0

这不是霍纳的方法....? – yobro97

+0

在我的问题中提到的代码中....每次通过函数时,度数都不会减半......因此减少了时间复杂度? – yobro97

+0

@ yobro97分解系数的代码部分是O(n log n)。 –