create polynomial from array and multiply them in javascript

To create a polynomial from an array in JavaScript, the index of the element in the array represents the power of the term and the value of the element in the array represents the coefficient of the term. For example, if the array is [1, 2, 3], the corresponding polynomial is 1x² + 2x + 3.

To multiply two polynomials, you'll need to perform the distributive property. For each term in the first polynomial, multiply it by every term in the second polynomial, and then add the results. Here's an implementation:

index.tsx
function createPolynomial(arr) {
  let poly = "";
  for (let i = arr.length - 1; i >= 0; i--) {
    if (arr[i] !== 0) { // only add non-zero terms
      let sign = arr[i] > 0 ? "+" : "-";
      let coef = Math.abs(arr[i]);
      let power = i === 0 ? "" : i === 1 ? "x" : "x^" + i;
      poly += ` ${sign} ${coef}${power}`;
    }
  }
  return poly.replace(/^\s*\+/, ""); // remove leading plus sign
}

function multiplyPolynomials(poly1, poly2) {
  let result = [];
  let degree = poly1.length + poly2.length - 2; // highest degree of result
  for (let i = 0; i <= degree; i++) {
    result[i] = 0;
    for (let j = 0; j <= i; j++) {
      result[i] += (poly1[j] || 0) * (poly2[i - j] || 0);
    }
  }
  return createPolynomial(result);
}

let poly1 = [1, 2, 3]; // 1x² + 2x + 3
let poly2 = [4, 5]; // 4x + 5
let result = multiplyPolynomials(poly1, poly2); // 4x³ + 13x² + 22x + 15
console.log(result);
903 chars
30 lines

In this example, createPolynomial takes an array and returns a formatted string representing the corresponding polynomial. multiplyPolynomials takes two arrays of coefficients and returns a string representing the product polynomial.

related categories

gistlibby LogSnag