\usepackage{scalerel,mathtools}
\setcounter{MaxMatrixCols}{20}
\usepackage{graphicx,multirow,pgffor}
\usepackage{hyperref}
\newcommand{\PhantC}{\phantom{\colon}}
\newcommand{\CenterInCol}[1]{\multicolumn{1}{c}{#1}}
\newcommand{\longdiv}{\smash{\mkern-0.43mu\vstretch{1.5}{\hstretch{.7}{|}}}}
\begin{document}
\[
\arraycolsep=6pt
\renewcommand\arraystretch{1.2}
\begin{array}{l@{\hskip\arraycolsep}l@{\hskip\arraycolsep}r}
& & a_1= y_2x_4 - y_3x_1^2 + y_3x_4^2 - y_4x_1^3 + y_4x_4^3 \\
& & a_2=-y_2x_4 - y_3x_4^2 - y_4x_4^3 \\
\cline{2-3}
y_1+y_2x_4+y_3x_4^2+y_4x_4^3 & \longdiv & y_1y_2x_4 - y_1y_3x_1^2 +
y_1y_3x_4^2 - y_1y_4x_1^3 + y_1y_4x_4^3 + y_2^2x_1x_4 +
y_2y_3x_1x_4^2 + y_2y_4x_1x_4^3\\
-y_2x_1+y_2x_4-y_3x_1^2+y_3x_4^2-y_4x_1^3+y_4x_4^3 & \longdiv &
\end{array}
\]
\end{document}
I need some help in writing this long division as it is going out of the page.
The problem that I am facing while writing long division in latex is when the divisor and the dividend are 3 line long polynomials.In those cases my polynomials are going out of the page.
You could just write the dividend over 2 lines, just like you did for the divisor. The following should hopefully stay within the margins of your page:
\[
\arraycolsep=6pt
\renewcommand\arraystretch{1.2}
\begin{array}{l@{\hskip\arraycolsep}l@{\hskip\arraycolsep}r}
& & a_1= y_2x_4 - y_3x_1^2 + y_3x_4^2 - y_4x_1^3 + y_4x_4^3 \\
& & a_2=-y_2x_4 - y_3x_4^2 - y_4x_4^3 \\
\cline{2-3}
y_1+y_2x_4+y_3x_4^2+y_4x_4^3-y_2x_1
& \longdiv & y_1y_2x_4 - y_1y_3x_1^2 + y_1y_3x_4^2 - y_1y_4x_1^3 + y_1y_4x_4^3 \\
+y_2x_4-y_3x_1^2+y_3x_4^2-y_4x_1^3+y_4x_4^3
& \longdiv & + y_2^2x_1x_4 + y_2y_3x_1x_4^2 + y_2y_4x_1x_4^3
\end{array}
\]
This works for 12pt font on US letter paper with standard 1 inch margins, and on A4 paper with 2.5 cm margins.