Multiply two polynomials - GeeksforGeeks
Given two polynomials represented by two arrays, write a function that multiplies given two polynomials.
Read full article from Multiply two polynomials - GeeksforGeeks
Given two polynomials represented by two arrays, write a function that multiplies given two polynomials.
These methods are mainly based ondivide and conquer. Following is one simple method that divides the given polynomial (of degree n) into two polynomials one containing lower degree terms(lower than n/2) and other containing higher degree terns (higher than or equal to n/2)
Let the two given polynomials be A and B. For simplicity, Let us assume that the given two polynomials are of same degree and have degree in powers of 2, i.e., n = 2i The polynomial 'A' can be written as A0 + A1*xn/2 The polynomial 'B' can be written as B0 + B1*xn/2 For example 1 + 10x + 6x2 - 4x3 + 5x4 can be written as (1 + 10x) + (6 - 4x + 5x2)*x2 A * B = (A0 + A1*xn/2) * (B0 + B1*xn/2) = A0*B0 + A0*B1*xn/2 + A1*B0*xn/2 + A1*B1*xn = A0*B0 + (A0*B1 + A1*B0)xn/2 + A1*B1*xn
So the above divide and conquer approach requires 4 multiplications and O(n) time to add all 4 results. Therefore the time complexity is T(n) = 4T(n/2) + O(n). The solution of the recurrence is O(n2) which is same as the above simple solution.
The idea is to reduce number of multiplications to 3 and make the recurrence as T(n) = 3T(n/2) + O(n)
How to reduce number of multiplications?
This requires a little trick similar to Strassen’s Matrix Multiplication. We do following 3 multiplications.
This requires a little trick similar to Strassen’s Matrix Multiplication. We do following 3 multiplications.
X = (A0 + A1)*(B0 + B1) // First Multiplication Y = A0B0 // Second Z = A1B1 // Third The missing middle term in above multiplication equation A0*B0 + (A0*B1 + A1*B0)xn/2 + A1*B1*xn can obtained using below. A0B1 + A1B0 = X - Y - Z
So the time taken by this algorithm is T(n) = 3T(n/2) + O(n)
The solution of above recurrence is O(nLg3) which is better than O(n2).
The solution of above recurrence is O(nLg3) which is better than O(n2).
A simple solution is to one by one consider every term of first polynomial and multiply it with every term of second polynomial. Following is algorithm of this simple method.
multiply(A[0..m-1], B[0..n01]) 1) Create a product array prod[] of size m+n-1. 2) Initialize all entries in prod[] as 0. 3) Travers array A[] and do following for every element A[i] ...(3.a) Traverse array B[] and do following for every element B[j] prod[i+j] = prod[i+j] + A[i] * B[j] 4) Return prod[].
The following is C++ impl
Read full article from Multiply two polynomials - GeeksforGeeks