#include<stdio.h>
#include<stdlib.h>
#define Maxdegree 999
struct Polynomial
{
int CoeffArray[Maxdegree+1];
int HighPower;
};
void putin(struct Polynomial *);
void putout(struct Polynomial *);
int Maxhighpower(struct Polynomial *,struct Polynomial *);
void ZeroPolynomial(struct Polynomial *);
void Addpolynomial(struct Polynomial *,struct Polynomial *);
void Subpolynomial(struct Polynomial *, struct Polynomial *);
void Ridepolynomial(struct Polynomial *, struct Polynomial *);
int main()
{
struct Polynomial poly1,poly2;
int choose;
printf("please type the coefficient of i like <i ai>,i is 0 to 999\n\n");
printf("for poly1 stop by EOF\n");
ZeroPolynomial(&poly1);
putin(&poly1);
printf("for poly2 stop by EOF\n");
ZeroPolynomial(&poly2);
putin(&poly2);
printf("\nplease choose a operate:\n1.add\n2.subtract\n3.ride\n");
scanf("%d",&choose);
switch (choose)
{
case 1: Addpolynomial(&poly1,&poly2); break;
case 2: Subpolynomial(&poly1,&poly2); break;
case 3: Ridepolynomial(&poly1,&poly2); break;
}
system("pause");
return 0;
}
void Addpolynomial(struct Polynomial *poly1,struct Polynomial *poly2)
{
int step,highpower;
struct Polynomial polysum;
ZeroPolynomial(&polysum);
highpower=Maxhighpower(poly1,poly2);
polysum. HighPower=highpower;
for(step=highpower;step>-1;step--)
polysum. CoeffArray[step]=
poly1->CoeffArray[step]+
poly2->CoeffArray[step];
putout(&polysum);
}
void Subpolynomial(struct Polynomial *poly1, struct Polynomial *poly2)
{
int step,highpower;
struct Polynomial polysum;
ZeroPolynomial(&polysum);
highpower=Maxhighpower(poly1,poly2);
polysum. HighPower=highpower;
for(step=highpower;step>-1;step--)
polysum. CoeffArray[step]=
poly1->CoeffArray[step]-
poly2->CoeffArray[step];
putout(&polysum);
}
void Ridepolynomial(struct Polynomial *poly1,struct Polynomial *poly2)
{
int step1,step2,highpower;
struct Polynomial polysum;
ZeroPolynomial(&polysum);
polysum.HighPower=poly1->HighPower+poly2->HighPower;
if(polysum.HighPower>Maxdegree)
printf("Exceeded array size!\n");
else
{
for(step1=0;step1<poly1->HighPower+1;step1++)
for(step2=0;step2<poly2->HighPower+1;step2++)
polysum.CoeffArray[step1+step2]+=
poly1->CoeffArray[step1]*
poly2->CoeffArray[step2];
putout(&polysum);
}
}
int Maxhighpower(struct Polynomial *poly1,struct Polynomial *poly2)
{
if(poly1->HighPower>poly2->HighPower)
return poly1->HighPower;
else
return poly2->HighPower;
}
void ZeroPolynomial(struct Polynomial *poly)
{
int step;
for(step=Maxdegree;step>-1;step--)
poly->CoeffArray[step]=0;
}
void putin(struct Polynomial *poly)
{
int i,a;
poly->HighPower=0;
while(scanf("%d%d",&i,&a)!=EOF)
{
poly->CoeffArray[i]=a;
if(poly->HighPower<i)
poly->HighPower=i;
}
}
void putout(struct Polynomial *polyresult)
{
int i;
printf("Result is :\n");
for(i=polyresult->HighPower;i>-1;i--)
if(polyresult->CoeffArray[i]!=0)
printf("%d : %d\n",i,polyresult->CoeffArray[i]);
}