/**************************************************** * This program multiplies a polynomial P(x) by a * * polynomial Q(x) * * ------------------------------------------------- * * Ref.: "Mathématiques en Turbo-Pascal By M. Ducamp * * and A. Reverchon (vol 2), Eyrolles, Paris, 1988" * * [BIBLI 05]. * * ------------------------------------------------- * * SAMPLE RUN: * * * * MULTIPLY TWO POLYNOMIALS: * * * * P(X) = x3 - 6x + 7 * * Q(x) = 5x5 -3x4 +x2 -3 * * * * +5 X8 -3 X7 -30 X6 +54 X5 -21 X4 -9 X3 +7 X2 * * * * +18 X -21 * * * * ------------------------------------------------- * * Functions used (of unit Polynoms): * * * * AddNumber(), EnterPolynom(), DisplayPolynom() * * and MultNumber(). * * * * C++ version by J-P Moreau. * * (To be linked with polynoms.cpp).* * (www.jpmoreau.fr) * ****************************************************/ #include #include #include #include "polynoms.h" ar_polynom *P, *Q, *R; // P(X) * Q(X) = R(X) - R can be either P or Q bool MultPolynom(ar_polynom *P, ar_polynom *Q, ar_polynom *R) { int i,j, n; ar_number u; ar_polynom *nr; nr = (ar_polynom *) calloc(1,sizeof(ar_polynom)); //verify that P and Q are not void if (P->degree==0 && P->coeff[0].value==0) return FALSE; if (Q->degree==0 && Q->coeff[0].value==0) return FALSE; nr->degree=P->degree+Q->degree; if (nr->degree>AR_MAXPOL) return FALSE; // R degree is too big for (n=0; n<=nr->degree; n++) { if (!SetNumber(&nr->coeff[n],"0")) return FALSE; for (i=0; i<=P->degree; i++) { j=n-i; if (j>=0 && j<=Q->degree) { if (!MultNumber(P->coeff[i],Q->coeff[j],&u)) return FALSE; if (!AddNumber(nr->coeff[n],u,&nr->coeff[n])) return FALSE; } } } //copy nr in R R->degree=nr->degree; for (i=0; i<=nr->degree; i++) R->coeff[i]=nr->coeff[i]; free(nr); return TRUE; } void main() { //dynamic memory allocation of polynomials P = (ar_polynom *) calloc(1,sizeof(ar_polynom)); Q = (ar_polynom *) calloc(1,sizeof(ar_polynom)); R = (ar_polynom *) calloc(1,sizeof(ar_polynom)); printf("\n MULTIPLY TWO POLYNOMIALS:\n\n"); if (!EnterPolynom(" P(X) = ", P)) return; if (!EnterPolynom(" Q(X) = ", Q)) return; printf("\n"); if (MultPolynom(P,Q,R)) DisplayPolynom(R); else printf(" Error in multiplication.\n"); printf("\n\n"); free(P); free(Q); free(R); } //end of file multpol.cpp