methods / longdiv.texon commit update practice exam spreadsheet (e46f1b2)
   1%  longdiv.tex  v.1  (1994)  Donald Arseneau  
   2%
   3%  Work out and print integer long division problems.  Use:
   4%       \longdiv{numerator}{denominator}
   5%  The numerator and denominator (divisor and dividend) must be integers, and
   6%  the quotient is an integer too.  \longdiv leaves a remainder.
   7%  Use this in any type of TeX.
   8
   9\newcount\gpten % (global) power-of-ten -- tells which digit we are doing
  10\countdef\rtot2 % running total -- remainder so far
  11\countdef\LDscratch4 % scratch
  12
  13\def\longdiv#1#2{%
  14 \vtop{\normalbaselines \offinterlineskip
  15   \setbox\strutbox\hbox{\vrule height 2.1ex depth .5ex width0ex}%
  16   \def\showdig{$\underline{\the\LDscratch\strut}$\cr\the\rtot\strut\cr
  17       \noalign{\kern-.2ex}}%
  18   \global\rtot=#1\relax
  19   \count0=\rtot\divide\count0by#2\edef\quotient{\the\count0}%\show\quotient
  20   % make list macro out of digits in quotient:
  21   \def\temp##1{\ifx##1\temp\else \noexpand\dodig ##1\expandafter\temp\fi}%
  22   \edef\routine{\expandafter\temp\quotient\temp}%
  23   % process list to give power-of-ten:
  24   \def\dodig##1{\global\multiply\gpten by10 }\global\gpten=1 \routine
  25   % to display effect of one digit in quotient (zero ignored):
  26   \def\dodig##1{\global\divide\gpten by10
  27      \LDscratch =\gpten
  28      \multiply\LDscratch  by##1%
  29      \multiply\LDscratch  by#2%
  30      \global\advance\rtot-\LDscratch \relax
  31      \ifnum\LDscratch>0 \showdig \fi % must hide \cr in a macro to skip it
  32   }%
  33   \tabskip=0pt
  34   \halign{\hfil##\cr % \halign for entire division problem
  35     $\quotient$\strut\cr
  36     #2$\,\overline{\vphantom{\big)}%
  37     \hbox{\smash{\raise3.5\fontdimen8\textfont3\hbox{$\big)$}}}%
  38     \mkern2mu \the\rtot}$\cr\noalign{\kern-.2ex}
  39     \routine \cr % do each digit in quotient
  40}}}
  41
  42\endinput % Demonstration below:
  43
  44\noindent Here are some long division problems
  45
  46\indent
  47\longdiv{12345}{13} \quad
  48\longdiv{123}{1234} \quad
  49\longdiv{31415926}{2} \quad
  50\longdiv{81}{3} \quad
  51\longdiv{1132}{99} \quad
  52\longdiv{86491}{94}
  53\bye