1 votes

Polynomial Addition, TAD Polynomial, Java

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 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 I implement iPolinomial, 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 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());
    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);

HolaDevs.com

HolaDevs is an online community of programmers and software lovers.
You can check other people responses or create a new question if you don't find a solution

Powered by:

X