/*这是一个基于数组实现的一个简单多项式结构
主要的缺点就是会浪费很大内存空间*/
#include
#include
#include
#define MAX 100
typedef struct node
{
int num[MAX+1];//存储多项式的系数
int high;//存储多项式中次数最高项的次数
}Polymariol;
//把多项式初始化为0
void zero(Polymariol* poly)
{
for(int i=0;i<=MAX;i++)
{
poly->num[i]=0;
}
poly->high=0;
}
//两个多项式相加
void add(const Polymariol* poly1,const Polymariol* poly2,Polymariol* sum)
{
zero(sum);
sum->high = poly1->high > poly2->high ? poly1->high : poly2->high;
for(int i = sum->high;i>=0;i--)
{
sum->num[i] = poly1->num[i] + poly2->num[i];
}
}
//两个多项式相减,前者减去后者
void sub(const Polymariol* poly1,const Polymariol* poly2,Polymariol* res)
{
zero(res);
res->high = poly1->high > poly2->high ? poly1->high : poly2->high;
for(int i = res->high;i>=0;i--)
{
res->num[i] = poly1->num[i] - poly2->num[i];
}
}
//多项式乘法
void multip(const Polymariol* poly1,const Polymariol* poly2,Polymariol* res)
{
zero(res);
res->high = poly1->high + poly2->high;
if(res->high > MAX)
{
printf("Exceded array size\n");
exit(-1);
}
else
{
for(int i = poly1->high;i>=0;i--)
{
for(int j = poly2->high;j>=0;j--)
{
res->num[i+j] += poly1->num[i]*poly2->num[j];
}
}
}
}
//按照一定格式输出多项式
void show(Polymariol* p)
{
for(int x = 0;x<=p->high;x++)
{
if(x==p->high)
printf("%d*X^%d",p->num[x],x);
else
printf("%d*X^%d + ",p->num[x],x);
}
printf("\n");
}
/*
使用两个简单的多项式进行测试
p1 = 1+x1+x2
p2 = 1+x1
p1+p2 = 2 + 2x2 +x2
p2-p1 = 0 + 0 -x2
p2*p1 = 1 + 2x1 + 2x2 +x3
*/
int main(void)
{
Polymariol* p1 = (Polymariol*)malloc(sizeof(struct node));
Polymariol* p2 = (Polymariol*)malloc(sizeof(struct node));
Polymariol* res = (Polymariol*)malloc(sizeof(struct node));
zero(p1);
zero(p2);
zero(res);
p1->high = 2;
for(int a=0;a<=p1->high;a++)
{
p1->num[a]=1;
}
p2->high = 1;
for(int b=0;b<=p2->high;b++)
{
p2->num[b]=1;
}
add(p1,p2,res);
show(res);
zero(res);
sub(p2,p1,res);
show(res);
zero(res);
multip(p1,p2,res);
show(res);
//回收分配的内存空间
free(p1);
free(p2);
free(res);
return 0;
}