-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpolynomial multiplication
89 lines (87 loc) · 1.94 KB
/
polynomial multiplication
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
#include<stdio.h>
#include<stdlib.h>
struct node
{
int coeff,power;
struct node* next;
};
function to add new node at the end of list
struct node* addnode(struct node* start,int coeff,int power)
{
struct node* newnode=(struct node*)malloc(sizeof(struct node));
newnode->coeff=coeff;
newnode->power=power;
newnode->next=NULL;
struct node *ptr=start;
while(ptr->next!=NULL)
{
ptr=ptr->next;
}
ptr->next=newnode;
return start;
}
void printlist(struct node *ptr)
{
while(ptr!=NULL)
{
printf("%d x^ %d +",ptr->coeff,ptr->power);
ptr=ptr->next;
}
printf("%d",ptr->coeff);
}
void removeduplicates(struct node* start)
{
struct node* ptr1,*ptr2,*dup;
ptr1=start;
while(ptr1!=NULL&&ptr1->next!=NULL)
{ptr2=ptr1;
while(ptr2->next!=NULL)
{
if (ptr1->power==ptr2->next->power)
{
ptr1->coeff=ptr1->coeff+ptr2->next->coeff;
dup=ptr2->next;
ptr2->next=ptr2->next->next;
free(dup);
}
else
ptr2=ptr2->next;
}
ptr1=ptr1->next;
}
}
struct node* multiply(struct node *poly1,struct node *poly2,struct node *poly3)
{
struct node *ptr1,*ptr2;
ptr1=poly1;
ptr2=poly2;
while(ptr1!=NULL)
{
while(ptr2!=NULL)
{
int coeff,power;
coeff=ptr1->coeff * ptr2->coeff;
power=ptr1->power+ptr2->power;
poly3=addnode(poly3,coeff,power);
ptr2=ptr2->next;
}
ptr2=poly2;
ptr1=ptr1->next;
}
removeduplicates(poly3);
return poly3;
}
int main()
{
struct node *poly1=NULL,*poly2=NULL,*poly3=NULL;
poly1=addnode(poly1,3,2);
poly1=addnode(poly1,5,1);
poly1=addnode(poly1,6,0);
poly2=addnode(poly2,6,1);
poly2=addnode(poly2,9,0);
printlist(poly1);
printlist(poly2);
poly3=multiply(poly1,poly2,poly3);
printlist(poly3);
return 0;
}