Saturday, May 8, 2010

Polynomial Multiplication

//Polynomial Multiplication

#include
#include
#include

typedef struct poly
{
int coeff,expo;
}P;
P p1[10],p2[10],p3[20]={0};
int t1,t2;

void multiply();

void main()
{
int i,ch;
char cho;
clrscr();

printf("Please enter number of terms in p1: ");
scanf("%d",&t1);
printf("\nPlease enter coeff. & expo of terms in p1\n");
for(i=0;i {
scanf("%d%d",&p1[i].coeff,&p1[i].expo);
}
printf("\n\nPlease enter number of terms in p2: ");
scanf("%d",&t2);
printf("\nPlease enter coeff. & expo of terms in p2\n");
for(i=0;i {
scanf("%d%d",&p2[i].coeff,&p2[i].expo);
}

do
{
clrscr();
printf("First polynomial is\n");
for(i=0;i<(t1-1);i++)
{
printf("(%d x^%d) + ",p1[i].coeff,p1[i].expo);
}
printf("(%d x^%d)",p1[i].coeff,p1[i].expo);
printf("\n\nSecond polynomial is\n");
for(i=0;i<(t2-1);i++)
{
printf("(%d x^%d) + ",p2[i].coeff,p2[i].expo);
}
printf("(%d x^%d)",p2[i].coeff,p2[i].expo);

printf("\n\n\tYour choices are:\n");
printf(" \t1:Multiplication\n \t2:Exit\n\n");
printf("\n\nPlease enter your choice: ");
scanf("%d",&ch);

switch(ch)
{
case 1:
multiply();
break;

case 2:
exit();

default:
printf("\n\nInvalid choice");
}
printf("\nPress y to continue and any other key to stop:");
fflush(stdin);
scanf("%c",&ch);
}
while(cho=='y' || cho=='Y');
getch();
}

void multiply()
{
int i=0,j=0,k=0,cnt=0,exp,coef,flag;
for(i=0;i<20;i++)
{
p3[i].coeff=0;
p3[i].expo=0;
}
i=0;
while(i {
j=0;
while(j {
flag=0;
coef=p1[i].coeff*p2[j].coeff;
exp=p1[i].expo+p2[j].expo;
for(cnt=0;cnt {
if(p3[cnt].expo==exp)
{
p3[cnt].coeff=p3[cnt].coeff+coef;
flag=1;
}
}
if(flag==0)
{
p3[k].expo=exp;
p3[k].coeff=coef;
k++;
}
j++;
}
i++;
}
printf("\nMultiplication is \n");
for(i=0;i<(k-1);i++)
{
printf("(%d x^%d) + ",p3[i].coeff,p3[i].expo);
}
printf("(%d x^%d)",p3[i].coeff,p3[i].expo);
}

No comments: