Multiply two polynomials in C++

C++Server Side ProgrammingProgramming

In this tutorial, we are going to write a program that multiplies two polynomials. The coefficients of each term of the polynomial is given in an array.

Let's see the steps to solve the problem.

  • 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.

Example

Let's see the code.

 Live Demo

#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

Conclusion

If you have any queries in the tutorial, mention them in the comment section.

raja
Published on 03-Jul-2021 04:43:04
Advertisements