You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用algpseudocode包编写LaTeX算法报错Missing \endcsname inserted求解

LaTeX algpseudocode编译报错「Missing \endcsname inserted」的解决

问题场景

使用algpseudocode包编写算法时,出现「Missing \endcsname inserted」编译错误,但最终文档中的算法显示正常。涉事代码如下:

\begin{algorithm}[hbt!]
\caption{ Grain 128 AEAD Decrypt with NIST API}\label{alg:cap}
\algrenewcommand\algorithmicrequire{\textbf{Input}}
\algrenewcommand\algorithmicensure{\textbf{Output}}
\begin{algorithmic}[1]
\Require {ad, adlen, m, mlen, k, nonce}
\Ensure {m}
\State {Initialize generator with k and nonce}
\State Construct $c'= (Encode(adlen)||ad||c_0,....c_{clen-65}||0x80)$
\State {Let}
\State\hspace{\algorithmicindent} $M$ = bit length of $Encode(adlen)||ad$
\State\hspace{\algorithmicindent} $mlen = clen - 64$
\State\hspace{\algorithmicindent} $d_i = 0,$ $(0 \leq i \leq M-1)$
\State\hspace{\algorithmicindent} $d_i = 1,$ $(M \leq i \leq M+mlen-1)$
\State {$Decrypt$ using $m'_i = c'_i \oplus z_{i}d_{i}, (0 \leq i \leq M+mlen-1)$}
\State {$Authenticate$ using $z'_i$ and generate $A_{M+mlen+1}$}
\State Set $m = m'_{M+mlen-1}$
\If {$c_{clen-64},......c_{clen-1} == A_{M+mlen+1}$}
\State return 0
\Else
\State return -1
\EndIf
\end{algorithmic}
\end{algorithm}

错误原因

报错的核心是手动使用\hspace{\algorithmicindent}触发解析错误:\algorithmicindent是algpseudocode定义的长度宏,直接放入\hspace参数时,LaTeX会错误地将其解析为命令名的一部分,导致\endcsname相关报错。虽然最终文档能显示,但编译过程的错误会影响后续排查其他问题。

解决方法

改用algpseudocode内置的\Indent和\EndIndent命令实现缩进,替代手动的\hspace操作,同时修正数学环境中==的不规范写法(改为单=或\equiv)。修改后的代码如下:

\begin{algorithm}[hbt!]
\caption{ Grain 128 AEAD Decrypt with NIST API}\label{alg:cap}
\algrenewcommand\algorithmicrequire{\textbf{Input}}
\algrenewcommand\algorithmicensure{\textbf{Output}}
\begin{algorithmic}[1]
\Require {ad, adlen, m, mlen, k, nonce}
\Ensure {m}
\State {Initialize generator with k and nonce}
\State Construct $c'= (Encode(adlen)||ad||c_0,\dots,c_{clen-65}||0x80)$
\State {Let}
\Indent
\State $M$ = bit length of $Encode(adlen)||ad$
\State $mlen = clen - 64$
\State $d_i = 0,$ $(0 \leq i \leq M-1)$
\State $d_i = 1,$ $(M \leq i \leq M+mlen-1)$
\EndIndent
\State {$Decrypt$ using $m'_i = c'_i \oplus z_{i}d_{i}, (0 \leq i \leq M+mlen-1)$}
\State {$Authenticate$ using $z'_i$ and generate $A_{M+mlen+1}$}
\State Set $m = m'_{M+mlen-1}$
\If {$c_{clen-64},\dots,c_{clen-1} = A_{M+mlen+1}$}
\State return 0
\Else
\State return -1
\EndIf
\end{algorithmic}
\end{algorithm}

内容的提问来源于stack exchange,提问作者Najmi Azzahra

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 09:37:44