/////// File: Poly.C /////// #include #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 (1) { *c = *++a + *++b; if (*c++ == 0) c -= 2; // terms cancel (2) b++; } else *c++ = *++a; // no terms to combine a++; } while (*b >= 0) *c++ = *b++; // add left over terms in b *c = -1; // terminator 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"; } }