Click here to Skip to main content
Sign Up to vote bad
good
See more: C
i performed polynomial multiplication.but the results contains more than one node with same degree.
 
eg:(4x^3+2x^2+1)(2x^2+2) -> 8x^5 +8x^3 +4x^4 +4x^2 + 2x^2 +2
but i want the result as -> 8x^5 +8x^3 +4x^4 +6x^2 + 2 (ie to sum the nodes with same degree).
 

For that i coded as below.it performs well for smaller expressions.but when i give the expression above as input it produces the result as
8x^5 +8x^3 +4x^4 +6x^2
 
The last element is not displaying.i again and again corrected the for loop limits.but that doesn't help.why the last element not displaying?somebody plz help.......
 
/*startmul points to multiplied result linked list.startaddmul is for the final linked list*/
for(tempmul=startmul;tempmul!=NULL;tempmul=tempmul->next)
{
  if(startaddmul==NULL)
  {
    newnode=malloc(sizeof(struct node));
    newnode->coef=tempmul->coef;
    newnode->deg=tempmul->deg;
    newnode->next=NULL;
    startaddmul=newnode;
  }
  else
  {
    for(temp=startaddmul;temp!=NULL;temp=temp->next)
    {
      if(temp->deg==tempmul->deg)
      {
        temp->coef+=tempmul->coef;
        flag=1;
      }
    }
    if(flag!=1)
    {
      for(temp=startaddmul;temp->next!=NULL;temp=temp->next)
        ;
      newnode=malloc(sizeof(struct node));
      newnode->coef=tempmul->coef;
      newnode->deg=tempmul->deg;
      newnode->next=NULL;
      temp->next=newnode;
    }
  }
}
}
 
Edit: formatted code - Avi Berger
Posted 2-Mar-10 5:11am
Edited 2-Mar-10 11:16am


1 solution

Hi your code is write. You made a small logical mistake.. You forget to clear flag. I tried your code as it is with resenting flag. It was working good.
 
if(flag!=1)
    {
      for(temp=startaddmul;temp->next!=NULL;temp=temp->next)
        ;
      newnode=malloc(sizeof(struct node));
      newnode->coef=tempmul->coef;
      newnode->deg=tempmul->deg;
      newnode->next=NULL;
      temp->next=newnode;
    }
else
{
    flag = 0;
}
  Permalink  

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Your Filters
Interested
Ignored
     
0 Sergey Alexandrovich Kryukov 6,959
1 Prasad_Kulkarni 3,671
2 OriginalGriff 3,359
3 _Amy 3,332
4 CPallini 2,925


Advertise | Privacy | Mobile
Web04 | 2.6.130617.1 | Last Updated 4 Mar 2010
Copyright © CodeProject, 1999-2013
All Rights Reserved. Terms of Use
Layout: fixed | fluid