Given a polynomial of the form cnxn + cn-1xn-1 + cn-2xn-2 + … + c1x + c0 and a value of x, find the value of polynomial for a given value of x. Here cn, cn-1, .. are integers (may be negative) and n is a positive integer.
Read full article from Horner's Method for Polynomial Evaluation | GeeksforGeeks
Horner’s method can be used to evaluate polynomial in O(n) time. To understand the method, let us consider the example of 2x3 – 6x2 + 2x – 1. The polynomial can be evaluated as ((2x – 6)x + 2)x – 1. The idea is to initialize result as coefficient of xn which is 2 in this case, repeatedly multiply result with x and add next coefficient to result. Finally return result.
int horner(int poly[], int n, int x){ int result = poly[0]; // Initialize result // Evaluate value of polynomial using Horner's method for (int i=1; i<n; i++) result = result*x + poly[i]; return result;}
No comments:
Post a Comment