Last active
September 20, 2022 17:50
-
-
Save Minecraftian14/ce683c814bd095c46893c27d98eab35a to your computer and use it in GitHub Desktop.
Single Variate Polynomial Multiplication
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
typedef struct n { | |
float coef; | |
int exp; | |
struct n *next; | |
} Node; | |
Node *makeNode(float coef, int exp) { | |
Node *n = malloc(sizeof(Node)); | |
n->coef = coef; | |
n->exp = exp; | |
n->next = NULL; | |
return n; | |
} | |
Node *insert(Node *head, float coef, int exp) { | |
if (head == NULL) return makeNode(coef, exp); | |
Node *p = head; | |
while (p->next != NULL) p = p->next; | |
p->next = makeNode(coef, exp); | |
return head; | |
} | |
void printTerm(Node *node) { | |
if (node->coef == 0) return; | |
if (node->coef < 0) printf(" - %.2f", -node->coef); | |
else printf(" + %.2f", node->coef); | |
if (node->exp == 0) return; | |
if (node->exp == 1) printf(" x"); | |
else printf(" x^%d", node->exp); | |
} | |
void print(Node *head) { | |
do printTerm(head); | |
while ((head = head->next) != NULL); | |
printf("\n"); | |
} | |
Node *addition(Node *p1, Node *p2) { | |
Node *res = NULL; | |
while (p1 != NULL && p2 != NULL) { | |
if (p1->exp > p2->exp) | |
(res = insert(res, p1->coef, p1->exp), p1 = p1->next); | |
else if (p1->exp < p2->exp) | |
(res = insert(res, p2->coef, p2->exp), p2 = p2->next); | |
else | |
(res = insert(res, p1->coef + p2->coef, p2->exp), | |
p1 = p1->next, p2 = p2->next); | |
} | |
while (p1 != NULL) | |
(res = insert(res, p1->coef, p1->exp), p1 = p1->next); | |
while (p2 != NULL) | |
(res = insert(res, p2->coef, p2->exp), p2 = p2->next); | |
return res; | |
} | |
Node *multiplication(Node *p1, Node *p2) { | |
Node *res = NULL; | |
Node *temp = NULL, *p; | |
while (p1 != NULL) { | |
temp = NULL; | |
p = p2; | |
do temp = insert(temp, p1->coef * p->coef, p1->exp + p->exp); | |
while ((p = p->next) != NULL); | |
res = addition(res, temp); | |
p1 = p1->next; | |
} | |
return res; | |
} | |
int main() { | |
Node *poly1 = NULL; | |
poly1 = insert(poly1, 1, 2); | |
poly1 = insert(poly1, -2, 1); | |
poly1 = insert(poly1, 1, 0); | |
print(poly1); | |
Node *poly2 = NULL; | |
poly2 = insert(poly2, 1, 1); | |
poly2 = insert(poly2, -1, 0); | |
print(poly2); | |
Node *poly3 = multiplication(poly1, poly2); | |
print(poly3); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment