Hello can you help me to create the sum method to add two polynomials. Given a polynomial P(x)=a0+a1x+a2x2+a3x3+ +anxn , I have an iPolynomial interface (which is given in the exercise and I can not modify), which is the following

``````public interface iPolinomio {

public int getCoeficiente(int n);

public void setCoeficiente(int n, int newValue);
public int calcularValor(int x);

public iPolinomio suma (iPolinomio p);

}``````

Now in the Polynomial class I implement iPolinomial, I have the following

``````public class Polinomio implements iPolinomio{

private int[] coeficientes;  //a

coeficientes = new int[coeficiente.length];
for (int i=0;i<coeficientes.length;i++){
this.coeficientes[i]=coeficiente[i];
}
}
}

public int getCoeficiente(int n){  //n es grado
int numero = this.coeficientes[n];
return numero;
}

public void setCoeficiente(int n, int newValue){
this.coeficientes[n]=newValue;
}

public int calcularValor(int x){
for (int i=1;i<coeficientes.length;i++){
}
}``````

And here comes the error... I don't know how I can add it if at the end I have to return an iPolinomial. It tells me that it cannot convert from int to iPolinomial.

``````public iPolinomio suma (iPolinomio p){
iPolinomio suma = null;
for (int i=0;i<this.coeficientes.length;i++){
suma = this.getCoeficiente(i) + p.getCoeficiente(i);
}
return suma;
}
}``````

What should I do? Thank you in advance

1voto

Klaimmore Points 3568

With an example:

P1(x) = `a + b*x + c*x^2`

P2(x) = `d + e*x^2 + f*x^3`

When you add 2 polynomials you must add the coefficients of equal degree:

P1(x) + P2(x) = `(a+d) + (b+0)*x + (c+e)*x^2 + (0+f)*x^3`

Then in the code, you should instantiate a new array of sufficient size to store the coefficients of the higher degree polynomial.

``````    int grado = Math.max(this.getGrado(), p.getGrado());
for (int i=0; i <= grado; i++){
coeficientes[i] += this.getCoeficiente(i);
coeficientes[i] += p.getCoeficiente(i);
}``````

And finally return a new polynomial:

``return new Polinomio(grado, coeficientes);``