我需要增强蛮力多项式评估算法。我收到 x 的最高次幂(n 的值),多项式(a,b,c,..)所有元素的系数值作为整数数组列表。但是我不能在 java 上应用这个算法: f(x) = ax^n + bx^(n-1) + cx^(n-3)+... + z 如何在 java 上应用这个多项式?它的算法是什么?有帮助吗?
package brute.force;
import java.util.*;
import java.util.Scanner;
public class BruteForce {
public static void main(String[] args) {
Scanner scan = new Scanner (System.in);
ArrayList<Integer> coefficients = new ArrayList<>();
int powerOfX, x;
System.out.print("Enter integers please ");
System.out.println("(EOF or non-integer to terminate): ");
while(scan.hasNextInt()){
coefficients.add(scan.nextInt());
}
Integer [] nums = coefficients.toArray(new Integer[0]);
for(int i = 0; i < nums.length; i++){
System.out.println(nums[i]);
}
}
}
最佳答案
您需要使用以下迭代来计算它:
double result = 0;
Integer [] nums = coefficients.toArray(new Integer[0]);
for(int i = 0; i < nums.length; i++){
result = result *x + nums[i];
}
System.out.println(result);
它被称为Horner 方法。 这种方法的好处例如四次多项式是:
f(x) = ax^3 + bx^2 + cx + z
转换为:
f(x) = ((a)*x + b)*x + c)*x + z
关于java - Java中的蛮力多项式算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20286573/