Polynomial Multiplication
#include
#include
#include
struct Node
{
int c,e;
struct Node *next;
}*head1=NULL,*head2=NULL,*head3=NULL;
void readPoly1()
{
struct Node
*temp,*temp1;
int ch=1;
while(ch!=0)
{
temp=(struct
Node *)malloc(sizeof(struct Node));
printf("\nEnter
the Coefficient:");
scanf("%d",&temp->c);
printf("\nEnter
the Exponent:");
scanf("%d",&temp->e);
temp->next=NULL;
if(head1==NULL)
{
head1=temp;
}
else
{
temp1=head1;
while(temp1->next!=NULL)
temp1=temp1->next;
temp1->next=temp;
}
printf("\nDo
you want to create a new node(0/1)");
fflush(stdin);
scanf("%d",&ch);
}
}
void readPoly2()
{
struct Node
*temp,*temp1;
int ch=1;
while(ch!=0)
{
temp=(struct
Node *)malloc(sizeof(struct Node));
printf("\nEnter
the Coefficient:");
scanf("%d",&temp->c);
printf("\nEnter
the Exponent:");
scanf("%d",&temp->e);
temp->next=NULL;
if(head2==NULL)
{
head2=temp;
}
else
{
temp1=head2;
while(temp1->next!=NULL)
temp1=temp1->next;
temp1->next=temp;
}
printf("\nDo
you want to create a new node(0/1)");
fflush(stdin);
scanf("%d",&ch);
}
}
void multiply()
{
struct Node
*p,*q,*temp,*last,*temp1;
int c,e;
p=head1;
q=head2;
while(p!=NULL)
{
temp1=q;
while(temp1!=NULL)
{
c=p->c*temp1->c;
e=p->e+temp1->e;
if(head3==NULL)
{
temp=(struct
Node *)malloc(sizeof(struct Node));
temp->c=c;
temp->e=e;
temp->next=NULL;
head3=temp;
last=head3;
}
else
{
temp=(struct
Node *)malloc(sizeof(struct Node));
temp->c=c;
temp->e=e;
temp->next=NULL;
last->next=temp;
last=temp;
}
temp1=temp1->next;
}
p=p->next;
}
}
void deleteEqualExponentTerms()
{
struct Node *i,*j,*prevNode;
for(i=head3;i!=NULL;i=i->next){
prevNode=i;
for(j=i->next;j!=NULL;j=j->next){
if(i->e==j->e){
prevNode->c=prevNode->c+j->c;
prevNode->next=prevNode->next->next;
}
prevNode=j;
}
}
}
void traverse(struct Node *ptr)
{
while(ptr!=NULL)
{
printf("
%dX%d+",ptr->c,ptr->e);
ptr=ptr->next;
}
}
int main()
{
printf("first
poly");
readPoly1();
printf("\n\n");
printf("\nP=");
traverse(head1);
printf("second
poly");
readPoly2();
printf("\nQ=");
traverse(head2);
printf("\n*******************************");
multiply();
deleteEqualExponentTerms();
printf("\nR=");
traverse(head3);
printf("\n");
getch();
}
Output:
first poly
Enter the Coefficient:10
Enter the Exponent:3
Do you want to create a new node(0/1)1
Enter the Coefficient:2
Enter the Exponent:2
Do you want to create a new node(0/1)1
Enter the Coefficient:3
Enter the Exponent:1
Do you want to create a new node(0/1)0
P= 10X3+ 2X2+ 3X1+second poly
Enter the Coefficient:4
Enter the Exponent:2
Do you want to create a new node(0/1)1
Enter the Coefficient:2
Enter the Exponent:1
Do you want to create a new node(0/1)0
Q= 4X2+ 2X1+
*******************************
R= 40X5+ 28X4+ 16X3+ 6X2+
0 comments:
Post a Comment