Polynomial Long Division

by wio_dude

HTML

<script>
MathJax = {
  tex: {
    inlineMath: [['$', '$'], ['\\(', '\\)']]
  }
};
</script>
<script id="MathJax-script" async
  src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-chtml.js">
</script>
<h1>Polynomial Long Division</h1>
<h2>Calculator</h2>
Divide <input id="dividend" type="text" value="4x^4+3x-1" /> by <input id="divisor" type="text" value="x^2+3" />
<br />
<div id="result" class="math-tex"></div>

<h2>Instructions</h2>
<ol>
<li>Divide the highest degree term in the dividend by the highest degree term in the divisor.</li>
<li>Multiply the result by the divisor</li>
<li>Subtract the result from the dividient</li>
</ol>

CSS

input {
  text-align: center;
}

JavaScript

const ids = ['dividend', 'divisor', 'result', 'mathjax'];
const $e = {};
for (const id of ids) {
  $e[id] = document.getElementById(id);
}

$e.dividend.addEventListener('input', (_evt) => {
  update();
});

$e.divisor.addEventListener('input', (_evt) => {
  update();
});


class Polynomial extends Array {
  static parse(text) {
    const polynomial = new Polynomial();
    const terms = text.replace(/-/, '+-').split(/\+/);
    for (const term of terms) {
      const parts = term.trim().split(/x\^?/);
      if (parts.length === 1) {
        const coeff = parseFloat(parts[0]);
        polynomial.addCoeff(0, coeff);
        continue;
      }
      let [co, pow] = parts;

      const coeff = co.length === 0 ? 1 : parseFloat(co);
      const power = pow.length === 0 ? 1 : parseInt(pow, 10);
      polynomial.addCoeff(power, coeff);
    }
    return polynomial;
  }

  static fromTerm(coeff, power) {
    const polynomial = new Polynomial();
    polynomial.addTerm(coeff, power);
    return polynomial;
  }

  constructor() {
  	super(1);
    this[0] = 0;
  }
  
  getCoeff(power) {
  	return this.length > power ? this[power] : 0;
  }
  
  addCoeff(power, coeff) {
  	if (coeff === 0) {
    	return;
    }
    while (this.length <= power) {
      this.push(0);
    }
    this[power] += coeff;
  }

  addTerm(coeff, power) {
    while (this.length <= power) {
      this.push(0);
    }
    this[power] += coeff
  }

  highDivide(that) {
    const power = this.length - that.length;
    if (power < 0) {
      return null;
    }
    const thatCoeff = that.at(-1);
    if (thatCoeff === 0) {
      return null;
    }
    const thisCoeff = this.at(-1);
    const coeff = thisCoeff / thatCoeff;
    return [coeff, power];
  }

  multiply(that) {
    const product = new Polynomial();
    for (const [e1, c1] of this.entries()) {
      for (const [e2, c2] of that.entries()) {
        product.addCoeff(e1 + e2, c1 * c2);
      }
    }
    return product;
  }
  
  subtract(that) {
  	const...