public Polynomial(int[] coefficients) The constructor that receives as argument
ID: 3904253 • Letter: P
Question
public Polynomial(int[] coefficients)
The constructor that receives as argument the array of coefficients that define the polynomial. For a polynomial of degree n, the array coefficients contains exactly n + 1 elements so that the coefficient of the term of order k is in the element coefficients[k]. For example, the polynomial 5x3 - 7x + 42 that will be used as example in all of the following methods would be given as the coefficient array {42, -7, 0, 5}.
Terms missing from inside the polynomial are represented by having a zero coefficient in that position. However, the coefficient of the highest term of every polynomial should always be nonzero, unless the polynomial itself is identically zero. If this constructor is given as argument a coefficient array whose highest terms are zeroes, it should simply ignore those zero terms. For example, if given the coefficient array {-1, 2, 0, 0, 0}, the resulting polynomial would have degree of only one, as if that argument array had really been {-1, 2} without these leading zeros.
To guarantee that the Polynomial class is immutable so that no outside code can ever change the internal state of an object after its construction (at least not without resorting to underhanded tricks such as reflection), the constructor should not assign only the reference to the coefficients array to the private field of coefficients, but it must create a separate but identical defensive copy of the argument array, and store that defensive copy instead. This ensures that the stored coefficients of the polynomial do not change if somebody later changes the contents of the shared coefficients array that was given as the constructor argument.
Test Code:
Explanation / Answer
class Polynomial{
private int[] data;
private 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 (i = len-1; i>=0; i--){
if (data[i] != 0){
degree = i;
break;
}
}
}
public double evaluate(double x){
double sum = 0;
for (int i = 0; i<=degree; i++){
sum = sum + data[i] * Math.pow(x,i);
}
return sum;
}
double getCoefficient(int n){
if (n <= degree && n >=0){
return data[n];
}
else {
return -1;
}
}
int getDegree(){
return degree;
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.