Data Structures 之 散列

1. Horner法则

参考资料:http://www.cnblogs.com/tanky_woo/archive/2010/11/11/1874980.html

简介:

假设有n+2个实数a0,a1,…,an,和x的序列,要对多项式Pn(x)= anxn+an-1xn-1+…+ax+a求值,直接方法是对每一项分别求值,并把每一项求的值累加起来,这种方法十分低效,它需要进行n+(n-1)+…+1=n(n+1)/2次乘法运算和n次加法运算。

通过如下变换我们可以得到一种快得多的算法,即Pn(x)= anxn +an-1xn-1+…+ax+a=((…(((anx +an-1)x+an-2)x+ an3)…)x+a1)x+a,这种求值的安排我们称为霍纳法则。

Horner法则出现的原因:为多项式求值提供了更高效的算法。

#include <iostream>


using namespace std;


double HornerFunc(double a[], int n, double x);


int main()
{
 cout << "test is starting ..." << endl;
 int n;
 double x;
 
 double *a;
 
 cout << "input the n : " << endl;
 cin >> n;


 cout << "input the x : " << endl ;
 cin >> x;


 a = new double[n+1];
 cout << "input a[n] ..." << endl;
 for (int i=0; i<n+1; i++)
 {
 cin >> a[i];
 }




 for(int i=n; i>=0; i--)
    {
        if(i != n)
            cout << " + ";
        cout << a[i] << "*x^" << i;
    }
    cout << " = " << HornerFunc(a, n, x) << endl;
 
 delete[]a;   //new使用完释放空间


 return 0;


}






double HornerFunc(double a[], int n, double x)
{
    double res = 0.0;
 
    for(int i=n; i>=0; i--)
 {
 res = x*res + a[i];    //(an * x + a(n-1)) * x + a(n-2) ... 叠加
 }
     
    return res;
}




你可能感兴趣的:(Data Structures 之 散列)