-
Notifications
You must be signed in to change notification settings - Fork 0
/
Polynomial_Addition.cpp
87 lines (81 loc) · 2.12 KB
/
Polynomial_Addition.cpp
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
#include <iostream>
using namespace std;
struct Node
{
int coeff, exp;
Node *next = nullptr;
};
int main()
{
system("cls");
Node *p1 = NULL, *p2 = NULL, *p = NULL;
int n1, n2;
cout << "Enter the number of terms in the first polynomial: ";
cin >> n1;
cout << "Enter the number of terms in the second polynomial: ";
cin >> n2;
cout << "\nEnter coefficient and exponent of each term of first polynomial:\n";
for (int i = 0; i < n1; i++)
{
int coeff, exp;
cin >> coeff >> exp;
Node *temp = new Node{coeff, exp};
temp->next = p1;
p1 = temp; // p1 bhaneko polynomial 1 ko head
}
cout << "\nEnter coefficient and exponent of each term of second polynomial:\n";
for (int i = 0; i < n2; i++)
{
int coeff, exp;
cin >> coeff >> exp;
Node *temp = new Node{coeff, exp};
temp->next = p2;
p2 = temp; // p2 = polynomial 2 ko head
}
while (p1 && p2)
{
if (p1->exp == p2->exp)
{
Node *temp = new Node{p1->coeff + p2->coeff, p1->exp};
temp->next = p;
p = temp; // p = result polynomial ko head
p1 = p1->next;
p2 = p2->next;
}
else if (p1->exp > p2->exp)
{
Node *temp = new Node{p1->coeff, p1->exp};
temp->next = p;
p = temp;
p1 = p1->next;
}
else if (p1->exp < p2->exp)
{
Node *temp = new Node{p2->coeff, p2->exp};
temp->next = p;
p = temp;
p2 = p2->next;
}
}
while (p1)
{
Node *temp = new Node{p1->coeff, p1->exp};
temp->next = p;
p = temp;
p1 = p1->next;
}
while (p2)
{
Node *temp = new Node{p2->coeff, p2->exp};
temp->next = p;
p = temp;
p2 = p2->next;
}
cout << "The Added Polynomial is:\n";
while (p != NULL)
{
cout << p->coeff << "x^" << p->exp << " + ";
p = p->next;
}
return 0;
}