= Solution
Scan the <polynomial coefficients> from highest degree downward. Omit zero terms, omit coefficient magnitude one on nonconstant terms, print `-` for negative terms, and print `+` only before a positive term after the first. A helper prints small integral magnitudes without a decimal suffix; other <real numbers> use `Out.Real`.
``
PROCEDURE OutMagnitude(c: REAL);
VAR n: INTEGER;
BEGIN
IF c < MAX(INTEGER) THEN
n := ENTIER(c);
IF c = n THEN Out.Int(n, 0) ELSE Out.Real(c, 0) END
ELSE
Out.Real(c, 0)
END
END OutMagnitude;
PROCEDURE OutPoly(p: Poly);
VAR i: INTEGER; c, magnitude: REAL; first: BOOLEAN;
BEGIN
IF p.degree < 0 THEN Out.String("0"); RETURN END;
first := TRUE; i := p.degree;
WHILE i >= 0 DO
c := p.coeff[i];
IF c # 0.0 THEN
IF c < 0.0 THEN Out.Char("-")
ELSIF ~first THEN Out.Char("+")
END;
magnitude := ABS(c);
IF (i = 0) OR (magnitude # 1.0) THEN
OutMagnitude(magnitude)
END;
IF i > 0 THEN
Out.Char("x");
IF i > 1 THEN Out.Char("^"); Out.Int(i, 0) END
END;
first := FALSE
END;
DEC(i)
END
END OutPoly;
``
The <representation invariant> ensures a nonzero <polynomial> prints at least one term. Constant $1$ and $-1$ retain their coefficients, whereas $x$ and $-x$ omit magnitude one. Thus the requested example prints
$$
\boxed{x^4-3x^2+7x-1.}
$$
Different `Out.Real` implementations may use decimal or scientific notation for nonintegral coefficients; either denotes the appropriate <real number>. The number of coefficient inspections is linear in the stored <polynomial degree>.
Back to article page