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.

Input is in the form of an array say poly[] where poly[0] represents coefficient for xn and poly[1] represents coefficient for xn-1 and so on.

Examples:

// Evaluate value of 2x3 - 6x2 + 2x - 1 for x = 3
Input: poly[] = {2, -6, 2, -1}, x = 3
Output: 5

// Evaluate value of 2x3 + 3x + 1 for x = 2
Input: poly[] = {2, 0, 3, 1}, x = 2
Output: 23

A naive way to evaluate a polynomial is to one by one evaluate all terms. First calculate xn, multiply the value with cn, repeat the same steps for other terms and return the sum. Time complexity of this approach is O(n2) if we use a simple loop for evaluation of xn. Time complexity can be improved to O(nLogn) if we use O(Logn) approach for evaluation of xn.

[ad type=”banner”]

Horner’s method can be used to evaluate polynomial in O(n) time. To understand the method, let us consider the example of 2×3 – 6×2 + 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.

Following is C++ implementation of Horner’s Method.

[pastacode lang=”c” manual=”%23include%20%3Ciostream%3E%0Ausing%20namespace%20std%3B%0A%20%0A%2F%2F%20returns%20value%20of%20poly%5B0%5Dx(n-1)%20%2B%20poly%5B1%5Dx(n-2)%20%2B%20..%20%2B%20poly%5Bn-1%5D%0Aint%20horner(int%20poly%5B%5D%2C%20int%20n%2C%20int%20x)%0A%7B%0A%20%20%20%20int%20result%20%3D%20poly%5B0%5D%3B%20%20%2F%2F%20Initialize%20result%0A%20%0A%20%20%20%20%2F%2F%20Evaluate%20value%20of%20polynomial%20using%20Horner’s%20method%0A%20%20%20%20for%20(int%20i%3D1%3B%20i%3Cn%3B%20i%2B%2B)%0A%20%20%20%20%20%20%20%20result%20%3D%20result*x%20%2B%20poly%5Bi%5D%3B%0A%20%0A%20%20%20%20return%20result%3B%0A%7D%0A%20%0A%2F%2F%20Driver%20program%20to%20test%20above%20function.%0Aint%20main()%0A%7B%0A%20%20%20%20%2F%2F%20Let%20us%20evaluate%20value%20of%202×3%20-%206×2%20%2B%202x%20-%201%20for%20x%20%3D%203%0A%20%20%20%20int%20poly%5B%5D%20%3D%20%7B2%2C%20-6%2C%202%2C%20-1%7D%3B%0A%20%20%20%20int%20x%20%3D%203%3B%0A%20%20%20%20int%20n%20%3D%20sizeof(poly)%2Fsizeof(poly%5B0%5D)%3B%0A%20%20%20%20cout%20%3C%3C%20%22Value%20of%20polynomial%20is%20%22%20%3C%3C%20horner(poly%2C%20n%2C%20x)%3B%0A%20%20%20%20return%200%3B%0A%7D” message=”C Program” highlight=”” provider=”manual”/]

Output:

Value of polynomial is 5

Time Complexity: O(n)

[ad type=”banner”]