Algorithm note 02--induction (Horner rule)

Source: Internet
Author: User

Polynomial evaluation

Suppose there is a sequence of n+2 real a0,a1,..., An and X, to find the polynomial

P_NX = a_nx^n + a_n-1x^n-1 + ... + a_1x + a_0;

You need multiplication: n+n-1 + ... +2+1 = n (n+1)/2

Need addition: N

Visible algorithm efficiency is O (n^2)

and P_nx = ((... (((((a_n) x + a_n-1) x + a_n-2) x + a_n-3) ...) X + a_1x) + a_0

So the idea:

p_0x = A_n

p_1x = xp_0x + a_n-1

p_2x = xp_2x + a_n-2

......

P_NX = xp_n-1x + a_0

Complexity of Time:

Make t (n) The sum of the addition and multiplication required for n times, assuming that the multiplication is O (1)

T (1) = 2

T (2) = t (1) + 1 +1 = t (1) +2

T (n) = t (n-1) + 1 +1 = t (n-1) + 2

So t (n) = t (1) + n-1 = 2*n = n +n

Multiplication n times, addition n times, time complexity O (n)

Code:

#include <iostream>using namespace Std;int solve_px (int a[],int x, int n) {int px = a[0];for (int i =1; i<n;i++) {px = Px*x + a[i];} return px;}  int main () {//px4 = 3*x^4+6*x^3+2*x^2+5*x+6//px0 =         3 (a[0])//px1 = x*px0 + 6 (a[1])//px2 = x*px1 + 2 (a[2])//px3 = x*px2 + 5 (a[3])//px4 = x*px3 + 6 (a[4]) int a[5] = {3,6,2,5,6};int x = 2;cout<<solve_px (a,x,5) <<endl;return 1;}

Algorithm note 02--induction (Horner rule)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.