Sunday, March 4, 2012

Polynomial Addition

 If the polynomials are not very sparse, we can represent them using arrays. Where index is the exponent and value is the coefficient.How can we add two polynomials represented in arrays.

Code:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct
{
    int* arr;
    int maxExponent;

}Polynomial;


Polynomial add(Polynomial a, Polynomial b)
{
    Polynomial c;

    Polynomial *min,  *max;

    if(a.maxExponent > b.maxExponent)
    {
        max = &a;
        min = &b;
    }
    else
    {
        min = &a;
        max = &b;
    }

    c.arr = (int*)calloc(max->maxExponent + 1, sizeof(int));
    c.maxExponent =  max->maxExponent;

    memcpy(c.arr, max->arr, (max->maxExponent + 1) * sizeof(int));

    int i;

    for(i = 0; i <= min->maxExponent; ++i)
    {
        c.arr[i] += min->arr[i];
    }

    return c;
}

int main()
{
    int a[] = {10, 30, 40, 50, 5};
    int b[] = {20, 40, 10, 4};

    Polynomial a1 = {a, 4};
    Polynomial a2 = {b, 3};


    Polynomial c = add(a1, a2);

    int i;

    for(i = 0; i <= c.maxExponent; i++)
        printf("%d ", c.arr[i]);

    printf("\n");
    system("pause");
    return 0;
}

No comments:

Post a Comment