public class Poly
{
  private int degree;
  private double coeffs[];

  public Poly(double ...c)
  {
    this.degree = c.length - 1;
    this.coeffs = new double[c.length];
    for(int i = 0; i < c.length; i++)
    {
      this.coeffs[i] = c[i];
    }
  }

  public int getDegree()
  {
    return this.degree;
  }

  public double[] getCoeficients()
  {
    double retval[] = new double[this.coeffs.length];
    for(int i = 0; i < this.coeffs.length; i++)
    {
      retval[i] = this.coeffs[i];
    }
    return retval;
  }

  public Poly plus(Poly rhs)
  {
    int retDegree = Math.max(this.degree, rhs.degree);    
    double retCoeffs[] = new double[retDegree+1];
    for(int i = 0; i <= retDegree; i++)
    {
      if(i > this.degree)
      {
        retCoeffs[i] = rhs.coeffs[i];
      }
      else if (i > rhs.degree)
      {
        retCoeffs[i] = this.coeffs[i];
      }
      else
      {
        retCoeffs[i] = this.coeffs[i] + rhs.coeffs[i];
      }
    }
    return new Poly(retCoeffs);
  }

  public Poly minus(Poly rhs)
  {
    int retDegree = Math.max(this.degree, rhs.degree);    
    double retCoeffs[] = new double[retDegree+1];
    for(int i = 0; i <= retDegree; i++)
    {
      if(i > this.degree)
      {
        retCoeffs[i] = -rhs.coeffs[i];
      }
      else if (i > rhs.degree)
      {
        retCoeffs[i] = this.coeffs[i];
      }
      else
      {
        retCoeffs[i] = this.coeffs[i] - rhs.coeffs[i];
      }
    }
    while (retDegree > 0 && retCoeffs[retDegree] == 0.0)
    {
      retDegree--;
    }
    double r[] = new double[retDegree+1];
    for(int i = 0; i <= retDegree; i++)
    {
      r[i] = retCoeffs[i];
    }
    return new Poly(r);
  } 

  public Poly times(Poly rhs)
  {
    int degL = this.degree;
    int degR = rhs.degree;
    int degRet = degL + degR;
    double retCoeff[] = new double[degRet+1];
    
    for(int i = 0; i <= degL; i++)
    {
      for(int j = 0;  j <= degR; j++)
      {
        retCoeff[i+j] += this.coeffs[i] * rhs.coeffs[j];
      }
    }
    return new Poly(retCoeff);
  }
    
  boolean equals(Poly rhs)
  {
    Poly temp = this.minus(rhs);
    if(temp.degree == 0 && temp.coeffs[0] == 0.0)
      return true;
    else
      return false;
  }

  public String toString()
  {
    String retval = "" + coeffs[0];
    for (int i = 1; i  < coeffs.length; i++)
    {
      retval += " + " + coeffs[i] + "*X^" + i;
    }
    return retval;
  }
      









  public static void main(String args[])
  {
    Poly p1 = new Poly(1.0, 2.0);
    Poly p2 = new Poly(1.0, 2.0);
    Poly p3 = new Poly(5.0, 0.0, 0.0, 0.0, 0.0, 2.0); //5 + 2*X^5
    Poly diff = p1.times(p2); // implements p1 + p2
    Poly diff2 = p2.times(p1);
    System.out.println("p1 equals p2?" + p1.equals(p2));
    System.out.println("p1 equals p3?" + p1.equals(p3));

    System.out.println("p1  = " + p1); 
    System.out.println("p2  = " + p2); 
    System.out.println("p1 times p2 is" +  diff); 
    System.out.println("p2 times pl is" +  diff2); 
  }
}
