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();
}

結束:

 就這。

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章