在 C++ 中乘以两个多项式
多项式的各项系数以数组形式给出。我们需要对两个多项式相乘。我们来看一个例子。
输入
A = [1, 2, 3, 4] B = [4, 3, 2, 1]
输出
4x6 + 11x5 + 20x4 + 30x3 + 20x2 + 11x1 + 4
算法
初始化两个多项式。
创建一个长度为两个多项式的数组。
迭代遍历这两个多项式。
取第一个多项式中的一个项,并使用第二个多项式中的所有项对其进行乘法。
将结果存储在结果多项式中。
实现
以下是上述算法在 C++ 中的实现
#include <bits/stdc++.h>
using namespace std;
int *multiplyTwoPolynomials(int A[], int B[], int m, int n) {
int *productPolynomial = new int[m + n - 1];
for (int i = 0; i < m + n - 1; i++) {
productPolynomial[i] = 0;
}
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
productPolynomial[i + j] += A[i] * B[j];
}
}
return productPolynomial;
}
void printPolynomial(int polynomial[], int n) {
for (int i = n - 1; i >= 0; i--) {
cout << polynomial[i];
if (i != 0) {
cout << "x^" << i;
cout << " + ";
}
}
cout << endl;
}
int main() {
int A[] = {1, 2, 3, 4};
int B[] = {4, 3, 2, 1};
int m = 4;
int n = 4;
cout << "First polynomial: ";
printPolynomial(A, m);
cout << "Second polynomial: ";
printPolynomial(B, n);
int *productPolynomial = multiplyTwoPolynomials(A, B, m, n);
cout << "Product polynomial: ";
printPolynomial(productPolynomial, m + n - 1);
return 0;
}输出
如果您运行上述代码,将会得到以下结果。
First polynomial: 4x^3 + 3x^2 + 2x^1 + 1 Second polynomial: 1x^3 + 2x^2 + 3x^1 + 4 Product polynomial: 4x^6 + 11x^5 + 20x^4 + 30x^3 + 20x^2 + 11x^1 + 4
Advertisement
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP