I've heard that Latex is a Turing complete language. So I went on to write a Fibonacci program in Latex and I succeeded (without using packages). Now I want to write a factorial program in latex (without using packages). I wrote the following code:- (includes debug texts)
\documentclass{article}
\begin{document}
\typein[\n]{Enter the value of n :-}
\newcommand{\scaleup}[2]{
\newcount\ofac
\ofac #1\relax
\newcount\ntemp
\ntemp \the#2\relax
{
\loop
\ifnum \ntemp>1
\advance#1 \the\ofac\relax
\advance\ntemp -1\relax
nfac(m) = \the#1
\nfac \the#1\relax
\repeat
}
}
\newcommand{\factorial}[1]{
\newcount\num
\newcount\nfac
\newcommand{\nfacinloop}{1}
\num #1\relax
\nfac 1\relax
\loop
\ifnum \num>0
% \huge{\the\num}
% \scaleup{\nfac}{\num}
\newcount\ofac
\ofac \nfac\relax
\newcount\ntemp
\ntemp \the\num\relax
{
\loop
\ifnum \ntemp>1
\advance\nfac \the\ofac\relax
\advance\ntemp -1\relax
nfac(m) = \the\nfac
\nfac \the\nfac\relax
\renewcommand{\nfacinloop}{\the\nfac}
nfacinloop = \nfacinloop
\repeat
}
nfac = \the\nfac
nfacinloop = \nfacinloop
% \huge{\the\num}
\advance\num -1\relax
% \huge{\the\num}
\repeat
}
\factorial{\n}
\end{document}
However this does not run, because each time the control exits the inner loop, the value of \nfac is reset to 1. I could not find any (without using packages) to retain the value of \nfac. Am I wrong somewhere? Please help.
Note: I used pdftex to compile.
{}
. You have to prefix assignments with\global
to make changes visible outside. E.g., try\global\nfac \the\nfac\relax
in the loop.\newcounter
..., changes within the loop should be global i.e.\setcounter
,\addtocounter
etc.\newcount
inside the loop, registers are a finite resource (although there are a lot more in etex than classic tex)