c++ - Polynomial Class: Polynomial Multiplication -
i have polynomial
class has get_vect
member function stores integers in vector representation of coefficients of polynomial. now, trying multiply 2 polynomials using multiply
non-member function, stuck when comes actual multiplication of vectors. far, have 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 = 0 ; poly2.size()-poly1.size() ; ++i ) { poly2.push_back(0); } } else if( poly1.size() > poly2.size() ) { for(size_t = 0 ; poly1.size()-poly2.size() ; ++i ) { poly1.push_back(0); } } return poly3; }
i see how has follow below pattern:
ok, if understand problem correctly, want poly3
vector<int>
holds coefficients result polynomial multiplication between polynomials represented poly1
, poly2
.
tacit in request 3 polynomials polynomials in single variable, each coefficient representing coefficient in front of increasing power of variable. ie. { 4, 5, 6, 7 }
corresponds 4 + 5x + 6x2 + 7x3.
if so, actual multiplication shouldn't difficult @ all, long polynomials aren't terribly huge. need code looks approximately this:
poly3.resize(poly1.size() + poly2.size() - 1, 0); // make output big enough; init 0 (size_t = 0; != poly1.size(); i++) (size_t j = 0; j != poly2.size(); j++) poly3[i+j] += poly1[i] * poly2[j];
now result in poly3
should product of poly1
, poly2
.
it's entirely possible forgot edge condition; i'll watch comments here point out did. in meantime, though, did few tests , appears gives correct output.
if have rather large polynomials, might want math libraries handle multiplication. under 20 - 30 terms? unless code leans hard on polynomial evaluation, suspect won't bottleneck.
Comments
Post a Comment