I have a Polynomial
class that has a get_vect
member function which stores integers in a vector that is to be the representation of the coefficients of the polynomial. Now, I am trying to multiply two polynomials together using a Multiply
non-member function, but I get stuck when it comes to the actual multiplication of the vectors. So far, what I have is what is shown below:
Polynomial Multiply(const Polynomial & poly1, const Polynomial & poly2)
{
vector<int> Poly1 = poly1.get_vect();
vector<int> Poly2 = poly2.get_vect();
vector<int> Poly3;
if( Poly1.size() < Poly2.size() )
{
for(size_t i = 0 ; Poly2.size()-Poly1.size() ; ++i )
{
Poly2.push_back(0);
}
}
else if( Poly1.size() > Poly2.size() )
{
for(size_t i = 0 ; Poly1.size()-Poly2.size() ; ++i )
{
Poly1.push_back(0);
}
}
return Poly3;
}
I see that it some how has to follow the below pattern:
Ok, so if I understand the problem correctly, you want Poly3
to be a vector<int>
that holds the coefficients that result from a polynomial multiplication between the polynomials represented by Poly1
and Poly2
.
Tacit in this request is that all three polynomials are polynomials in a single variable, with each coefficient representing the coefficient in front of an increasing power of that variable. ie. that { 4, 5, 6, 7 }
corresponds to 4 + 5x + 6x2 + 7x3.
If so, then the actual multiplication shouldn't be that difficult at all, as long as your polynomials aren't terribly huge. You need code that looks approximately like this:
Poly3.resize(Poly1.size() + Poly2.size() - 1, 0); // Make the output big enough; init to 0
for (size_t i = 0; i != Poly1.size(); i++)
for (size_t j = 0; j != Poly2.size(); j++)
Poly3[i+j] += Poly1[i] * Poly2[j];
Now the result in Poly3
should be the product of Poly1
and Poly2
.
It's entirely possible I forgot an edge condition; I'll watch for comments here to point out where I did. In the meantime, though, I did a few tests and it appears this gives the correct output.
If you have rather large polynomials, then you might want to look into math libraries to handle the multiplication. But for anything under about 20 - 30 terms? Unless your code leans very hard on this polynomial evaluation, I suspect this won't be your bottleneck.