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)