To solve a polynomial equation I have written following program, is there any way to optimize this program.
Following code is working code:
Program takes input n,x where n is the deg of polynomial and x is the point at which the polynomial is to be evaluated.
#include<stdio.h>
int power(int x, int y);
int main()
{
// n is the deg of polynomial
// x is the value of polynomial for which it is to be evaluated
int x=0,n=0,A[10],sum=0,i=0,M=0,y=0;
printf("Enter value of n,x \n");
scanf("%d %d",&n,&x);
printf("Enter the coeficients\n");
for(i=0;i<=n;i++) //Taking coefiecent values
{
scanf("%d",&A[i]);
}
y=n;
for(i=0;i<=n;i++)
{
M=power(x,y);
sum=sum+(A[i]*M);
y--;
}
printf("\nSum of polynomial is %d",sum);
return 0;
}
int power(int x, int y)
{
int result = x;
int i;
if(y == 0) return 1;
if(x < 0 || y < 0) return 0;
for(i = 1; i < y; ++i)
result *= x;
return result;
}
2 Answers 2
By following Horner's Method only n multiplications are needed.
#include <stdio.h>
int main()
{
// n is the deg of polynomial
// x is the value of polynomial for which it is to be evaluated
int x=0,n=0,A[10],b,i;
printf("Enter value of n,x \n");
scanf("%d %d",&n,&x);
//Taking coefficient values
printf("Enter the coeficients\n");
for(i=0;i<=n;i++) scanf("%d",&A[i]);
for(i = n - 1,b = A[n];i >= 0;i--) b = b*x + A[i];
printf("\nSum of polynomial is %d\n",b);
return 0;
}
If user enters the coefficients in A[n], A[n-1], ... A[1], A[0]
order, code gets nice and tight. No need to save all the coefficients and no need to limit them to 10. Calculate the sum as you go.
BTW: Always good to check the results of scanf()
.
#include<stdio.h>
int main() {
// n is the deg of polynomial
// x is the value of polynomial for which it is to be evaluated
int x, n, A;
long sum = 0; // or use long long
printf("Enter value of n,x \n");
if (scanf("%d %d", &n, &x) != 2) {
return 1; // bad input
}
printf("Enter the coefficients\n"); // spelling change
while (n-- >= 0) {
if (scanf("%d", &A) != 1) {
return 1; // bad input
}
sum *= x;
sum += A;
}
printf("\nSum of polynomial is %ld", sum);
return 0;
}