Polynomial Handout
CS 400

J. Dichter

/////// File: Poly.h ///////

class Poly

{ public:

Poly(int *p, int terms); // constructor

Poly operator+(Poly q); // poly addition

Poly operator-(Poly q); // poly subtraction

Poly operator*(Poly q); // poly multiplication

unsigned int deg() // degree

{ return(pol[0] > 0 ? pol[0] : 0); }

void display(); // display host object

/* other members */

private:

int length(); // length of pol

int *pol;

};

/////// File: Poly.cpp ///////

#include <iostream.h>

#include "Poly.h"

#define MAX(x,y) ((x) > (y) ? (x) : (y))

#define MIN(x,y) ((x) < (y) ? (x) : (y))

Poly::Poly(int *p, int n) // constructor

{ n = 2*n;

pol = new int[n+1]; // dynamic allocation

for ( int i=0 ; i < n ; i++ )

pol[i] = *p++;

pol[n] = -1; // terminator

}

 

int Poly::length() // private member

{ for (int i=0 ; pol[i] > -1 ; i += 2);

return(i+1);

}

 

Poly Poly::operator+(Poly q)

{ int *c, *a, *b, *tmp;

unsigned len, d;

len = length()+q.length()-1;

d = 1+2*(1+ MAX(deg(), q.deg()));

len = MIN(len, d); // max length of answer

tmp = c = new(int[len]); // temporary space for result

a = pol; b = q.pol;

while (*a >= 0) // for each term of a

{ while(*b > *a) // terms in b of higher power

{ *c++ = *b++;

*c++ = *b++;

}

*c++ = *a;

if (*a == *b) // add terms of like power

{ *c = *++a + *++b;

if (*c++ == 0) c -= 2; // terms cancel

b++;

}

else *c++ = *++a; // no terms to combine

a++;

}

while (*b >= 0) {

*c++ = *b++;

*c++ = *b++; } // add left over terms in b

*c = -1; // terminator marker

Poly ans(tmp, (c-tmp)/2); // answer object

delete tmp; // free temporary space

return(ans);

}

void Poly::display()

{ int *p = pol;

switch ( *p )

{ case -1: // zero poly

cout << "0" << endl; break;

case 0: // constant poly

cout << p[1] << endl; break;

default:

cout << '('; // display terms

while ( *p >= 0 )

{ cout << *p << " " << *(p+1);

p += 2;

if (*p != -1) cout << ", ";

}

cout << ")\n";

}

}