多项式除法编程怎么写

时间:2025-03-04 04:48:40 明星趣事

多项式除法可以通过模拟手工长除法的过程来实现。下面是一个用C++编写的多项式除法示例代码:

```cpp

include

include

include

using namespace std;

// 定义多项式节点结构

struct PolyNode {

int coef;// 系数

int exp; // 指数

PolyNode* next; // 指向下一个节点的指针

};

// 创建多项式链表

PolyNode* createPoly(const vector>& poly) {

PolyNode* head = nullptr;

PolyNode* tail = nullptr;

for (const auto& term : poly) {

PolyNode* node = new PolyNode{term.second, term.first, nullptr};

if (!head) {

head = node;

tail = node;

} else {

tail->next = node;

tail = node;

}

}

return head;

}

// 打印多项式

void printPoly(PolyNode* poly) {

bool isFirst = true;

while (poly) {

if (!isFirst) cout << " + ";

isFirst = false;

cout << poly->coef << "x^" << poly->exp;

poly = poly->next;

}

cout << endl;

}

// 多项式除法

void polyDiv(PolyNode* dividend, PolyNode* divisor, PolyNode*& quotient, PolyNode*& remainder) {

quotient = nullptr;

remainder = dividend;

while (remainder && remainder->exp >= divisor->exp) {

int coeff = remainder->coef / divisor->coef;

int exp = remainder->exp - divisor->exp;

PolyNode* node = new PolyNode{coeff, exp, nullptr};

if (!quotient) {

quotient = node;

} else {

PolyNode* temp = quotient;

while (temp->next && temp->next->exp > exp) {

temp = temp->next;

}

node->next = temp->next;

temp->next = node;

}

remainder = remainder->next;

while (remainder && remainder->exp >= divisor->exp) {

remainder->coef -= coeff * divisor->coef;

remainder = remainder->next;

}

}

}

int main() {

// 示例多项式

vector> dividend = {{1, 4}, {2, 3}, {3, 2}, {4, 1}}; // 1 + 2x + 3x^2 + 4x^3

vector> divisor = {{1, 1}, {1, -1}};// x - 1

// 创建多项式链表

PolyNode* polyDividend = createPoly(dividend);

PolyNode* polyDivisor = createPoly(divisor);

// 进行多项式除法

PolyNode* quotient, *remainder;

polyDiv(polyDividend, polyDivisor, quotient, remainder);

// 输出结果

cout << "Quotient: ";

printPoly(quotient);

cout << "Remainder: ";

printPoly(remainder);

// 清理内存

delete polyDividend;

delete polyDivisor;

delete quotient;

delete remainder;

return 0;

}

```

这段代码首先定义了一个多项式节点的结构`PolyNode`,然后实现了创建多项式链表、打印多项式和多项式除法的函数。在`main`函数中,我们创建了两个多项式链表表示被除数和除数,并调用`polyDiv`函数进行除法运算,最后输出商和余数。

请注意,这个代码示例假设输入的多项式系数为非负整数,并且按照指数递减的顺序给出。在实际应用中,可能需要对输入进行验证和处理。此外,这个代码没有考虑除数为零的情况,实际应用中应该添加相应的错误检查。