-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy path01-Polynomial.c
More file actions
131 lines (110 loc) · 2.19 KB
/
01-Polynomial.c
File metadata and controls
131 lines (110 loc) · 2.19 KB
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
//Polynomial addition
#include <stdio.h>
#define size 100
struct polynomial
{
int coef, exp;
}term[size], temp;
int readPoly(int n)
{
static int x=-1;
for(int k=0;k<n;k++)
{
x++;
scanf("%d %d", &term[x].coef, &term[x].exp);
}
return x;
}
void sort(int first, int last)
{
for(int i=first; i<last; i++)
for(int j=first+1; j<=last; j++)
if(term[j].exp>term[j-1].exp)
{
temp=term[j];
term[j]=term[j-1];
term[j-1]=temp;
}
}
void displayPoly(int first, int last)
{
for(int i=first; i<last; i++)
printf("%dx^%d + ",term[i].coef,term[i].exp);
printf("%dx^%d\n",term[last].coef,term[last].exp);
}
int addPoly(int af, int al, int bf, int bl, int cf)
{
int p, q, sum, cl, free;
p=af;
q=bf;
free=cf;
while((p<=al) && (q<=bl))
{
sum=0;
if(term[p].exp==term[q].exp)
{
sum=term[p].coef+term[q].coef;
if(sum!=0)
free=newterm(sum, term[p].exp, free);
p++;
q++;
}
else if(term[p].exp<term[q].exp)
{
free=newterm(term[q].coef, term[q].exp, free);
q++;
}
else if(term[p].exp>term[q].exp)
{
free=newterm(term[p].coef, term[p].exp, free);
p++;
}
}
if(p<=al)
{
free=newterm(term[p].coef, term[p].exp, free);
p++;
}
if(q<=bl)
{
free=newterm(term[q].coef, term[q].exp, free);
}
cl=free-1;
return cl;
}
int newterm(int coef, int exp, int free)
{
if(free>=size)
printf("Array overflow");
else
{
term[free].coef=coef;
term[free].exp=exp;
free++;
}
return free;
}
void main()
{
int af=0, al, bf, bl, cf, cl, n1, n2;
printf("Enter the number of terms in first polynomial\n");
scanf("%d", &n1);
printf("\nEnter the first polynomial\n");
al=readPoly(n1);
bf=al+1;
sort(af, al);
printf("\nEnter the number of terms in second polynomial\n");
scanf("%d", &n2);
printf("\nEnter the second polynomial\n");
bl=readPoly(n2);
cf=bl+1;
sort(bf, bl);
cl=addPoly(af, al, bf, bl, cf);
sort(cf, cl);
printf("\nFirst polynomial:\n");
displayPoly(af, al);
printf("\nSecond polynomial:\n");
displayPoly(bf, bl);
printf("\nSum of the two polynomials:\n");
displayPoly(cf, cl);
}