HiveBrain v1.2.0
Get Started
← Back to all entries
patterncMinor

Evaluating a polynomial at a given value of x and n

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
polynomialvalueandgivenevaluating

Problem

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

   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;
}

Solution

By following Horner's Method only n multiplications are needed.

#include 

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= 0;i--) b = b*x + A[i];

   printf("\nSum of polynomial is %d\n",b);

   return 0;
}

Code Snippets

#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;
}

Context

StackExchange Code Review Q#45841, answer score: 2

Revisions (0)

No revisions yet.