-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0319Polynomial.cpp
More file actions
86 lines (79 loc) · 2 KB
/
Copy path0319Polynomial.cpp
File metadata and controls
86 lines (79 loc) · 2 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
#include <iostream>
using namespace std;
class Polynomial;
class Term {
friend class Polynomial;
private:
float coef; int exp;
public:
Term(float coef=0, int exp=0): coef(coef), exp(exp) {}
};
class Polynomial {
private:
Term *termArray;
int capacity;
int terms;
public:
Polynomial(Term termArray=NULL,int cap=0,int term=0): termArray(NULL), capacity(cap), terms(term) {}
Polynomial Add(Polynomial poly);
void NewTerm(const float theCoeff, const int theExp);
void print();
};
void Polynomial::NewTerm(const float theCoeff, const int theExp) {
if(terms==capacity)
{
capacity += 4;
Term *start = new Term[capacity]; //new array!
//copy(termArray, termArray+terms, start);
for(int i=0; i<terms; i++) {
start[i] = termArray[i];
delete[] termArray; //dellocate old memory!
termArray = start;
}
termArray[terms].coef=theCoeff;
termArray[terms++].exp=theExp; //why?
}
}
Polynomial Polynomial::Add(Polynomial b) {
Polynomial c;
int aPos=0, bPos=0; //aPos, bPos?
while((aPos<terms)&&(bPos<b.terms))
if((termArray[aPos].exp = b.termArray[bPos].exp)) {
float t = termArray[aPos].coef + b.termArray[bPos].coef;
aPos++; bPos++;
}
else if((termArray[aPos].exp < b.termArray[bPos].exp)) {
c.NewTerm(b.termArray[bPos].coef, b.termArray[bPos].exp);
bPos++;
}
else {
c.NewTerm(termArray[aPos].coef, termArray[aPos].exp);
aPos++;
}
for(int aPos=0; aPos<terms; aPos++)
c.NewTerm(termArray[aPos].coef, termArray[aPos].exp);
for(int bPos=0; bPos<b.terms; bPos++)
c.NewTerm(b.termArray[bPos].coef, b.termArray[bPos].exp);
return c;
}
void Polynomial::print() {
for(int i=0; i<terms; i++) {
if(termArray[i].coef==0) continue;
if(termArray[i].exp==0) cout<<termArray[i].coef;
else if(i==terms-1) cout<<termArray[i].coef<<"x^"<<termArray[i].exp;
else cout<<termArray[i].coef<<"x^"<<termArray[i].exp<<"+";
}
cout<<endl;
}
int main() {
Polynomial a, b, c;
a.NewTerm(5,5);
a.NewTerm(4,4);
a.print();
b.NewTerm(3,3);
b.NewTerm(2,2);
b.NewTerm(1,1);
b.print();
c=a.Add(b);
c.print();
}