如何实现两个多项式合并

mac2024-05-31  48

一、算法分析

现假设有两个多项式,均按升序排列,要将如下两个多项式进行合并,合并后的新序列仍按升序排列:

多项式1:x^2 + 2x^3 + 3x^5

多项式2:x + 2x^2 + 8x^4 + 4x^5

进行合并的基本思路如下:

      多项式1和多项式2均从第一项开始循环,比较其幂指数是否相同。若a1(多项式1中的某一项)的幂指数大于b1(多项式2的某一项)的幂指数,则将a1追加入新申请的数组中;如果b1的幂指数大于a1的幂指数,则将b1追加入新申请的数组中;如果a1和b1的幂指数相同,则将这两项的系数相加,追加入新申请的数组中。循环结束后,若某一多项式仍有项,则将剩余的项全部追加进新申请的多项式。

二、核心代码

POLYNOMIAL *addPoly(const POLYNOMIAL *polyOne,const POLYNOMIAL *polyAnother){ POLYNOMIAL *result = NULL; //先申请一个空多项式数组 initPolynomial(&result,getCapacity(polyOne) + getCapacity(polyAnother)); //数组容量为进行比较的两个数组容量之和 int polyOneIndex = 0; int polyOtherIndex = 0; POLY_ITEM itemOne; POLY_ITEM itenOther; double newCoeff; getElementAt(polyOne,polyOneIndex,&itemOne); getElementAt(polyAnother,polyOtherIndex,&itemOther); While(polyOneIndex < getCount(polyOne) && polyTwoIndex < getCount(polyAnother)){ if(itemOne.expon > itemOther.expon){ appendElementAt(result,itemOne); getElementAt(polyOne,++polyOneIndex,&itemOne); continue; } //a1>b1,将a1追加入新申请的数组,a1后移 if(itemOne.expon < itemOther.expon){ appendElementAt(result,itemOther); getElementAt(polyOne,++polyOneIndex,&itemOther); continue; } //a1<b1,将b1追加入新申请的数组,b1后移 newCoeff = itemOne.coeff + itemOther.coeff; if(fabs(newCoeff) > 1e-6){ itemOne.coeff = newCoeff; appendElementAt(result,itemOne); } //a1=b1,则系数求和,再进行追加 getElementAt(polyOne,++polyOneIndex,&itemOne); getElementAt(polyOne,++polyOneIndex,&itemOther); //a1,b1均后移 } while(polyOneIndex < getCount(polyOne)){ appendElement(result,itemOne); getElementAt(polyOne,++polyOneIndex,&itemOne); //若多项式1未循环结束,则剩余项全部追加 } while(polyOtherIndex < getCoUNT(polyOther)){ appendElement(result,itemOther); getElementAt(polyOther,++polyOtherIndex,&itemOther); 若多项式2未循环结束,则剩余项全部追加 } return result; }

以上讲解若有不当之处,请各位大佬指正。

最新回复(0)