0

我正在创建一种将 2 个多项式表达式相乘的方法,这样:

3x^5 * 2x^3 = 6x^8-> 系数相乘,指数相加。

我的测试用例如下所示

@Test
public void times01() throws TError { 
    assertEquals(Term.Zero, Term.Zero.times(Term.Zero)); 
}

我还应该补充一点Term.Zero = (0,0)Term.Unit = (1,0)所以任何乘以Term.ZeroisTerm.Zero和任何乘以Term.Unit返回本身的Term.Unit有效值都是 1。

public Term times(Term that) throws CoefficientOverflow, ExponentOverflow, NegativeExponent {
    return null;
}

这就是times方法。我正在寻求有关编码该times方法的帮助?我发现的问题是如何处理 3 个 Term 对象,Term1Term2不是Term3使用无穷无尽的if-statements.

4

1 回答 1

0

到目前为止,我已经设计了以下伪代码:

Term1 == Term.Zero OR Term2 == Term.Zero => Term3 = Term.Zero
Term1 == Term.Unit => Term3 = Term2
Term2 == Term.Unit => Term3 = Term1

Term1.coef * Term2.coef = Term3.coef
Term1.expo * Term2.expo = Term3.expo

使用以下代码

@SuppressWarnings("null")
public Term times(Term that) throws CoefficientOverflow, ExponentOverflow, NegativeExponent {
    Term term1 = new Term(coef,expo);
    Term term2 = that;
    Term term3 = null;

    if(term1 == Zero || term2 == Zero) {
        term3 = Zero;
    } else if(term1 == Unit) {
        term3 = term2;
    } else if(term2 == Unit) {
        term3 = term1;
    } else if(term1.coef == 2 && term1.expo == 0) {
        term3.coef = term2.coef * 2;
        term3.expo = term2.expo;
    } else if(term2.coef == 2 && term2.expo == 0) {
        term3.coef = term1.coef * 2;
    term3.expo = term1.expo;
    } else {
        term3.coef = term1.coef * term2.coef;
        term3.expo = term1.expo + term2.expo;
    }



    return term3;
}

但这让我不得不将 Term 类中的“coef/expo”变量从

final private int coef;

private int coef;

这会在以下测试中出现错误...

@Test
public void times09() throws TError { assertEquals(new Term(min,2), new Term(hmin,2).times(new Term(2,0))); }

有任何想法吗?

于 2012-11-17T19:58:11.103 回答