Question
write a method for multiply and add for the following code, it add and multiply the two equations in standard form in java then return
write a method for multiply and add for the following code, it add and multiply the two equations in standard form in java
then return their sum and product equation which also be in standard form.
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);
}
}
public class Test{
public static void main(String argc[]){
Polynomial sum, product;
Polynomial p1 = new Polynomial(4,5);
Polynomial p2 = new Polynomial(2,5);
p3 = p1.add(p2);
p1 = new Polynomial(5,4);
p2 = new Polynomial(3,2);
p4 = p1.add(p2);
sum = p3.add(p4);
product = p3.multiply(p4);
sum.print();
product.print();
p1.print();
p2.print();
}
}
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started