Question

The second lab continues with the Polynomial class from the first lab by adding new methods...

The second lab continues with the Polynomial class from the first lab by adding new methods for polynomial arithmetic to its source code. (There is no inheritance or polymorphism taking place yet in this lab.) Since the class Polynomial is designed to be immutable, none of the following methods should modify the objects this or other in any way, but return the result of that arithmetic operation as a brand new Polynomial object created inside that method.

public Polynomial add(Polynomial other)

Creates and returns a new Polynomial object that represents the result of polynomial addition of the two polynomials this and other. This method should not modify this or other polynomial in any way. Make sure that just like with the constructor, the coefficient of the highest term of the result is nonzero, so that adding the two polynomials 5x10 - x2 + 3x and -5x10 + 7, each having a degree 10, produces the result -x2 + 3x + 7 that has a degree of only 2 instead of 10.

public Polynomial multiply(Polynomial other)

Creates and returns a new Polynomial object that represents the result of polynomial multiplication of the two polynomials this and other. Polynomial multiplication works by multiplying all possible pairs of terms between the two polynomials and adding them together, combining terms of equal degree together into a single term.

Here is my polynomial class:

public class Polynomial{
private int[] data;
private int degree;
  
public Polynomial(int[] coefficients){
int len = coefficients.length;
data = new int[coefficients.length];
for (int i = 0; i<coefficients.length; i++){
data[i] = coefficients[i];
}

for (int i = len-1; i>=0; i--){
if (data[i] != 0){
degree = i;
break;
}
}
}
  
public long evaluate(int x){
int coeffs[]={1,2,3,4}; //change it according to question
long sum = 0;
long input = 1;
for (int i = 0; i < coeffs.length; i++) {
sum += coeffs[i] * input;
input *= x;
}
return sum;
}
  
public int getCoefficient(int k){
if (k <= degree && k >=0){
return data[k];
}
else {
return -1;
}
}
  
public int getDegree(){
return degree;
}
}
  

0 0
Add a comment Improve this question Transcribed image text
Answer #1

//Polynomial.java

public class Polynomial {

      

       private int[] data;

       private int degree;

      

       public Polynomial(int[] coefficients){

             int len = coefficients.length;

             data = new int[coefficients.length];

             for (int i = 0; i<coefficients.length; i++){

                    data[i] = coefficients[i];

             }

             for (int i = len-1; i>=0; i--){

                           if (data[i] != 0){

                                 degree = i;

                                 break;

                           }

             }

       }

      

       public long evaluate(int x){

             int coeffs[]={1,2,3,4}; //change it according to question

             long sum = 0;

             long input = 1;

             for (int i = 0; i < coeffs.length; i++) {

                    sum += coeffs[i] * input;

                    input *= x;

             }

             return sum;

       }

      

       public int getCoefficient(int k){

             if (k <= degree && k >=0){

                    return data[k];

             }

             else {

                    return -1;

             }

       }

      

       public int getDegree(){

             return degree;

       }

      

       // method to add 2 polynomial

       public Polynomial add(Polynomial other)

       {

             Polynomial result;

             // if degree of this polynomial is greater than other

             if(degree > other.getDegree())

             {

                    result = new Polynomial(data); // create the result polynomial same as this

                    // add the coefficients of other polynomial to result

                    for(int i=0;i<=other.getDegree();i++)

                    {

                           result.data[i] += other.data[i];

                    }

             }

             else

             {

                    result = new Polynomial(other.data); // create the result polynomial same as other

                    // add the coefficients of this polynomial to result

                    for(int i=0;i<=degree;i++)

                    {

                           result.data[i] += data[i];

                    }

             }

            

             return result; // return the resultant polynomial

       }

      

       // method to multiply two polynomials

       public Polynomial multiply(Polynomial other)

       {

             Polynomial result;

             // get the resultant degree

             int res_degree = degree + other.degree;

             int res_coeff[] = new int[res_degree+1]; // create a coefficents array of degree res_degree

             // set all elements to 0

             for(int i=0;i<res_coeff.length;i++)

                    res_coeff[i] = 0;

            

             result = new Polynomial(res_coeff); // create a resultant polynimial using res_coeff

            

             // loop to multiply two polynomials

             for(int i=0;i<=degree;i++)

             {

                    for(int j=0;j<=other.getDegree();j++)

                           result.data[i+j] += data[i]*other.data[j]; // in multiplication the degrees are added

             }

            

             return result; // return the resultant polynomial

       }

      

       // toString method to return the string representation of polynomial

       public String toString()

       {

             String polyStr = "";

             for(int i=data.length-1;i>0;i--)

             {

                    if(data[i] != 0)

                    {

                           if(polyStr.length() == 0)

                           {

                                 if(Math.abs(data[i]) != 1)

                                        polyStr += data[i];

                                 else

                                 {

                                        if(data[i] < 0)

                                               polyStr += "-";

                                 }

                                 polyStr += "x"+i;

                           }else

                           {

                                 if(data[i] > 0)

                                        polyStr += " + ";

                                 else

                                        polyStr += " - ";

                                 if(Math.abs(data[i]) != 1)

                                        polyStr += (int)Math.abs(data[i]);

                                 polyStr += "x"+i;

                           }

                    }

             }

            

             if(polyStr.length() == 0)

             {

                    polyStr += data[0];

             }else

             {

                    if(data[0] != 0)

                    {

                           if(data[0] > 0 )

                                 polyStr += " + ";

                           else

                                 polyStr += " - ";

                           polyStr += (int)Math.abs(data[0]);

                    }

             }

            

             return polyStr;

       }

