Repository navigation
Expand file tree
/
Copy pathPolynomial.java
More file actions
155 lines (124 loc) · 2.36 KB
/
Copy pathPolynomial.java
File metadata and controls
155 lines (124 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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
import java.util.LinkedList;
import java.util.ListIterator;
public class Polynomial
{
private LinkedList<Term> poly;
public Polynomial()
{
poly = new LinkedList<Term>();
}
public void addTerm(int co, int po)
{
poly.addLast(new Term(co,po));
}
public void print()
{
ListIterator<Term> iter = poly.listIterator();
while(iter.hasNext())
{
Term t=iter.next();
System.out.print(t);
}
System.out.println(" ");
}
public void insert(int co, int po)
{
Term temp = new Term(co,po);
ListIterator<Term>iter = poly.listIterator();
while(iter.hasNext())
{
Term t = iter.next();
if(temp.getPow() == t.getPow())
{
t.setCoe(temp.getCoe()+t.getCoe());
return;
}
else if(temp.getPow() > t.getPow())
{
iter.previous();
iter.add(temp);
return;
}
}
iter.add(temp);
}
public void multiply(int co, int po)
{
ListIterator<Term> iter = poly.listIterator();
while(iter.hasNext())
{
Term cur = iter.next();
cur.setCoe(co * cur.getCoe());
cur.setPow(po + cur.getPow());
}
}
public void derive()
{
ListIterator<Term> iter = poly.listIterator();
Term t;
while(iter.hasNext())
{
t = iter.next();
int newCoe = t.coe * t.pow;
int newPow = t.pow - 1;
if(t.pow == 1)
{
System.out.print("(" + t.pow + ", 0)");
continue;
}
if(newCoe != 0)
System.out.print("(" + newCoe + ", " + newPow + ")");
}
System.out.println();
}
static class PolyTest
{
public static void main(String[] args)
{
Polynomial p = new Polynomial();
System.out.println("The Equation is ");
p.addTerm(5,10);
p.addTerm(9,7);
p.addTerm(-1,1);
p.addTerm(-10,0);
p.print();
System.out.println("The Sum of the Equation and x is ");
p.insert(1,1);
p.print();
System.out.println("The Derivative of the First Equation is ");
p.derive();
System.out.println("Multiply 2x into the equation gets ");
p.multiply(2, 1);
p.print();
}
}
class Term
{
private int coe;
private int pow;
public int getCoe()
{
return coe;
}
public int getPow()
{
return pow;
}
public void setCoe(int co)
{
coe = co;
}
public void setPow(int po)
{
pow=po;
}
public Term(int co,int po)
{
coe = co; pow = po;
}
public String toString()
{
return "(" + coe + "," + pow + ")";
}
}
}