Multiply two polynomials in C++

C++Server Side ProgrammingProgramming

The coefficients of each term of the polynomial are given in an array. We need to multiply the two polynomials. Let's see an example.

Input

A = [1, 2, 3, 4]
B = [4, 3, 2, 1]

Output

4x6 + 11x5 + 20x4 + 30x3 + 20x2 + 11x1 + 4

Algorithm

• Initialise two polynomials.

• Create a new array with a length of two polynomials.

• Iterate over the two polynomials.

• Take one term from the first polynomial and multiply it with all the terms in the second polynomial.

• Store the result in the resultant polynomial.

Implementation

Following is the implementation of the above algorithm in 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;
}

Output

If you run the above code, then you will get the following result.

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