create polynomial from array multiply them return only coeficients in javascript

To create a polynomial from an array of coefficients, we can use the reduce() method on the provided array. We start by initializing our polynomial string with the first coefficient of the array. For each subsequent coefficient in the array, we append a term to our polynomial string that includes the coefficient and the degree of that term.

Here's the code that implements this algorithm:

index.tsx
function createPolynomial(coefficients) {
  const polynomial = coefficients.reduce((poly, coef, degree) => {
    if (degree === 0) {
      // initialize the polynomial with the first coefficient
      return `${coef}`;
    } else if (coef === 0) {
      // don't add this term if coefficient is 0
      return poly;
    } else {
      // add a term to the polynomial string for this coefficient
      const xTerm = degree === 1 ? 'x' : `x^${degree}`;
      const sign = coef > 0 ? '+' : '-';
      return `${poly} ${sign} ${Math.abs(coef)}${xTerm}`;
    }
  }, '');

  return polynomial.trim();
}

const coefficients = [1, -2, 3, 0, 5];
const polynomial = createPolynomial(coefficients);
console.log(polynomial); // Output: "1 - 2x + 3x^2 + 5x^4"
747 chars
23 lines

This code assumes that the coefficients are in descending order of degree, i.e., coefficients[0] is the coefficient of the highest degree term. The output of createPolynomial() is a string representing the polynomial in standard form (i.e., descending order of degree with no missing terms). The polynomial string also excludes the variable symbol (e.g., "x") and any exponent with a coefficient of 1.

related categories

gistlibby LogSnag