用c++写一个一元稀疏多项式计算器
时间: 2023-07-04 08:24:28 浏览: 50
好的,以下是用C++实现一元稀疏多项式计算器的代码,包括多项式的加法、减法、乘法、求导和积分计算:
```c++
#include <iostream>
#include <unordered_map>
#include <cmath>
using namespace std;
// 定义多项式的项
struct Term {
int coef; // 系数
int exp; // 指数
Term(int c = 0, int e = 0) : coef(c), exp(e) {}
};
// 定义多项式类
class Polynomial {
public:
Polynomial() {}
~Polynomial() {}
// 加法
Polynomial operator+(const Polynomial& other) const {
Polynomial res;
for (auto& term : terms) {
res.terms[term.first] += term.second;
}
for (auto& term : other.terms) {
res.terms[term.first] += term.second;
}
return res;
}
// 减法
Polynomial operator-(const Polynomial& other) const {
Polynomial res;
for (auto& term : terms) {
res.terms[term.first] += term.second;
}
for (auto& term : other.terms) {
res.terms[term.first] -= term.second;
}
return res;
}
// 乘法
Polynomial operator*(const Polynomial& other) const {
Polynomial res;
for (auto& term1 : terms) {
for (auto& term2 : other.terms) {
int exp = term1.first + term2.first;
int coef = term1.second * term2.second;
res.terms[exp] += coef;
}
}
return res;
}
// 求导
Polynomial derivative() const {
Polynomial res;
for (auto& term : terms) {
if (term.first > 0) {
res.terms[term.first - 1] += term.second * term.first;
}
}
return res;
}
// 积分
Polynomial integral() const {
Polynomial res;
for (auto& term : terms) {
res.terms[term.first + 1] += term.second / (term.first + 1);
}
return res;
}
// 打印多项式
void print() const {
bool first = true;
for (auto& term : terms) {
if (term.second == 0) continue;
if (term.second > 0 && !first) {
cout << "+";
}
first = false;
cout << term.second;
if (term.first > 0) {
cout << "x";
if (term.first > 1) {
cout << "^" << term.first;
}
}
}
cout << endl;
}
// 添加项
void add_term(int coef, int exp) {
terms[exp] += coef;
}
private:
unordered_map<int, int> terms; // 哈希表存储多项式的每一项
};
int main() {
Polynomial p1, p2, res;
// 第一个多项式
p1.add_term(2, 3);
p1.add_term(3, 2);
p1.add_term(4, 1);
p1.add_term(5, 0);
cout << "p1(x) = ";
p1.print();
// 第二个多项式
p2.add_term(1, 4);
p2.add_term(2, 3);
p2.add_term(3, 2);
p2.add_term(4, 1);
p2.add_term(5, 0);
cout << "p2(x) = ";
p2.print();
// 加法
res = p1 + p2;
cout << "p1(x) + p2(x) = ";
res.print();
// 减法
res = p1 - p2;
cout << "p1(x) - p2(x) = ";
res.print();
// 乘法
res = p1 * p2;
cout << "p1(x) * p2(x) = ";
res.print();
// 求导
res = p1.derivative();
cout << "dp1(x)/dx = ";
res.print();
// 积分
res = p1.integral();
cout << "∫p1(x)dx = ";
res.print();
return 0;
}
```
以上代码中,我们使用了`unordered_map`来存储多项式的每一项,其中键为指数,值为系数。在多项式的加减乘法中,我们遍历两个多项式的哈希表,对于相同指数的项进行系数相加/相减/相乘,并将结果存储到结果多项式的哈希表中。在求导和积分计算中,我们遍历多项式的哈希表,对于每一项进行求导/积分操作,并将结果存储到结果多项式的哈希表中。最后,我们使用`print`函数打印出多项式的表达式。