Consider a cubic polynomial:
Code:
C3 x3 + C2 x2 + C1 x + C0
= x3 C3
+ x2 C2
+ x1 C1
+ x0 C0
The best way to store polynomials is by stuffing the coefficients Cn in an array, in increasing order so that C0, the constant, is the first element in the array. For any polynomial order or degree degree, you have degree+1 coefficients and degree roots.
Obviously, you can now work with polynomials of any degree, as long as you have an array large enough for the coefficients.
What happens when you multiply a polynomial by (x - a)?
Code:
( C3 x3 + C2 x2 + C1 x + C0 ) ( x - a )
= C3 x3 x - a C3 x3
+ C2 x2 x - a C2 x2
+ C1 x x - a C1 x
+ C0 x - a C0
= x4 C3
+ x3 ( C2 - a C3 )
+ x2 ( C1 - a C2 )
+ x1 ( C0 - a C1 )
+ x0 ( - a C0 )
Ah ha! Multiplying by x simply shifts all coefficients up by one place. Multiplying the original polynomial by a constant is just multiplying all the coefficients by that same constant.
So, each new coefficient is the same as the next lower coefficient in the original polynomial, minus the same coefficient in the original polynomial multiplied by a: Ci ⇐ Ci-1 - a Ci.
Since the highest coefficient is only multiplied by x, we need to handle highest and lowest coefficients separately. In other words, for multiplying a polynomial coeff[] of degree degree by (x - a) , we only need (pseudocode):
Code:
coeff[degree + 1] = coeff[degree]
for i from degree down to 1
coeff[i] = coeff[i - 1] - coeff[i] * a
coeff[0] = -coeff[0] * a
degree = degree + 1
To construct a polynomial from the known roots, just start with the first degree polynomial describing the initial root,
Code:
degree = 1
coeff[1] = x
coeff[0] = -root0
and multiply by each (x - rootk) as outlined above.
If you go by the FOIL method, you find that you'll get the exact same results, and a very similar algorithm -- both need a nested loop, outer loop going over the roots, and inner loop updating the polynomial coefficients. I find the way I show here easier to understand, implement, and extend.
If you are interested in this, I'd recommend next looking at how to add two polynomials of different degree together (yes, it is very, very simple!), and how to multiply two polynomials together (which is more complex, but if you remember how to do it on paper, it should prove rather straightforward).