Untitled

mail@pastecode.io avatarunknown
plain_text
2 months ago
1.7 kB
1
Indexable
Never
#include <stdio.h>
#include <stdlib.h>

struct node {
    int coeff;
    int exp;
    struct node *next;
};

struct node *insert(struct node *head, int coeff, int exp) {
    struct node *new_term = (struct node *)malloc(sizeof(struct node));
    new_term->coeff = coeff;
    new_term->exp = exp;
    new_term->next = NULL;
    
    if (head == NULL) {
        return new_term;
    }
    
    struct node *curr = head;
    while (curr->next != NULL) {
        curr = curr->next;
    }
    curr->next = new_term;
    return head;
}

struct node *multipoly(struct node *poly1, struct node *poly2) {
    struct node *result = NULL;
    for (struct node *term1 = poly1; term1 != NULL; term1 = term1->next) {
        for (struct node *term2 = poly2; term2 != NULL; term2 = term2->next) {
            int coeff = term1->coeff * term2->coeff;
            int exp = term1->exp + term2->exp;
            result = insert(result, coeff, exp);
        }
    }
    return result;
}

void display(struct node *poly) {
    struct node *curr = poly;
    while (curr != NULL) {
        printf("(%d)x^%d", curr->coeff, curr->exp);
        curr = curr->next;
        if (curr != NULL) {
            printf("+");
        }
    }
    printf("\n");
}

int main() {
    struct node *poly1 = NULL;
    struct node *poly2 = NULL;

    poly1 = insert(poly1, 4, 3);
    poly1 = insert(poly1, 7, 1);
    poly1 = insert(poly1, 5, 0);

    poly2 = insert(poly2, 5, 3);
    poly2 = insert(poly2, 3, 2);
    poly2 = insert(poly2, 1, 0);

    printf("Polynomial 1: ");
    display(poly1);

    printf("Polynomial 2: ");
    display(poly2);

    struct node *result = multipoly(poly1, poly2);

    printf("Resultant Polynomial: ");
    display(result);

    return 0;
}