       public static void main(String[] args) {

            

             // test the add and multiply methods

             int coeffs1[] = {0,3,-1,0,0,0,0,0,0,0,5};

             int coeffs2[] = {7,0,0,0,0,0,0,0,0,0,-5};

            

             Polynomial poly1 = new Polynomial(coeffs1);

             Polynomial poly2 = new Polynomial(coeffs2);

             System.out.println("Polynomial1 :"+poly1);

             System.out.println("Polynomial2 :"+poly2);

            

             Polynomial addPoly = poly1.add(poly2);

             System.out.println("Polynomial1 + Polynomial2 : "+addPoly);

            

             Polynomial mulPoly = poly1.multiply(poly2);

             System.out.println("Polynomial1 * Polynomial2 : "+mulPoly);

       }

}

//end of Polynomial.java

Output:

Add a comment
Know the answer?
Add Answer to:
The second lab continues with the Polynomial class from the first lab by adding new methods...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • For this lab, you must define a class called Polynomial. This class definition must include the f...

    please answer this question in python 3 For this lab, you must define a class called Polynomial. This class definition must include the following methods: ._init_0- the initialiser for the class ._str_0- returns a formatted string representation of a Polynomial object add_term) - adds a new term (coefficient and exponent) to the Polynomial .addo-modifies the existing Polynomial by adding another one to it ._add_0-returns a new Polynomial object that is the sum of two polynomials scale) - scales a Polynomial...

  • For this lab, you must define a class called Polynomial. This class definition must include the f...

    Please answer this in python 3, thank you. For this lab, you must define a class called Polynomial. This class definition must include the following methods: ._init_0- the initialiser for the class ._str_0- returns a formatted string representation of a Polynomial object add_term) - adds a new term (coefficient and exponent) to the Polynomial .addo-modifies the existing Polynomial by adding another one to it ._add_0-returns a new Polynomial object that is the sum of two polynomials scale) - scales a...

  • Polynomial Using LinkedList class of Java Language Description: Implement a polynomial class using a LinkedList defined...

    Polynomial Using LinkedList class of Java Language Description: Implement a polynomial class using a LinkedList defined in Java (1) Define a polynomial that has the following methods for Polynomial a. public Polynomial() POSTCONDITION: Creates a polynomial represents 0 b. public Polynomial(double a0) POSTCONDITION: Creates a polynomial has a single x^0 term with coefficient a0 c. public Polynomial(Polynomial p) POSTCONDITION: Creates a polynomial is the copy of p d. public void add_to_coef(double amount, int exponent) POSTCONDITION: Adds the given amount to...

  • I need help filling in the the code in the methods add, multiply, and evaluate package...

    I need help filling in the the code in the methods add, multiply, and evaluate package poly; import java.io.IOException; import java.util.Scanner; /** * This class implements evaluate, add and multiply for polynomials. * * * */ public class Polynomial {       /**    * Reads a polynomial from an input stream (file or keyboard). The storage format    * of the polynomial is:    * <pre>    * <coeff> <degree>    * <coeff> <degree>    * ...    *...

  • Create a class to represent a term in an algebraic expression. As defined here, a term...

    Create a class to represent a term in an algebraic expression. As defined here, a term consists of an integer coefficient and a nonnegative integer exponent. E.g. in the term 4x2, the coefficient is 4 and the exponent 2 in -6x8, the coefficient is -6 and the exponent 8 Your class will have a constructor that creates a Term object with a coefficient and exponent passed as parameters, and accessor methods that return the coefficient and the exponent. Your class...

  • Can anyone add the 1) add_to_coef, add, multiply, coefficient, eval and equals method in the main...

    Can anyone add the 1) add_to_coef, add, multiply, coefficient, eval and equals method in the main function..so can take it from text file.... or 2) make main function with user input for all methods mentioned in the program. import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Scanner; public class Polynomial { //array of doubles to store the coefficients so that the coefficient for x^k is stored in the location [k] of the array. double coefficients[]; static int size; //fube the following...

  • Lab 7 Add three instance variables to your class RightTriangle from lab 5. The first two...

    Lab 7 Add three instance variables to your class RightTriangle from lab 5. The first two are of type int and are called xLoc and yLoc and the third is of type int called ID. Also add a static variable of type double called scaleFactor. This should be initialized to a default value of 1. Update the constructor to set the three new instance variables and add appropriate get and set methods for the four new variables. All set methods...

  • Complete the CashRegister class by implementing the methods and adding the correct attributes (characteristics) as discussed...

    Complete the CashRegister class by implementing the methods and adding the correct attributes (characteristics) as discussed in class. Once complete, test the class using the CashRegisterTester class. Make sure you have 3 total items in the cash register. I have two classes, the first is CashRegisterTester below: public class CashRegisterTester { public static void main(String[] args) { //Initialize all variables //Construct a CashRegister object CashRegister register1 = new CashRegister(); //Invole a non-static method of the object //since it is non-static,...

  • C++ NEED AS SOON AS POSSIBLE! BigInt class is used for the mathematical operations that involve...

    C++ NEED AS SOON AS POSSIBLE! BigInt class is used for the mathematical operations that involve very big integer calculations that are outside the limit of all available primitive data types. For example, factorial of 100 contains 158 digits in it so we can’t store it in any primitive data type available. We can store as large Integer as we want in it. Your goal is to overload the operators for a generic “BigInt” class. You will need to write...

  • Use your Food class, utilities code, and sample data from Lab 1 to complete the following...

    Use your Food class, utilities code, and sample data from Lab 1 to complete the following Tasks. def average_calories(foods):     """     -------------------------------------------------------     Determines the average calories in a list of foods.     foods is unchanged.     Use: avg = average_calories(foods)     -------------------------------------------------------     Parameters:         foods - a list of Food objects (list of Food)     Returns:         avg - average calories in all Food objects of foods (int)     -------------------------------------------------------     """ your code here is the...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT