Friday, 2 May 2014

Evaluating a Polynomial

You are given a polynomial of degree n. The polynomial is of the form P(x) = anxn + an-1xn-1 + … + a0, where the ai‘s are the coefficients. Given an integer x, write a program that will evaluate P(x).

INPUT: Line 1 contains the integers n and x separated by whitespace.
Line 2 contains the coefficients an, an-1…, a0 separated by whitespace.

OUTPUT: A single integer which is P(x).

CONSTRAINTS: The inputs will satisfy the following properties. It is not necessary to validate the inputs.
1 <= n <= 10 1 <= x <= 10 0 <= ai <=10

#include<stdio.h>
int power(int x, int y);
int main()
{
int n,a[10],i,x,p=0;
scanf("%d%d",&n,&x);
i=n;
while(i>=0)
{
scanf("%d",&a[i]);
i--;
}
for(i=n;i>=0;i--)
{
p += a[i]*power(x,i);
}
printf("%d",p);
return 0;
}
int power(int x, int y)
{
int result = x;
if(y == 0)
return 1;
if(x < 0 || y < 0)
return 0;
for(int i = 1; i < y; ++i)
result *= x;
return result;
}

No comments: