给定形式为c n x n + c n-1 x n-1 + c n-2 x n-2 +…+ c 1 x + c 0的多项式,并取x的值,求出a的多项式值给定x的值。在此,c n ,c n-1 ,…是整数(可以是负数),而n是正整数。
输入采用数组形式,例如poly [] ,其中poly [0]代表x n的系数,poly [1]代表x n-1的系数,依此类推。
例子:
// 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
一种简单的评估多项式的方法是一个一个地评估所有项。首先计算x n ,将值乘以c n ,对其他项重复相同的步骤并返回总和。如果我们使用一个简单的循环来评估x n ,则该方法的时间复杂度为O(n 2 )。如果我们使用O(Logn)方法评估x n,则时间复杂度可以提高到O(nLogn)。
Horner方法可用于评估O(n)时间中的多项式。为了理解该方法,让我们考虑2x 3 – 6x 2 + 2x – 1的示例。多项式可以评估为((2x – 6)x + 2)x – 1。 x n在这种情况下为2,将结果重复乘以x,然后将下一个系数相加。最终返回结果。
以下是霍纳法的实现。
C++
#include
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
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
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
Javascript
输出:
Value of polynomial is 5