gpt4 book ai didi

java - 有没有更有效的多项式乘法方法?

转载 作者:行者123 更新时间:2023-11-29 08:03:48 25 4
gpt4 key购买 nike

这是我将两个 an*x^n + an-1*x^n-1 + ... + a1*x + a0 形式的多项式相乘的方法.每个Term对象有两个字段:double coefficientint power . Polynomial通过将项存储在 ArrayList<Term> 中来表示多项式.当前的乘法实现是 O(n^2)。关于如何使其更快的任何想法或提示?

public Polynomial multiply(Polynomial P2) {
PolynomialImp result = new PolynomialImp();
for (Term currentThisTerm : this.terms)
{
for (Term currentP2Term : ((PolynomialImp) P2).terms)
{
result.addTerm(new TermImp(currentThisTerm.getCoefficient()*currentP2Term.getCoefficient(), currentThisTerm.getExponent() + currentP2Term.getExponent()));
}
}
//Sort polynomial in decreasing exponent order
return result.sort();
}

如果需要,下面是 addTerm 方法:

private void addTerm(Term nextTerm)
{
for (int i = 0; i < this.terms.size(); i++)
{
if (this.terms.get(i).getExponent() == nextTerm.getExponent())
{
//Add the coefficients if the current term has the same exponent as a term that is already in the polynomial.
//This preserves the sorting of the polynomial except during multiply.
this.terms.set(i, new TermImp(this.terms.get(i).getCoefficient() + nextTerm.getCoefficient(), this.terms.get(i).getExponent()));
return;
}
}
//Avoid adding zeros to the polynomial.
if (nextTerm.getCoefficient() != 0)
this.terms.add(nextTerm);
}

最佳答案

这就是我实现这个功能的方式

public class Polynomial {
private final double[] coeff;

public Polynomial(double... coeff) {
this.coeff = coeff;
}

@Override
public String toString() {
return Arrays.toString(coeff);
}

public Polynomial multiply(Polynomial polynomial) {
int totalLength = coeff.length + polynomial.coeff.length - 1;
double[] result = new double[totalLength];
for (int i = 0; i < coeff.length; i++)
for (int j = 0; j < polynomial.coeff.length; j++) {
result[i + j] += coeff[i] * polynomial.coeff[j];
}
return new Polynomial(result);
}

public static void main(String... args) {
Polynomial p1 = new Polynomial(1, 2, 3);
System.out.println(p1 + "^2 =" + p1.multiply(p1));
Polynomial p2 = new Polynomial(3, -1, -1);
System.out.println(p1 + "*" + p2 + "=" + p1.multiply(p2));
}
}

打印

[1.0, 2.0, 3.0]^2 =[1.0, 4.0, 10.0, 12.0, 9.0]
[1.0, 2.0, 3.0]*[3.0, -1.0, -1.0]=[3.0, 5.0, 6.0, -5.0, -3.0]

关于java - 有没有更有效的多项式乘法方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12731595/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com