I'm trying to multiply two polynomials together in C++. I'd like to keep the overal structure of this code as-is if possible. I understand there may be a "faster way." Here is my code for polynomial addition:
Polynomial Add(Polynomial &poly1, Polynomial &poly2)
{
vector<int> temp1;
if( poly1.Degree() > poly2.Degree() )
{
for( int i = 0 ; i<poly2.Degree() ; i++ )
{
temp1[i]=poly1.Coefficient(i)+poly2.Coefficient(i);
}
Polynomial temp0(temp1);
return temp0;
}
else if ( poly1.Degree() < poly2.Degree() )
{
for( int i = 0 ; i<poly1.Degree() ; i++ )
{
temp1[i]=poly1.Coefficient(i)+poly2.Coefficient(i);
}
Polynomial temp0(temp1);
return temp0;
}
}
Here is my Degree() member function definition:
int Polynomial::Degree() const
{
for(int i = 0; i < coefficient.size(); i++)
{
int last=0;
if(coefficient[i] != 0)
{
last = i;
}
return last;
}
}
Here is my Polynomial class declaration:
class Polynomial {
public:
Polynomial();
Polynomial(vector<int> &coeffs);
int Degree() const;
int Coefficient(int k) const;
void print() const;
void constantMultiply(int x);
void Transform();
int nonzero() const;
private:
vector<int> coefficient;
};
Now, what I'm trying to do is multiply two input polynomials using this addition function, and I feel that I could use the below literature from Cohn's Classic Algebra to do the trick with some sufficient thought.
I think this should do what you're looking for. If poly1 has a coefficient for degree i then we iterate over poly2's coeffecients. Each coefficient of poly2 is multiplied and the result will be degree i+j, like x^1*x^2=x^(1+2)=x^3.
Polynomial Mul(Polynomial &poly1, Polynomial &poly2)
{
vector<int> temp1;
for( int i = 0; i<poly1.Degree() ; i++ ){
if(poly1.Coefficient[i] != 0){
for( int j = 0; j<poly2.Degree() ; j++ ){
if(poly2.Coefficient[j] != 0){
temp1[i+j] = poly1.Coefficient(i)*poly2.Coefficient(j);
}
}
}
}
Polynomial temp0(temp1);
return temp0;
}
Please let me know if I'm missing the question, or if this doesn't solve it for you!
Your temp[i]
won't work. I checked. You'll need to do push_back
or some such operation to fill it. It will work if you already know the size of the larger polynomial.
Something like this:
int how_big;
if(poly1.Degree()>poly2.Degree())
{
how_big = poly1.Degree()+1;
}
else
{
how_big = poly2.Degree()+1;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.