Loading...
Loading...
A maths tool adds and multiplies polynomials and evaluates the product. A stored polynomial never has a zero leading term, so 0x^2 + 7 is kept as 7.
Write a class Polynomial with a field long[] c, where c[i] is the coefficient of x^i. The constructor Polynomial(long[] coeffs) copies the array and drops zero leading terms (but keeps at least one). Add plus, times (both return a new Polynomial), long valueAt(long x) and String text().
P + Q = ..., P * Q = ... and VALUE v, where v is (P × Q)(x). Write terms from the highest power, like 3x^2 - x + 1: skip zero terms, write x for power 1, and drop a coefficient of 1 or -1 in front of x. The zero polynomial is 0.Example
Input
2 3 -2 1 1 1 -1 2
Output
P + Q = 3x^2 - x P * Q = 3x^3 - 5x^2 + 3x - 1 VALUE 9
P = 3x^2 - 2x + 1 and Q = x - 1; the product at x = 2 is 24 - 20 + 6 - 1 = 9.
Try the problem first. Open one hint at a time.
In the constructor, start from the last index and move down while the coefficient is 0 and the index is above 0.
For the product, the term a[i] × b[j] adds to index i + j of an array of size n + m - 1.
Horner's rule evaluates from the top: v = v × x + c[i].
In text(), print the first term's sign as -, and later signs as + or - with the absolute value.
Write your Java code, run it on the examples and submit it to hidden tests.
Solve in the editor