Click here to download the code in pdf
/*C program for polynomial multiplication:-*/
#include<stdio.h>
#include<stdlib.h>
#define INT_MIN -32767
typedef struct polynomial
{
int Exp;
int Coef;
struct polynomial *next;
}polynomial;
polynomial *get()
{
polynomial *temp, *New, *last;
int Exp, flag;
int Coef;
temp = NULL;
flag = 1;
/*Enter polinomial in descending order of exponent
Enter INT_MIN for exponent to terminate */
do
{
/*Enter Coefficient and Exponent*/
scanf("%d%d", &Coef, &Exp);
if(Exp == INT_MIN)
break;
/* Allocate new polynomial */
New = (polynomial *)malloc(sizeof(polynomial));
New -> Coef = Coef;
New -> Exp = Exp;
New -> next = NULL;
if(flag == 1)
{
temp = New;
last = temp;
flag = 0;
}
else
{
last->next = New;
last = New;
}
}while(1);
return temp;
}
void show(polynomial *head)
{
polynomial *Curr;
Curr = head;
if(Curr == NULL)
{
printf("The polynomial is empty\n");
return;
}
while(Curr != NULL)
{
if (Curr->Exp != 0)
printf("%dx^%d",Curr->Coef, Curr->Exp );
else
printf("%d",Curr->Coef);
Curr = Curr->next;
if(Curr != NULL)
if(Curr->Coef > 0)
printf(" + ");
}
printf("\n");
}
polynomial *Attach(int Exp, int Coef, polynomial *third)
{
polynomial *New, *tmp;
New = (polynomial *)malloc(sizeof(polynomial));
New->Exp = Exp;
New->Coef = Coef;
New->next = NULL;
tmp = third;
tmp->next = New;
tmp = New;
return(tmp);
}
polynomial *mul(polynomial *First, polynomial *Second)
{
polynomial *p1, *p2, *third, *dummy, *temp;
int Exp, flag;
int Coef;
p1 = First;
third = (polynomial *)malloc(sizeof(polynomial));
third->next = NULL;
dummy = third;
while(p1 != NULL)
{
p2 = Second;
while(p2 != NULL)
{
Coef = p1->Coef * p2->Coef;
Exp = p1->Exp + p2->Exp;
temp = dummy->next;
flag = 0;
while(temp != NULL && !flag)
{
if(temp->Exp == Exp)
flag = 1;
else
temp = temp->next;
}
if(flag == 1)
{
temp->Coef = temp->Coef + Coef;
}
else
third = Attach(Exp, Coef, third);
p2 = p2->next;
}
p1 = p1->next;
}
third->next = NULL;
third = dummy->next;
free(dummy);
return third;
}
int main()
{
polynomial *First, *Second, *ans;
polynomial *get(), *mul(polynomial *, polynomial *);
void show(polynomial *);
First = get();
Second = get();
printf("First Polinomial:-\n");
show(First);
printf("Second Polinomial:-\n");
show(Second);
ans = mul(First, Second);
printf("Resultant Polinomial:-\n");
show(ans);
return(0);
}Click here for a better view of this code
No comments:
Post a Comment