Question: write multiply and add to the following code, it adds and multiplies the two equations in standard form in java return their sum and product
write multiply and add to the following code, it adds and multiplies the two equations in standard form in java
return their sum and product equation which also be in standard form.
public class Test{
public static void main(String argc[]){
Polynomial sum, product;
Polynomial p1 = new Polynomial(4,1);
Polynomial p2 = new Polynomial(3,5);
p3 = p1.add(p2);
p1 = new Polynomial(7,4);
p2 = new Polynomial(2,2);
p4 = p1.add(p2);
sum = p3.add(p4);
product = p3.multiply(p4);
sum.print();
product.print();
p1.print();
p2.print();
}
}
class Polynomial{
private static class PolyNode{
private int coef;
private int expo;
private PolyNode next;
public PolyNode(int c, int e){
this(c, e, null);
}
public PolyNode(int c, int e, PolyNode n){
coef = c;
expo = e;
next = n;
}
public void setCoef(int c){ coef = c;}
public void setExpo(int e){ expo = e;}
public void setNext(PolyNode n){ next = n;}
public int getCoef(){ return coef;}
public int getExpo(){ return expo;}
public PolyNode getNext(){ return next;}
}
private PolyNode first;
private PolyNode last;
public Polynomial(){
first = last = null;
}
public Polynomial(int c, int e){
PolyNode tempn = new PolyNode(c, e);
first = last = tempn;
}
public void print(){
if (first == null){
System.out.println();
return;
}
PolyNode tempe = first;
String ans = "";
while (tempe != null){
if (tempe.getCoef() > 0) {
if (tempe != first) ans = ans + " + ";
ans = ans + tempe.getCoef();
}
else if (tempe.getCoef() < 0) ans = ans + " - " + tempe.getCoef() * -1;
if (tempe.getExpo() != 0){
ans = ans + "X^" + tempe.getExpo();
}
tempe = tempe.getNext();
}
System.out.println(ans);
}
}
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
