Friday 12 February 2016

Evaluating polynomials

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,
Pn (x) = an
Pn-1 (x) = an-1 + x * Pn (x)                              1st iteration.
Pn-2 (x) = an-2 + x * Pn-1 (x)                           2nd iteration.
.
.
P0 (x) = a0 + x * P1 (x)                                  nth iteration.
In general, Pi (x) = ai + x * Pi + 1 (x) and P0(x) is the final result.
Input
n m k an an-1 …. a0
(Space separated)
Output: P(k) value at the end of the mth iteration.
Sample Input:
2 2 5
3 2 1
Sample Output:
86
Constraints:
1 <= n, k, m <= 10
0 <= ai <=10


Solution -:


#include <stdio.h> int main() { int n, m, k, a[30],j; int ans,i; scanf("%d %d %d", &n, &m, &k); ans = 0; for( i = 0; i <= n; ++i) scanf("%d", &a[i]); ans=a[0]; for(j=1;j<=m;j++) { ans=ans*k+a[j]; } printf("%d",ans); return 0; }

8 comments:

  1. Replies
    1. just run a loop till m.
      and do ans=ans*k+a[i];
      to evaluate the polynomial.then output it.please read the question this one is pretty easy.

      Delete
  2. for(j=0;j<=m;j++)
    {
    ans=ans*k+a[i];
    }
    printf("%d",ans);

    this is giving an error

    ReplyDelete
  3. Here is the solution... I have removed one step so that you dont do simply copy and paste...
    int n, m, k, i, a[30];
    scanf("%d %d %d", &n, &m, &k);
    for(i = 0; i <= n; i++)
    scanf("%d", &a[i]);
    ans = a[0];
    for(i = 1; i <= m; i++)
    ans = a[i] + k * ans;
    printf("%d", ans);

    ReplyDelete
  4. int main()
    {
    int n,m,k,a[30];
    int ans,i;
    scanf("%d %d %d", &n, &m, &k);
    ans = 0;
    for(i=0;i<=n;i++)
    scanf("%d", &a[i]);
    m = sizeof(a)/sizeof(a[0]);
    horner(a,m,k);

    /*
    Write your code to evaluate the polynomial using
    Horner's rule.
    */

    return 0;
    }
    int hornor(int a[],int m,int k){
    int ans = a[0],i;
    for(i = 1; i <= m; i++)
    ans = a[i]+k*ans;
    printf("%d",ans);
    }

    I GET LIKE THIS
    Compilation : Failed
    Program/tmp/cckAi4WJ.o: In function `main':
    Program:(.text+0x8a): undefined reference to `horner' collect2: error: ld returned 1 exit status

    HOW TO SOLVE THIS

    ReplyDelete
    Replies
    1. I SOLVED IT there was spelling mistake

      Delete