题目:霍纳规则的正确性:
写出伪代码以实现朴素多项式求值(native polynomial-evaluation)算法,它从头开
始计算多项式的每一个项。这个算法的运行时间是多少?与霍纳规则相比其性能如何?
我用Java代码将其实现如下:
首先,写出一个计算次方值的方法
/**
* 计算次方值
* @param a 底数
* @param b 指数
* @return
*/
public static double pow(double a, double b) {
double ret = a;
if ( b == 0 )
return 1;
for (int i = 1; i < b; i++)
ret = ret * a;
return ret;
}
其时间复杂度显而易见为Θ(b)。
利用分治策略,我们还可以减小其时间复杂度,代码如下:
/**
* 计算次方值 递归版本
* @param a 底数
* @param b 指数
* @return
*/
public static double recursivePow(double a, int b) {
if ( b == 0 )
return 1;
if ( b == 1 )
return a;
//b为偶数
if ( b % 2 == 0 ) {
int mi = b / 2;
double temp = recursivePow(a,mi);
return temp * temp;
} else { //b为奇数
int mi = (int) b / 2;
double temp = recursivePow(a,mi);
return temp * temp * a;
}
}
我们可以写出其递归式T(n) = T(n/2) + Θ(1),根据主方法可得其时间复杂度Θ(logb)
main方法如下:
public static void main(String[] args) {
double[] coefficient = { 1, 2, 34, 2, 56, 7, 8 };
double x = 5;
double result = 0;
for (int i = 0; i < coefficient.length; i++)
result += coefficient[i] * pow(x, i);
System.out.println(result);
}
所以用朴素多项式求值(native polynomial-evaluation)算法,采用计算次方值的递归版本,其所用时间为O(nlogn);另一种版本的时间复杂度为O(n^2)
利用霍纳规则求解方法如下:
/**
* 霍纳规则
*/
public static double horner(double[] coefficient, double x) {
double y = 0;
for (int i = coefficient.length - 1; i >= 0; i--)
y = coefficient[i] + x * y;
return y;
}
所以用霍纳规则求解所需时间复杂度为O(n)。