の形式の 2 つの多項式を乗算するための私の方法を次に示しan*x^n + an-1*x^n-1 + ... + a1*x + a0
ます。各Term
オブジェクトには と の 2 つのフィールドが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);
}