The Wayback Machine - https://web.archive.org/web/20240713132901/https://www.geeksforgeeks.org/horners-method-polynomial-evaluation/
Open In App

Horner’s Method for Polynomial Evaluation

Last Updated : 02 Nov, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

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

 

Recommended Practice

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.
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.
Following is implementation of Horner’s Method. 
 

C++




#include <iostream>
using namespace std;
 
// returns value of poly[0]x(n-1) + poly[1]x(n-2) + .. + poly[n-1]
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;
}
 
// Driver program to test above function.
int main()
{
    // Let us evaluate value of 2x3 - 6x2 + 2x - 1 for x = 3
    int poly[] = {2, -6, 2, -1};
    int x = 3;
    int n = sizeof(poly)/sizeof(poly[0]);
    cout << "Value of polynomial is " << horner(poly, n, x);
    return 0;
}


Java




// Java program for implementation of Horner Method
// for Polynomial Evaluation
import java.io.*;
 
class HornerPolynomial
{
    // Function that returns value of poly[0]x(n-1) +
    // poly[1]x(n-2) + .. + poly[n-1]
    static int horner(int poly[], int n, int x)
    {
        // Initialize result
        int result = poly[0]; 
  
        // Evaluate value of polynomial using Horner's method
        for (int i=1; i<n; i++)
            result = result*x + poly[i];
  
        return result;
    }
     
    // Driver program
    public static void main (String[] args)
    {
        // Let us evaluate value of 2x3 - 6x2 + 2x - 1 for x = 3
        int[] poly = {2, -6, 2, -1};
        int x = 3;
        int n = poly.length;
        System.out.println("Value of polynomial is "
                                        + horner(poly,n,x));
    }
}
 
// Contributed by Pramod Kumar


Python3




# Python program for
# implementation of Horner Method
# for Polynomial Evaluation
 
# returns value of poly[0]x(n-1)
# + poly[1]x(n-2) + .. + poly[n-1]
def horner(poly, n, x):
 
    # Initialize result
    result = poly[0] 
  
    # Evaluate value of polynomial
    # using Horner's method
    for i in range(1, n):
 
        result = result*x + poly[i]
  
    return result
  
# Driver program to
# test above function.
 
# Let us evaluate value of
# 2x3 - 6x2 + 2x - 1 for x = 3
poly = [2, -6, 2, -1]
x = 3
n = len(poly)
 
print("Value of polynomial is " , horner(poly, n, x))
 
# This code is contributed
# by Anant Agarwal.


C#




// C# program for implementation of
// Horner Method  for Polynomial Evaluation.
using System;
 
class GFG
{
    // Function that returns value of poly[0]x(n-1) +
    // poly[1]x(n-2) + .. + poly[n-1]
    static int horner(int []poly, int n, int x)
    {
        // Initialize result
        int result = poly[0];
 
        // Evaluate value of polynomial
        // using Horner's method
        for (int i = 1; i < n; i++)
            result = result * x + poly[i];
 
        return result;
    }
     
    // Driver Code
    public static void Main()
    {
        // Let us evaluate value of
        // 2x3 - 6x2 + 2x - 1 for x = 3
        int []poly = {2, -6, 2, -1};
        int x = 3;
        int n = poly.Length;
        Console.Write("Value of polynomial is "
                            + horner(poly,n,x));
    }
}
 
// This code Contributed by nitin mittal.


PHP




<?php
// PHP program for implementation
// of Horner Method for Polynomial
// Evaluation.
 
// returns value of poly[0]x(n-1) +
// poly[1]x(n-2) + .. + poly[n-1]
function horner($poly, $n, $x)
{
    // Initialize result
    $result = $poly[0];
 
    // Evaluate value of polynomial
    // using Horner's method
    for ($i = 1; $i < $n; $i++)
        $result = $result *
                  $x + $poly[$i];
 
    return $result;
}
 
// Driver Code
 
// Let us evaluate value of
// 2x3 - 6x2 + 2x - 1 for x = 3
$poly = array(2, -6, 2, -1);
$x = 3;
$n = sizeof($poly) / sizeof($poly[0]);
 
echo "Value of polynomial is ".
         horner($poly, $n, $x);
 
// This code is contributed by mits.
?>


Javascript




<script>
// Javascript program for implementation
// of Horner Method for Polynomial
// Evaluation.
 
