-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPolynomial.cpp
More file actions
117 lines (101 loc) · 2.36 KB
/
Polynomial.cpp
File metadata and controls
117 lines (101 loc) · 2.36 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
#include <iostream>
#include <stack>
#include <vector>
#include <utility>
#include <set>
#include <math.h>
using namespace std;
class Term {
friend class Polynomial;
public:
Term(float coef, int exp) {
this->coef = coef;
this->exp = exp;
}
Term() = default;
private:
float coef;
int exp;
};
class Polynomial {
public:
Polynomial() {
this->terms = new Term[2];
this->capacity = 2;
this->max_degree = 0;
this->size = 0;
}
Polynomial(vector < pair<float, int>> vec) {
this->terms = new Term[2];
this->capacity = 2;
this->max_degree = 0;
this->size = 0;
for (int i = 0; i < vec.size(); i++) {
newItem(Term(vec[i].first, vec[i].second));
}
}
//should be added sorted
void newItem(const Term& term) {
if (size == capacity) {
this->capacity *= 2;
Term* temp = new Term[capacity];
copy(terms, terms + size, temp);
delete[] this->terms;
this->terms = temp;
}
this->terms[size] = term;
size++;
}
Polynomial Add(const Polynomial& pol2)
{
Polynomial result;
int a_pos = 0; int b_pos = 0;
while (a_pos < this->size && b_pos < pol2.size) {
if (this->terms[a_pos].exp ==pol2.terms[b_pos].exp) {
float add_result = this->terms[a_pos].coef + pol2.terms[b_pos].coef;
if (add_result)result.newItem({ add_result ,this->terms[a_pos].exp });
a_pos++;
b_pos++;
}
else if (this->terms[a_pos].exp > pol2.terms[b_pos].exp) {
result.newItem({ this->terms[a_pos].coef ,this->terms[a_pos].exp });
a_pos++;
}
else {
result.newItem({ pol2.terms[b_pos].coef ,pol2.terms[b_pos].exp });
b_pos++;
}
}
for (; a_pos < this->size; a_pos++) {
result.newItem({ this->terms[a_pos].coef,this->terms[a_pos].exp });
}
for (; b_pos < this->size; b_pos++) {
result.newItem({ pol2.terms[b_pos].coef,pol2.terms[b_pos].exp });
}
return result;
}
Polynomial operator+(const Polynomial& pol2) {
return Add(pol2);
}
void print() {
for (int i = 0; i < size; i++) {
if (this->terms->coef < 0)
cout << this->terms->coef << "x^" << this->terms[i].exp;
else
cout << '+' << this->terms[i].coef << "x^" << this->terms[i].exp;
}
cout << endl;
}
private:
int capacity;
int max_degree;
int size;
Term* terms;
};
int main() {
Polynomial pol1({ {2, 5}, { 2,3 }, { 5,1 }, { 3,0 } });
Polynomial pol2({ {1, 5}, { 2,2 }, { 4,1 }, { 3,0 } });
pol1.print();
pol2.print();
(pol1 + pol2).print();
}