/* Program to Perform Operations on Polynomials. This Program will take two polynomials as input and perform required addition/ multiplication operation */
#include<iostream.h>
#include<process.h>
template<class T>
class Poly
{
int degree;
T *coeff;
public:
Poly () { }
Poly(int n) { degree=n; coeff=new T[n+1]; }
void readPoly();
void printPoly();
void zeroPoly();
Poly * addPoly(Poly *, Poly *);
Poly * mulPoly(Poly *, Poly *);
};
template<class T>
void Poly<T> :: readPoly()
{
zeroPoly();
for(int i=degree;i>=0;i--)
{
cout<<"\n Enter the coefficient of X ^"<<i<<" : ";
cin>>coeff[i];
}
}
template<class T>
void Poly<T>:: printPoly()
{
cout<<"\n Polynomial is : \n";
for(int i=degree;i>=0;i--)
{
if(i>0) { cout<<coeff[i]<<" x^"<<i<<" + "; }
else { cout<<coeff[i]; }
}
}
template<class T>
void Poly<T> :: zeroPoly()
{
for(int i=degree;i>=0;i--){ coeff[i]=0; }
}
template<class T>
Poly<T> * Poly<T> :: addPoly(Poly *f, Poly *s)
{
int resDegree;
resDegree= (f->degree>s->degree)?f->degree:s->degree;
Poly *r;
r=new Poly(resDegree);
r->zeroPoly();
cout<<"\n Degree of resultent polynomial is:"<<r->degree;
for(int i=r->degree;i>=0;i--)
{
if((i<=f->degree)&&(i<=s->degree))
{
r->coeff[i]=f->coeff[i]+s->coeff[i];
}
else if(i<=f->degree)
{
r->coeff[i]=f->coeff[i];
}
else { r->coeff[i]=s->coeff[i]; }
}
return r;
}
template<class T>
Poly<T> *Poly<T> :: mulPoly(Poly *f, Poly *s)
{
int n;
n=f->degree+s->degree;
Poly *r;
r=new Poly(n);
r->zeroPoly();
int i,j, k;
for(i=f->degree; i>=0;i--)
{
for(j=s->degree; j>=0;j--)
{
k=i+j;
r->coeff[k]=r->coeff[k]+f->coeff[i]*s->coeff[j];
}
}
return r;
}
void main()
{
int poly1_Degree, poly2_Degree;
cout<<"\n Enter degree of Polynomial 1:";
cin>>poly1_Degree;
Poly <float>p1(poly1_Degree);
p1.readPoly();
p1.printPoly();
cout<<"\n Enter degree of Polynomial 2:";
cin>>poly2_Degree;
Poly <float>p2(poly2_Degree);
p2.readPoly();
p2.printPoly();
int ch;
while(1)
{
cout<<"\n Enter \n1.Addition\n2.Multiplication\n3.Exit\n Enter Your Choice:";
cin>>ch;
Poly <float> *p3;
switch(ch)
{
case 1: p3=p3->addPoly(&p1, &p2); break;
case 2: p3=p3->mulPoly(&p1, &p2); break;
case 3: exit(1);
default: cout<<"\n Enter Right Choice";
}
p3->printPoly();
}
}