-
Notifications
You must be signed in to change notification settings - Fork 0
/
polynom.cpp
83 lines (74 loc) · 1.68 KB
/
polynom.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
#include "polynom.h"
#include <math.h>
Polynom::Polynom(vector<int> v) {
if (v.empty())
throw runtime_error("Leere Initialisierungsliste nicht erlaubt!");
if (v.at(v.size()-1)==0)
throw runtime_error("Leitindex 0 nicht erlaubt!");
this->v = v;
}
int Polynom::wert(int n) const {
int a; int w = 0;
for (int e = (static_cast<int>(this->v.size())-1); e > -1; e--) {
a = this->v.at(static_cast<size_t>(e));
int z = pow(n, e);
z = z * a;
w += z;
}
return w;
}
int Polynom::grad() const {
return int(this->v.size())-1;
}
ostream& Polynom::print(ostream& o) const {
for (int i = (int(this->v.size())-1); i > -1; i--) {
o << this->v.at(static_cast<size_t>(i)) << "x^" << i;
if (i!=0)
o << "+";
}
return o;
}
ostream& Polynom::print_fmt(ostream& o) const {
bool first = true;
for (int e = (static_cast<int>(this->v.size())-1); e > -1; e--) {
int a = this->v.at(static_cast<size_t>(e));
if (a != 0) {
if (first) {
if ((a < -1) || (a > 1)) {
o << a;
} else if (a == -1) {
o << '-';
}
}
if ((!first)) {
if (a > 1) {
o << '+' << a;
} else if (a < -1) {
o << a;
} else if (a == 1) {
if (e == 0) {
o << "+1";
} else {
o << '+';
}
} else if (a == -1) {
if (e == 0) {
o << "-1";
} else {
o << '-';
}
}
}
if (e > 1) {
o << "x^" << e;
} else if (e == 1) {
o << 'x';
}
first = false;
}
}
return o;
}
ostream& operator<<(ostream& o, const Polynom& p) {
return p.print(o);
}