Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
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
v3

1 solution

Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

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.
 
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  
v2

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

  Print Answers RSS
0 Maciej Los 245
1 OriginalGriff 210
2 Manfred R. Bihy 190
3 CHill60 180
4 _Amy 155
0 OriginalGriff 7,445
1 Sergey Alexandrovich Kryukov 6,157
2 Maciej Los 3,774
3 Peter Leow 3,448
4 CHill60 2,702


Advertise | Privacy | Mobile
Web03 | 2.8.140721.1 | Last Updated 24 Dec 2013
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100