multiply polynoms from array coeficients in javascript

To multiply polynomials from their coefficients using JavaScript, you can follow the below approach:

  1. Create two arrays to represent your polynomials. Each entry of the array will represent the coefficient of a term in the polynomial. For example, the array [1, 2, 3] represents the polynomial 1 + 2*x + 3*x^2.
index.tsx
let poly1 = [1, 2, 3];
let poly2 = [2, 3, 4];
46 chars
3 lines
  1. Create an empty array to store the coefficients of the product polynomial. The length of this array should be the sum of the lengths of the other two arrays (minus one, since the highest degree term doesn't need to be multiplied).
index.tsx
let product = new Array(poly1.length + poly2.length - 1).fill(0);
66 chars
2 lines
  1. Loop over each term in the first polynomial.
index.tsx
for (let i = 0; i < poly1.length; i++)
39 chars
2 lines
  1. Inside this loop, loop over each term in the second polynomial.
index.tsx
for (let j = 0; j < poly2.length; j++)
39 chars
2 lines
  1. Multiply the two coefficients together, and add the result to the appropriate index in the product array. This index is given by the sum of the two loop counters. For example, the coefficient of the x^3 term (which corresponds to i+j=3 in this case) is stored in product[3].
index.tsx
product[i + j] += poly1[i] * poly2[j];
39 chars
2 lines
  1. After both loops complete, the product array will contain the coefficients of the product polynomial. You can use this array to construct a new array that represents the polynomial itself.
index.tsx
//[2,7,16,17,12] represents (1 + 2x + 3x²) * (2 + 3x + 4x²) = (2 + 7x + 16x² + 17x³ + 12x^4)
console.log(product);
115 chars
3 lines

Here's the complete code:

index.tsx
let poly1 = [1, 2, 3];
let poly2 = [2, 3, 4];
let product = new Array(poly1.length + poly2.length - 1).fill(0);

for (let i = 0; i < poly1.length; i++) {
    for (let j = 0; j < poly2.length; j++) {
        product[i + j] += poly1[i] * poly2[j];
    }
}

console.log(product);
277 chars
12 lines

related categories

gistlibby LogSnag