Horner's Rule
PROGRAM:You are given a polynomial of degree n. The polynomial is of the form P(x) = anxn + an-1xn-1 + … + a0. For given values k and m, You are required to find P(k) at the end of the mth iteration of Horner’s rule. The steps involved in the Horner’s rule are given below,
Pn (x) = an
Pn-1 (x) = an-1 + x * Pn (x) 1st iteration.
Pn-2 (x) = an-2 + x * Pn-1 (x) 2nd iteration.
.
.
P0 (x) = a0 + x * P1 (x) nth iteration.
In general, Pi (x) = ai + x * Pi + 1 (x) and P0(x) is the final result. The input to your program is as follows,
Line 1 contains the integers n, m and k separated by space.
Line 2 contains the coefficients an, an-1…, a0 separated by space.
INPUT: Integers n, m, k and the coefficients as described above.
OUTPUT: P(k) value at the end of the mth iteration.
Sample Input:
2 2 5
3 2 1
Sample Output:
86
Constraints:
1 <= n, k, m <= 10
0 <= ai <=10
PROGRAM:
#include<stdio.h>
int horner(int[],int,int);
int main()
{
int n,m,k,i;
int a[10];
scanf("%d%d%d",&n,&m,&k);
for(i=0;i<=n;++i)
{
scanf("%d",&a[i]);
}
printf("%d",horner(a,m,k));
return 0;
}
int horner(int a[],int m,int k)
{
if(m==0){
return a[m];
}
else{
return a[m]+k*horner(a,m-1,k);
}}
No comments:
Post a Comment