// returns value of poly[0]x(n-1) +
// poly[1]x(n-2) + .. + poly[n-1]
function horner(poly, n, x)
{
 
    // Initialize result
    let result = poly[0];
 
    // Evaluate value of polynomial
    // using Horner's method
    for (let i = 1; i < n; i++)
        result = result *
                  x + poly[i];
 
    return result;
}
 
// Driver Code
 
// Let us evaluate value of
// 2x3 - 6x2 + 2x - 1 for x = 3
let poly = new Array(2, -6, 2, -1);
let x = 3;
let n = poly.length
 
document.write("Value of polynomial is " +
         horner(poly, n, x));
 
// This code is contributed by _saurabh_jaiswal.
</script>


Output: 
 

Value of polynomial is 5

Time Complexity: O(n)

Auxiliary Space: O(1)

 



Previous Article
Next Article

Similar Reads

Expression Evaluation
Evaluate an expression represented by a String. The expression can contain parentheses, you can assume parentheses are well-matched. For simplicity, you can assume only binary operations allowed are +, -, *, and /. Arithmetic Expressions can be written in one of three forms: Infix Notation: Operators are written between the operands they operate on
15 min read
Evaluation of Prefix Expressions
Prefix and Postfix expressions can be evaluated faster than an infix expression. This is because we don't need to process any brackets or follow operator precedence rule. In postfix and prefix expressions which ever operator comes before will be evaluated first, irrespective of its priority. Also, there are no brackets in these expressions. As long
13 min read
Evaluation of Risk in Investments
Given two investment options A and B, we have to find the less risky investment of the two. The two investments A and B are each represented by an array. Each element in the array is a probable investment outcome. Thus each element in the array is a pair of two values. The first value is the amount of money received and the second value is the prob
12 min read
Arithmetic Expression Evaluation
The stack organization is very effective in evaluating arithmetic expressions. Expressions are usually represented in what is known as Infix notation, in which each operator is written between two operands (i.e., A + B). With this notation, we must distinguish between ( A + B )*C and A + ( B * C ) by using either parentheses or some operator-preced
2 min read
Remainder Evaluation
Given two positive integers Num1 and Num2, the task is to find the remainder when Num1 is divided by Num2. Examples: Input: Num1 = 11, Num2 = 3Output: 2Explanation: 3) 11 (3 - 9 --------- 2 -&gt; Remainder ---------- Input: Num1 = 15, Num2 = 3Output: 0 Approach 1: The problem can be solved by using the modulus operator. Modulus operator returns the
5 min read
Evaluation of Postfix Expression
Given a postfix expression, the task is to evaluate the postfix expression. Postfix expression: The expression of the form "a b operator" (ab+) i.e., when a pair of operands is followed by an operator. Examples: Input: str = "2 3 1 * + 9 -"Output: -4Explanation: If the expression is converted into an infix expression, it will be 2 + (3 * 1) - 9 = 5
15+ min read
Grid Evolution and Query Evaluation
Given a grid of dimensions n rows and m columns, where each element initially contains an integer from 0 to k-1. The grid evolves over time, with each element undergoing the transformation (grid[i][j] + 1) % k after each unit of time. You are also provided with a series of queries, each defined by [t, val, lx, ly, rx, ry], the task is to determine,
13 min read
Introduction to Evaluation Function of Minimax Algorithm in Game Theory
Prerequisite: Minimax Algorithm in Game TheoryAs seen in the above article, each leaf node had a value associated with it. We had stored this value in an array. But in the real world when we are creating a program to play Tic-Tac-Toe, Chess, Backgammon, etc. we need to implement a function that calculates the value of the board depending on the pla
8 min read
Evaluation of Expression Tree
Given a simple expression tree, consisting of basic binary operators i.e., + , - ,* and / and some integers, evaluate the expression tree. Examples: Input: Root node of the below tree Output:100 Input: Root node of the below tree Output: 110 Recommended PracticeExpression TreeTry It! Approach: The approach to solve this problem is based on followin
9 min read
All ways to add parenthesis for evaluation
Given a string that represents an expression constituting numbers and binary operator +, - and * only. We need to parenthesize the expression in all possible way and return all evaluated values. Input : expr = “3-2-1”Output : {0, 2}((3-2)-1) = 0 (3-(2-1)) = 2Input : expr = "5*4-3*2"Output : {-10, 10, 14, 10, 34}(5*(4-(3*2))) = -10(5*((4-3)*2)) = 10
8 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg