Consider a cubic polynomial:

Code:

C_{3} x^{3} + C_{2} x^{2} + C_{1} x + C_{0}
= x^{3} C_{3}
+ x^{2} C_{2}
+ x^{1} C_{1}
+ x^{0} C_{0}

The best way to store polynomials is by stuffing the coefficients C_{n} in an array, in increasing order so that C_{0}, 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:

( C_{3} x^{3} + C_{2} x^{2} + C_{1} x + C_{0} ) ( x - a )
= C_{3} x^{3} x - a C_{3} x^{3}
+ C_{2} x^{2} x - a C_{2} x^{2}
+ C_{1} x x - a C_{1} x
+ C_{0} x - a C_{0}
= x^{4} C_{3}
+ x^{3} ( C_{2} - a C_{3} )
+ x^{2} ( C_{1} - a C_{2} )
+ x^{1} ( C_{0} - a C_{1} )
+ x^{0} ( - a C_{0} )

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*: C_{i} ⇐ C_{i-1} - a C_{i}.

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] = -*root*_{0}

and multiply by each (x - *root*_{k}) 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).