Saturday, September 3, 2011

Multiply two Polynomial


/* Multiply two Polynomial */
#include <stdio.h>
#include <stdlib.h>

typedef struct node
 { int power;
   float coeff;
   struct  node *next;
 }node;
 node * insert(node *head,int power,float coeff);
 node * create();
 node * pmul(node *head1,node *head2);
 void print(node *head);
 int main()
 {
node *head1,*head2,*head3;
int op;
float value,x;
printf("\nEnter 1st polynomial :\n");
head1=create();
printf("\nEnter 2nd polynomial :\n");
head2=create();
// print(head1);
// print(head2);
// multiply
 head3=pmul(head1,head2);
 print(head3);

 }
 node * insert(node *head,int power,float coeff)
  {  node *p,*q;
     /*terms are stored in increasing order of power*/
     /*pointer is used to locate the correct place of insertion.
       pointer p is used to store the address of the node created for
       the current term*/
     p=(node*)malloc(sizeof(node));
     p->power=power;p->coeff=coeff;
     p->next=NULL;
     if(head==NULL)
       return(p);
     else
      if(power<head->power)
{ p->next=head;
 return(p);
}
      else
       { q=head;
while(q->next!=NULL && power>=q->next->power)
  q=q->next;
p->next=q->next;
q->next=p;
    /*if the node pointed by p and q have same power,merge two nodes*/
if(q->power==p->power)
  { q->coeff=q->coeff+p->coeff;
    q->next=p->next;
    free(p);
  }
return(head);
}
  }
 node * create()
 { int n,i,power;
   float coeff;
   node *head;
   head=NULL;
   printf("\nEnter No. of Terms:");
   scanf("%d",&n);
   printf("\nenter a term as a tuple of (power,coefficient)");
   for(i=1;i<=n;i++)
    { scanf("%d%f",&power,&coeff);
      head=insert(head,power,coeff);
    }
   return(head);
 }


 node * pmul(node *head1,node *head2)
 {    node *head,*p;
      head=NULL;
      while(head2 !=NULL)
       {
for(p=head1;p!=NULL;p=p->next)
 head=insert(head,p->power+head2->power,p->coeff * head2->coeff);
head2=head2->next;
       }
 return(head);
 }
 void print(node *head)
 {  printf("\n");
    while(head!=NULL)
     {
      printf("%6.2fX^%d  ",head->coeff,head->power);
      head=head->next;
    }
 }

No comments:

Post a Comment