![“算术溢出”错误](https://linux22.com/image/248249/%E2%80%9C%E7%AE%97%E6%9C%AF%E6%BA%A2%E5%87%BA%E2%80%9D%E9%94%99%E8%AF%AF.png)
可以处理高达 12 的阶乘。如何才能计算超出这个范围的阶乘?
错误:“算术溢出
\documentclass{article}
\begin{document}
\newcount\n \newcount\p \newcount\m
\def\factorial#1{{\m=#1\advance\m by 1
\n=1
\p=1
\loop\ifnum\n<\m \multiply\p by \n \advance\n by 1 \repeat\number\p}}
\def\printfactorials#1{\m=#1\advance\m by 1
\n=0
\loop\ifnum\n<\m \hfil\break\number\n! = \factorial{\n} \advance\n by 1 \repeat}
\printfactorials{12}
\end{document}
答案1
使用bigintcalc
(来自oberdiek
捆),可以得到以下输出:
\documentclass{article}
\usepackage{bigintcalc}% http://ctan.org/pkg/bigintcalc
\begin{document}
\newcount\n \newcount\p \newcount\m
\def\factorial#1{%
{\m=#1\advance\m by 1
\n=1
\p=1
\loop\ifnum\n<\m \multiply\p by \n \advance\n by 1 \repeat\number\p}}
\def\printfactorials#1{%
\m=#1\advance\m by 1
\n=0
\loop\ifnum\n<\m \hfil\break\number\n! = \factorial{\n} \advance\n by 1 \repeat}
\def\bigfactorial#1{%
\bigintcalcFac{#1}%
}
\def\printbigfactorials#1{%
\m=#1\advance\m by 1
\n=0
\loop\ifnum\n<\m \hfil\break\number\n! = \bigfactorial{\the\n} \advance\n by 1 \repeat}
%\printfactorials{12}
\printbigfactorials{20}
\end{document}
\bigintcalcXXX
是定义的基本运算符。\bigintcalcFac{<x>}
返回的阶乘<x>
。根据bigintcalc
文档,
包
bigintcalc
定义了处理大整数的算术运算。大整数可以作为显式整数给出,也可以作为扩展为显式数字的宏代码给出。大的表示数字的大小没有限制。大整数可能会超出 TeX 的范围限制 -2147483647 和 2147483647。只有内存问题才会限制可用范围。
答案2
嗯,基本上和 Werners 的回答一样,但我做了一个“基本”的实现\factorial
:-)
\documentclass{article}
\usepackage{bigintcalc}
\usepackage{fullpage}
\begin{document}
\def\factorial#1{{\edef\m{\bigintcalcInc{#1}}%
\def\n{1}%
\def\p{1}%
\loop\ifnum\n<\m\relax\edef\p{\bigintcalcMul\p\n}\edef\n{\bigintcalcInc\n}\repeat\p}}
\def\printfactorials#1{\edef\m{\bigintcalcInc{#1}}%
\def\n{0}%
\loop\ifnum\n<\m\relax \hfil\break\n! = \factorial{\n}
\edef\n{\bigintcalcInc\n}\repeat}
\footnotesize
\printfactorials{70}
\end{document}
嗯,事实上没有必要使用bigintcalc
。\printfactorials
实际上\edef\p{\bigintcalcMul\p\n}
只有它才需要它。