Try this:
//if any of the remaining coefficients is more than zero, then print out "+"
for(int j = n-1; j > 0; --j)
if(p.coefficient[j] > 0)
cout << "+";
Assuming degree is the largest exponent in the polynomial associated with a nonzero coeffieient then the degree of the product is the sum of the degrees of the two polynomials being multiplied together. Multiplication involes multiply each term of one polynomial by each term of the other. Each individual product term thus produced has the coefficient of p1.coeff * p2.coeff and the exponent is the sum of p1.exp + p2.exp. Once all of the individual product terms have been generated you can simplify the polynomial by adding the coefficients of each term with the same exponent, or you can simplify as you go by setting the coefficients of each term in the product to zero before you start multiplying terms and add each exponent to the current value of the coefficient of the appropriate term as it is generated. Using a nested loop is probably the most efficient way I know of to generate each of the product terms.
Lerner
Nearly a Posting Maven
2,382 posts since Jul 2005
Reputation Points: 739
Solved Threads: 396
>>poly.cpp(146): error C2679: binary '*' : no operator found which takes a right-hand operand of type 'int' (or there is no acceptable conversion)
You could create a constructor that takes an int and converts it into a polynomial or you could overload the * operator to take a polynomial and an int. But that wouldn't cover you in this case:
polyB = 3 * polyA;
Lerner
Nearly a Posting Maven
2,382 posts since Jul 2005
Reputation Points: 739
Solved Threads: 396
Tweak it a bit. Try putting a break; after finding the first remaining nonzero coefficient to prevent the multiple + signs and changing the starting point for j.
for(int j = degree - 1; j > 0; --j)
{
if(p.coefficient[j] > 0)
{
cout << "+";
break;
}
}
Lerner
Nearly a Posting Maven
2,382 posts since Jul 2005
Reputation Points: 739
Solved Threads: 396
Nah, you don't want to start j at degree either. Must be getting tired, sorry. All right, so try something this.
//assuming p.coefficient contains all coeffients, even if the coefficient is zero.
//for each term in p
for(int n = p.degree; n >= 0; n--)
{
if(p.coefficient[n] != 0)//print only terms with non zero coefficient
{
output << p.coefficient[n];
if(n > 0)
{
if(n > 1)
output << "x^" << n;
else //if n == 1
output << "x";
if(p.coefficient[n - 1] > 0)
output << " + ";
}
}
}
Skip the empty line between the if and the else, must be a tab or something I didn't erase.
Lerner
Nearly a Posting Maven
2,382 posts since Jul 2005
Reputation Points: 739
Solved Threads: 396