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
#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 = 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");
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s