计算Pn(x) = an * x^n + an-1 * x^(n-1) + ... + a1 * x + a0
直接计算,需要做的乘法次数 1+2+3+……+n = n(1+n)/2 = O(n2)
使用Horner规则,Pn(x) = ((... ((anx + an-1)x + an-2)x + ... + a2)x + a1)x + a0
需要做的乘法次数 n = O(n)
public class Horner{
public static int compute(int x, int[] A){
//计算Pn(x) = an * x^n + an-1 * x^(n-1) + ... + a1 * x + a0
int result = A[A.length-1];
for(int i = A.length-2; i >= 0; i --){
result = x*result + A[i];
}
return result;
}
public static void main(String[] args){
//单元测试。取 ai = 2^n-i;n为10。答案应为1024 * 11 = 11264
int x = 2;
final int N = 10;
int[] A = new int[N+1];
int tmp = 1024;
for(int i = 0; i < A.length; i ++){
A[i] = tmp;
tmp /= 2;
}
System.out.println(compute(x, A));
}
}
Java