Click here to Skip to main content
15,881,744 members
Please Sign up or sign in to vote.
5.00/5 (3 votes)
See more:
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
Updated 2-Mar-10 11:16am
v3

1 solution

Hi your code is right. You made a small logical mistake.. You forget to clear flag. I tried your code as it is with flag reset. It worked well.

C#
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;
}
 
Share this answer
 
v2

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900