Example polynomials: A = 3x + 2x + 1

advertisement
clark
cs1713
syllabus
lecture notes
programming assignments
Representing Polynomials
Polynomials can have terms which could have almost any exponent. How
can we represent them?
Approach #1: store as an array with the exponents as subscripts and the
coefficients as the element value.
For example A:
subscr
0
1
2
3
4
5
6
ipt
coeff
1
0
0
2
0
0
3
Example
A =
B =
C =
homework
set up
polynomials:
3x6 + 2x3 + 1
8x14 - 3x6 + 10x4 + 5X3
5x211 + 4x3
Are there any issues with this approach?
Representing Polynomials
Approach #2: store as a linked list
For example A:
For example C:
How would we populate a polynomial?
Use insertLL, but
 What are we ordering by?
 Do we want that ordering to be ascending or descending?
.
typedef struct
{
double dCoeff;
int iExponent;
} PolyTerm;
// coefficient
// exponent
typedef struct Node
{
PolyTerm term;
struct Node *pNext;
} Node;
Node *pHead = NULL;
Node *pPolyAHead = NULL;
Node *pFind;
PolyTerm term;
//
6
// insert 3x
term.dCoeff = 3;
term.iExponent = 6;
pFind = insertLL(&pPolyAHead, term);
//
3
// insert 2x
term.dCoeff = 2;
term.iExponent = 3;
pFind = insertLL(&pPolyAHead, term);
// insert 1
term.dCoeff = 1;
term.iExponent = 0;
pFind = insertLL(&pPolyAHead, term);
How would searchLL change?
How would insertLL change?
// this has been changed to support descending exponents
Node *searchLL(Node *pHead, int iMatch, Node **ppPrecedes)
{
Node *p;
*ppPrecedes = NULL;
for (p = pHead; p != NULL; p = p->pNext)
{
if (iMatch == p->term.iExponent)
return p;
if (iMatch > p->term.iExponent)
return NULL;
*pprecedes = p;
}
return NULL;
}
// this has been changed to support polynomials
Node *insertLL(Node **ppHead, PolyTerm term)
{
Node *pNew;
Node *pPrecedes;
Node *pFind;
// see if it already exists
pFind = searchLL(*ppHead, term.iExponent, &pPrecedes);
if (pFind != NULL)
return(pFind);
// already exists
pNew = allocateNode(term);
if (pPrecedes == NULL)
// at front of list
{
pNew->pNext = *ppHead;
*ppHead = pNew;
}
else
{
// after a node
pNew->pNext = pPrecedes->pNext;
pPrecedes->pNext = pNew;
}
return pNew;
}
Take the first derivative
For f(x) = 3x6 + 2x3 + 1,
f'(x) = 18x5 + 6x2
Show code for Node * firstDerivative(Node *pPolyHead) which finds the
first derivative of the specified polynomial and returns a pointer to that
new polynomial.
Node * firstDerivative(Node *pPolyHead)
{
Node *pNewPolyHead = NULL;
??
}
Adding Polynomials
Adding
A = 3x6 + 2x3 + 1
B = 8x14 - 3x6 + 10x4 + 5X3
Would give us this answer
14
Ans = 8x + 0x6 + 10x4 + 7X3 + 1
= 8x14 + 10x4 + 7X3 + 1
What is the algorithm to add two polynomials?
Download