这是我将形式的两个多项式相乘的方法an*x^n + an-1*x^n-1 + ... + a1*x + a0
。每个Term
对象都有两个字段:double coefficient
和int 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);
}