#include<iostream>
using namespace std;
class polynomial;
class term
{
private:
friend class polynomial;
float coef;
int exp;
};
class polynomial
{
term *termarry;
int capacity,terms;
public:
polynomial();
void display(int);
void add(polynomial);
void newterm(float,int);
};
polynomial::polynomial()
{
capacity=1;
terms=0;
termarry=new term[capacity];
}
void polynomial::newterm(float coef,int ex)
{
if(terms==capacity)
{
capacity*=2;
term *temp=new term[capacity];
copy(termarry,termarry+terms,temp);
termarry=temp;
delete temp;
}
termarry[terms].coef=coef;
termarry[terms++].exp=ex;
}
void polynomial:: add(polynomial b)
{
polynomial c;
int apos=0,bpos=0,cpos=0;
if(termarry[apos].exp==termarry[bpos].exp)
{
float t=(termarry[apos].coef)+(termarry[bpos].coef);
c.newterm(t,termarry[apos].exp);
apos++; bpos++;cpos++;
}
else if(termarry[apos].exp<b.termarry[bpos].exp)
{
c.newterm(b.termarry[bpos].coef,b.termarry[bpos].exp);
bpos++;cpos++;
}
else
{
c.newterm(termarry[apos].coef,termarry[apos].exp);
apos++;
cpos++;
}
for(;apos<terms;apos++)
{
c.newterm(termarry[apos].coef,termarry[apos].exp);
cpos++;
}
for(;bpos<b.terms;bpos++)
{
c.newterm(b.termarry[bpos].coef,b.termarry[bpos].exp);
cpos++;
}
c.display(cpos);
}
void polynomial::display(int pos)
{
int i;
for(i=0;i<pos;i++)
{
cout<<termarry[i].coef<<" "<<termarry[i].exp<<"+";
}
}
int main()
{
polynomial a,b;
float coef1,coef2;
int e1=0,e2=0,l1,l2;
cout<<"Enter lowest deg: ";
cin>>l1;
cout<<"\nEnter first polynomial: ";
while(1)
{
cin>>coef1>>e1;
a.newterm(coef1,e1);
if(e1==l1)
break;
}
cout<<"Enter lowest deg: ";
cin>>l2;
cout<<"\nEnter second polynomial: ";
while(1)
{
cin>>coef2>>e2;
b.newterm(coef2,e2);
if(e2==l2)
break;
}
cout<<"\nPolynomial after addition: \n";
a.add(b);
return 0;
}
I2luY2x1ZGU8aW9zdHJlYW0+CiB1c2luZyBuYW1lc3BhY2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