Console.WriteLine("Hello, World!"); var list = new double[100000000]; for(int i = 0; i < 100000000; i++) { list[i] = i; } Console.WriteLine("Func1结果:"+ Func1(100000000, 1, list)); Console.WriteLine("Func2结果:" + Func2(100000000, 1, list)); //a1*x^1 + a2*x2+a3*x^3+....+an*x^n static double Func1(int n,double x, double[] aList) { Stopwatch sw = new Stopwatch(); sw.Start(); double p = aList[0]; for (int i = 1; i <= n-1 ; i++) { p += (aList[i] * Math.Pow(x,i)); } sw.Stop(); Console.WriteLine("func1 耗时" + sw.Elapsed.TotalSeconds); return p; } //等价于a0 + x(a1 + x(a2 + x(a3 + x(...+x(an - 1 + x(an))))) static double Func2(int n, double x, double[] aList) { Stopwatch sw =new Stopwatch(); sw.Start(); double p = aList[n-1]; for (int i = n - 1; i>0; i--) { p = (p*x + aList[i-1]); } sw.Stop(); Console.WriteLine("func2 耗时"+ sw.Elapsed.TotalSeconds); return p; }
如上代码,采用两种不同的算法计算多项式的值,差异如下:第一种方法耗时是第二种方法耗时的五倍左右