# Formatting of polynomial long division with variable coefficients

Using the polynom package, I have been able to perform polynomial long division as so:

\usepackage{polynom}
$\polylongdiv{2x^2+3x+4}{x-1}$


However, I wish to perform polynomial long division with variable coefficients. My main trouble with this is formatting it to have the correct alignment. Going line by line from top to bottom in the same fashion as the output of \polylongdiv{}:

$\frac{a_{n}}{m_{d}}x+(\frac{b_{n}}{m_{d}}-\frac{c_{d}a_{n}}{m_{d}^2})$
$m_{d}x+c_{d}~)\overline{a_{n}x^2+b_{n}x+c_{n}}$
$\underline{-(a_{n}x^2+\frac{c_{d}a_{n}}{m_{d}}x)}$
$(b_{n}-\frac{c_{d}a_{n}}{m{d}})x+c_{n}$
$\underline{-((b_{n}-\frac{c_{d}a_{n}}{m{d}})x+(\frac{c_{d}b_{n}}{m_{d}}-\frac{c_{d}^2a_{n}}{m_{d}^2}))}$
$c_{n}-\frac{c_{d}}{m_{d}}(b_{n}-a_{n}\frac{c_{d}}{m_{d}})$


Any help in formatting this would be appreciated.

The following screenshot shows, side-by-side, the outputs of \polylong and of an equivalent array environment. The outputs are virtually identical. (Well, the vertical spacing of the array-based solution is every so slightly larger on balance, but let's call this "close enough".)

Is the structure of the array sufficiently clear for you to plug in the corresponding variable coefficients? E.g., in the first row you'd replace 2 and 5 with \frac{a_{n}}{m_{d}} and \Bigl(\frac{b_n}{m_d}-\frac{c_da_n}{m_d^2}\Bigr), respectively. In the second row, you'd replace x-1, 2, 3, and 4 with m_d x+c_d, a_n, b_n, and c_n, respectively. And so on. \documentclass{article}
\usepackage{array,polynom}
\newcolumntype{C}{>{{}}c<{{}}} % for '+' and '-' symbols
\newcolumntype{R}{>{\displaystyle}r} % automatic display-style math mode
\begin{document}
$\polylongdiv{2x^2+3x+4}{x-1} \qquad \setlength\arraycolsep{0pt} \setlength\extrarowheight{2pt} \begin{array}[t]{ RCRCRCR } & & & & 2x & + & 5 \\ \cline{2-7} x-1 \bigl) & & 2x^2 & + & 3x & + & 4 \\ & - & 2x^2 & + & 2x & & \\ \cline{2-5} & & & & 5x & + & 4 \\ & & & - & 5x & + & 5 \\ \cline{4-7} & & & & & & 9 \end{array}$
\end{document}