Reputation: 1723
I'm trying to write multiply 2 polynomials using overloading * operator
This is the overloading * func
Polynomial Polynomial::operator * (const Polynomial &right)
{
Polynomial temp;
temp.setPolynomial(right.maxExp + maxExp + 1);
for (int i = 0; i < maxExp; i++)
{
for (int j = 0; j < right.maxExp; j++)
temp.poly[1][i+j] += poly[0][i] * right.poly[0][j];
}
return temp;
}
The array result, where 1st row is the coefficients and the second row stores the exponents.
The first (original) polynomial is: (degree = 4, F = x^2)
0 0 1 0 0
0 0 2 0 0
The second polynomial is: (degree = 4, F = x^2)
0 0 1 0 0
0 0 2 0 0
The result polynomial is: // the location of the result is right (x^4)
0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 1 0 0 0 0 0 0 0
Polynomial class
class Polynomial
{
private:
int **poly;
int maxExp;
void createPolynomialArray(int);
public:
Polynomial();
Polynomial(int); // constructor
Polynomial(const Polynomial &); // copy constructor
~Polynomial(); // destructor
// setter
void setCoefficient(int,int);
void setPolynomial(int);
// getters
int getTerm() const; // get the maxExp (highest exponent)
int getCoefficient(int,int) const; // get a specific exponential value
// overloading operators
void operator=(const Polynomial &); // assignment
Polynomial operator+(const Polynomial &); // addition
Polynomial operator-(const Polynomial &); // substraction
Polynomial operator*(const Polynomial &);
}
Question: what's wrong with my code that it produces that values? Thanks!
Upvotes: 0
Views: 2828
Reputation: 6565
With this you are updating the result exponent with multiple of coefficients;
temp.poly[1][i+j] += poly[0][i] * right.poly[0][j];
I think the code should be
for (int j = 0; j < right.maxExp; j++)
{
temp.poly[0][i+j] += poly[0][i] * right.poly[0][j];
if (temp.poly[0][i+j] != 0)
temp.poly[1][i+j] = i+j;
}
Also i think in your code storing exponents is redundant information as position in array itself reflects the exponent
Upvotes: 1