Polynomial Evaluation
Updated Jan 30, 20255 min read
A polynomial is an expression that contains more than two terms. A term comprises of a coefficient and an exponent.
Example: P(x)=15x4+7x2+9x+7
P(x)=14x4+17x3−12x2+13x+16
A polynomial can be represented in form of array or structure. A structure representation of a polynomial contains two parts –
(i) coefficient and
(ii) the corresponding exponent.
The following is the structure definition of apolynomial:
Struct polynomial{
int coefficient;
int exponent;
};
There are two methods to evaluate Polynomial:
- Brute Force method and
- Horner's Method
Brute Force Method
P(x)=15∗x∗x∗x∗x+17∗x∗x∗x−12∗x∗x+13∗x+16
Now consider the general form of a polynomial of degree n is
P(x)=anxn+an−1xn−1+…..+a1x1+a0x0
where a0,a1,…..an−1,an are coefficients and x0,x1,xn−1,xn are related exponents and we have to evaluate polynomial at a specific value for x.
(i) Analysis of Brute Force Method
A brute force approach to evaluate a polynomial is to evaluate all terms one by one.First calculate xn, multiply the value with the related coefficient an ,repeat the same steps for other terms and return the sum
P(x)=an∗x∗x∗…∗x∗x+an−1∗x∗x∗…∗x∗x+an−2∗x∗x∗…∗x∗x+⋯+a2∗x∗x∗+a1∗x+a0
In the first term, it will take n multiplications, in the second term n-1multiplications, in the third term it takes n-2 multiplications….. In the last two terms: a2∗x∗x and a1∗x it takes 2 multiplications and 1multiplication accordingly.
Number of multiplications needed in the worst case is
T(n)=n+(n−1)+(n−2)+...+3+2+1
=n(n+1)/2=O(n2)
Horner’s method:
Horner’s method is an optimized technique for evaluating polynomials that reduces the number of multiplications and exponentiations. Instead of computing each term separately using exponentiation, Horner’s method rewrites the polynomial in a nested form to minimize calculations.
Mathematical Representation
A polynomial of degree nnn:
P(x)=anxn+an−1xn−1+...+a1x+a0
can be rewritten in nested form as:
P(x)=(...((anx+an−1)x+an−2)x+...+a1)x+a0
This avoids explicit exponentiation and reduces the time complexity to O(n).
Example Calculation Using Horner’s Method
Consider the polynomial:
P(x)=3x3−2x2+5x+1
For x=2x = 2x=2, using brute force:
P(2) = 3 * (2)3 - 2 *(2)2+5(2)+1
= 24 -8 + 10 +1 = 27
Using Horner’s method, we rewrite:
P(2)=((3×2−2)×2+5)×2+1 = 27
Thus, P(2) = 27, computed in just O(n) time.
