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).
You are provided with a function named power( ) that takes two positive integers x & y and returns xy. If y is 0, the function returns 1.
The prototype of this function is
int power(int x, int y);
You do not have to write the program for power ( ) function. This function is automatically added at the end of the code segment that you write.
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
Solution:
#include<stdio.h>
int power(int x, int y);
int main()
{
int n,x,i;
scanf("%d%d",&n,&x);
int arr[n+1];
for(i=n; i>=0; i--)
{
scanf("%d",&arr[i]);
}
int result =0;
for(i=n;i>0;i--)
{
result += arr[i]*power(x,i);
}
result += arr[i];
printf("%d",result);
return 0;
}
/* THE CODE BELOW WILL BE AUTOMATICALLY UNCOMMENTED DURING EXECUTION. PLEASE DO NOT MODIFY ANYTHING BELOW THIS LINE.*/
// 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:
Post a Comment