How to use a for loop to add and multiply different items in a list to get the final product of a polynomial

StackOverflow https://stackoverflow.com/questions/20352606

  •  07-08-2022
  •  | 
  •  

Question

I created a empty polynomal arrayList class. I wrote the other methods where i can fill the empty list with terms (3x6 , 5x2, etc...). So now i have to get the product of all the terms in the list. I know i have to multiply the coefficients and add the exponents. So i separated them already in my code. But now i'm stuck i can't recall how to keep the already multiplied terms and save them to multiply the next term. Then the same with adding the exponents. Not entirely sure i need the product variable... Also it doesn't have to be a for loop but i thought it best, maybe a do-while? Help would be appreciated, thanks!

/**
* Returns the product of all the terms of a Polynomial, as a String E.g.
* for the polynomial 3x^2 + 7x^3 + 2x^5, will return 42x^10
* 
* @return the polynomial product, as a String
*/
public String product() {
Term product;

for (int i = 0; i < termSequence.size(); i++) {
    int coeffMultiply = (termSequence.get(i)).getCoefficient();
    int expoMultiply = (termSequence.get(i)).getExponent();
    product = new Term(coeffMultiply, expoMultiply);

}


return ;

}

No correct solution

OTHER TIPS

For simple double values this is a valid solution:

public class PolynomialFunction implements Function {

    private final double[] coefficients;

    public PolynomialFunction(double... coefficients) {
        this.coefficients = coefficients;
    }

    @Override
    public double value(double x) {
        int len = coefficients.length;
        double xPowI = 1;
        double val = 0;

        for (int i = 0; i < len; i++) {
            val += coefficients[len - 1 - i] * xPowI;
            xPowI *= x;
        }

        return val;
    }

}

You should be able to refactor it to your needs.
If it turns out I haven't entirely understood your question, please comment!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top