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 <iostream>
#include <vector>

using namespace std;

struct Factor {
	int coef;
	int freq;
};
typedef vector<Factor> PolyType;

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) {
	vector<PolyType> tempMulResult;
	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();
}

结束:

 就这。

发布了12 篇原创文章 · 获赞 15 · 访问量 3182

猜你喜欢

转载自blog.csdn.net/a1341398182/article/details/104591193