Add polynomials, TAD Polynomial, Java

1

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

public interface iPolinomio {

public int getGrado();
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 iPolinomio, I have the following

public class Polinomio implements iPolinomio{

private int grado;  //n
private int[] coeficientes;  //a


public Polinomio(int grado,int[] coeficiente){
    this.grado=coeficiente.length;
    coeficientes = new int[coeficiente.length];
    for (int i=0;i<coeficientes.length;i++){
        this.coeficientes[i]=coeficiente[i];
    }
}
public int getGrado(){
    return this.grado;
}

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){
    int acumulado=coeficientes[0];
    for (int i=1;i<coeficientes.length;i++){
        acumulado+=coeficientes[i]*(int)Math.pow(x, i);
    }
    return acumulado;
}

And here comes the error ... I do not know how I can add it if in the end I have to return an iPolinomio. He tells me he can not convert from int to iPolinomio.

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? Thanks in advance

    
asked by Javi 24.01.2018 в 18:13
source

1 answer

1

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 polynomial coefficients of greater degree.

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

And finally return a new polynomial:

return new Polinomio(grado, coeficientes);
    
answered by 25.01.2018 / 16:23
source