Monday, 7 April 2014

NPTEL WEEK 4 ASSIGNMENT FOR MULTIPLYING POLYNOMIALS

Multiply Polynomials


A polynomial of degree n is of the form P(x) = anxn + an-1xn-1 + … + a0. Given two polynomials f(x) and g(x) of degrees n and m respectively, write a program to find the polynomial h(x) given by,


h(x) = f(x) * g(x)

INPUT: Line 1 contains n and m separated by space.
             Line 2 contains the coefficients an, an-1…, a0 of f(x) separated by space.
             Line 3 contains the coefficients bm, bm-1…, b0 of g(x) separated by space.

OUTPUT: The degree of h(x) followed by the coefficients ck, ck-1…, c0 of h(x) in next line separated by space.

Sample Input:
2 2
1 2 3
3 2 1

Sample Output:
4
3 8 14 8 3

Constraints:
1 <= n <= 10
1 <= ai <= 100

PROGRAM:

#include<stdio.h>  
  int main()  
  {  
  int n,m,i,j,k,a[10],b[10],sum=0;  
  scanf("%d%d",&n,&m);  
  for(i=n;i>=0;i--)  
  {  
  scanf("%d",&a[i]);  
  }  
  for(i=m;i>=0;i--)  
  {  
  scanf("%d",&b[i]);  
  }  
  printf("%d\n",n+m);  
  for(i=n+m;i>0;i--) 

  {  
  for(j=n;j>=0;j--)  
  {  
  for(k=m;k>=0;k--)  
  {  
  if(j+k==i)  
  {  
  sum=sum+a[j]*b[k];  
  }  
  }  
  }  
  if(i==0)  
  {  
  printf("%d ",sum);  
  }  
  else  
  {  
  printf("%d ",sum);  
  }  
  sum=0;  
  }  
 printf("%d",a[0]*b[0]);  
  return 0;  
  }  

No comments:

Post a Comment