Friday, 2 May 2014

Horner's Rule

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,

P(x) = an
Pn-1 (x) = an-1 + x * P(x)                          1st iteration.
Pn-2 (x) = an-2 + x * Pn-1 (x)                        2nd iteration.
.
.
P(x) = a0 + x * P(x)                             nth iteration.

In general, P(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.

Constraints:
1 <= n, k, m <= 10
0 <= a<=10




#include<stdio.h>
#include<math.h>
int function(int,int);
int c[10],i=0,n,m;
int main()
{
    int k;
    scanf("%d %d %d",&n,&m,&k);
    for(i=n;i>=0;i--)
     scanf("%d",&c[i]);
	i=n;
    printf("%d",function(m,k));
	return 0;
}
int function( int m, int k)
{
	int j;
	if(m==0)
	{
	 return(c[n]);
	}
	else
	{
	 j=n-m;
	 return( c[j] + k*function(m-1,k) );
    }
}

No comments: