Showing posts with label Program for multiplication of two polynomials (with sorting desending order). Show all posts
Showing posts with label Program for multiplication of two polynomials (with sorting desending order). Show all posts

Tuesday, July 19, 2011

Program for multiplication of two polynomials (with sorting desending order)

/*Serial No.133     [swami113.cpp]*/

#include<stdio.h>
#include<conio.h>
void main()
    {
    int a[6][2],b[6][2],p,q,i,j,k=0,temp1,temp2;
    int m[36][2],u[36][2];
    clrscr();
    printf("enter the no of terms in first polynomial= ");
    scanf("%d",&p);
    printf("enter coefficient and exponent of first polynomial\n");
    for(i=0;i<p;i++)
        {
        scanf("%d%d",&a[i][0],&a[i][1]);
        }
    printf("enter the no of terms in second polynomial= ");
    scanf("%d",&q);

    printf("enter coefficient and exponent of first polynomial\n");
    for(i=0;i<q;i++)
        {
        scanf("%d%d",&b[i][0],&b[i][1]);
        }
    printf("first polynomial= ");
    for(i=0;i<p;i++)
        {
        printf("(%d)x^(%d)",a[i][0],a[i][1]);
        if(i<(p-1))
        printf("+");
        }
printf("\nsecond polynomial= ");
    for(i=0;i<q;i++)
        {
        printf("(%d)x^(%d)",b[i][0],b[i][1]);
        if(i<(q-1))
        printf("+");
        }
        printf("\n\n");
        /*multiplication goes here*/
for(i=0;i<p;i++)
    {
    for(j=0;j<q;j++)
        {
        m[k][0]=a[i][0]*b[j][0];
        m[k][1]=a[i][1]+b[j][1];
                k++;
        }
    }
  /*sorting the result after multiplication*/
for(i=1;i<(p*q);i++)
    {
    for(j=1;j<(p*q);j++)
        {
        if(m[j-1][1]<m[j][1])
            {
            temp1=m[j-1][1];
            temp2=m[j-1][0];
            m[j-1][1]=m[j][1];
            m[j-1][0]=m[j][0];
            m[j][1]=temp1;
            m[j][0]=temp2;
            }
        }
    }
        /*adding similar terms*/
     u[0][0]=m[0][0],u[0][1]=m[0][1];k=0;
     for(i=0;i<(p*q);i++)
        {
        if(m[i][1]==m[i+1][1])
            {
            u[k][0]+=m[i+1][0];
            u[k][1]=m[i+1][1];
            }
        if(m[i][1]!=m[i+1][1])
            {
            k++;
            u[k][0]=m[i+1][0];
            u[k][1]=m[i+1][1];
            }
        }
     printf("\nMultiplication of two polynomials:\n");
    for(i=0;i<k;i++)
        {
        printf("(%d)x^(%d)",u[i][0],u[i][1]);
        if(i<(k-1))
        printf("+");
        }
    getch();
    }