c语言 加法 乘法运算,C语言 一元多项式的乘法与加法运算

C语言 一元多项式的乘法与加法运算

设计函数分别求两个一元多项式的乘积与和。

输入格式:

输入分2行,每行分别先给出多项式非零项的个数,再以指数递降方式输入一个多项式非零项系数和指数(绝对值均为不超过1000的整数)。数字间以空格分隔。

输出格式:

输出分2行,分别以指数递降方式输出乘积多项式以及和多项式非零项的系数和指数。数字间以空格分隔,但结尾不能有多余空格。零多项式应输出0 0。

输入样例:

4 3 4 -5 2 6 1 -2 0

3 5 20 -7 4 3 1

输出样例:

15 24 -25 22 30 21 -10 20 -21 8 35 6 -33 5 14 4 -15 3 18 2 -6 1

5 20 -4 4 -5 2 9 1 -2 0

好嘞,废话不多说,上代码:

#include #include using namespace std;

struct Factor {

int coef;

int freq;

};

typedef vectorPolyType;

PolyType polyAdd(PolyType& p1, PolyType& p2);

PolyType polyMul(PolyType& p1, PolyType& p2);

void polyPrint(PolyType&& p);

int main() {

PolyType poly[2];

for (auto& p : poly) {

int polySize;

cin >> polySize;

for (auto i = 0; i < polySize; i++) {

Factor factor{};

cin >> factor.coef >> factor.freq;

p.push_back(factor);

}

if (p.empty()) {

p.push_back({ 0,0 });

}

}

polyPrint(polyMul(poly[0], poly[1]));

cout << endl;

polyPrint(polyAdd(poly[0], poly[1]));

cout << endl;

return 0;

}

void polyPrint(PolyType&& p) {

auto check = [](PolyType& poly) {

for (auto& x : poly) if (x.coef) return false;

return true;

};

if (check(p)) {

cout << "0 0";

return;

}

for (auto it = p.begin(); it != p.end(); ++it) {

if (it->coef) {

if (it == p.begin()) {

cout << it->coef << " " << it->freq;

} else cout << " " << it->coef << " " << it->freq;

}

}

}

PolyType polyAdd(PolyType& p1, PolyType& p2) {

PolyType rtn;

auto itP1 = p1.begin();

auto itP2 = p2.begin();

while (itP1 != p1.end() && itP2 != p2.end())

if (itP1->freq == itP2->freq) {

rtn.push_back({ itP1->coef + itP2->coef, itP1->freq });

++itP1; ++itP2;

} else {

if (itP1->freq > itP2->freq)

rtn.push_back(*itP1++);

else

rtn.push_back(*itP2++);

}

rtn.insert(rtn.end(), itP1, p1.end());

rtn.insert(rtn.end(), itP2, p2.end());

return rtn;

}

PolyType polyMul(PolyType& p1, PolyType& p2) {

vectortempMulResult;

for (auto& factor1 : p1) {

PolyType tempMul;

for (auto& factor2 : p2) {

tempMul.push_back({ factor1.coef * factor2.coef, factor1.freq + factor2.freq });

}

tempMulResult.emplace_back(tempMul);

}

for (auto it = tempMulResult.begin(); it < tempMulResult.end() - 1; ++it) {

*(it + 1) = polyAdd(*it, *(it + 1));

}

return tempMulResult.back();

}

结束:

就这。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值