0

I am creating a method to multiply 2 polynomial expressions together such that:

3x^5 * 2x^3 = 6x^8 -> Where the coefficients are multiplied and the exponents are added together.

My test case for this would look something like the following

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

I should also add that Term.Zero = (0,0) and Term.Unit = (1,0) So anything multiplied by Term.Zero is Term.Zero and anything multiplied by Term.Unit returns itself as Term.Unit effectively is 1.

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

This is the times method. I'm asking for some help with coding the times method? The problem I've found is how to deal with the 3 Term objects, Term1, Term2 and Term3 and not using an endless amount of if-statements.

matsev
  • 32,104
  • 16
  • 121
  • 156
germainelol
  • 3,231
  • 15
  • 46
  • 82

1 Answers1

0

I have designed the following pseduo code so far:

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

With the following code

@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;
}

But this made me have to change my "coef/expo" variables in the Term class from

final private int coef;

to

private int coef;

And this gives an error on the following test...

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

Any ideas?

germainelol
  • 3,231
  • 15
  • 46
  • 82