LaTeX 伪代码

伪代码需要使用 algorithmalgpseudocode 包。

% Preamble
\usepackage{algorithm}
\usepackage{algpseudocode}
  • algorithm:提供一个浮动体环境来包含算法(类似于 table 环境),使得算法可以自动编号并出现在文档中合适的位置。
  • algpseudocode:提供伪代码的语法和命令
% Body
\begin{algorithm}[htbp]
\caption{An algorithm with caption}  % 设置标题
\label{alg:cap}                      % 设置引用标签
\begin{algorithmic}                  % 可以使用 [1] 启用行号

\Require $n \geq 0$
\Ensure $y = x^n$
\State $y \gets 1$
\State $X \gets x$
\State $N \gets n$
\While{$N \neq 0$}
    \If{$N$ is even}
        \State $X \gets X \times X$
        \State $N \gets \frac{N}{2}$  \Comment{This is a comment}
    \ElsIf{$N$ is odd}
        \State $y \gets y \times X$
        \State $N \gets N - 1$
    \EndIf
\EndWhile

\end{algorithmic}
\end{algorithm}

image

参考:Algorithms | Overleaf

修改注释符

\Comment 命令默认会创建一个右三角 符号表示注释。如果你希望使用其他符号,可以在引入 algpseudocode 包后使用下面这条命令:

\renewcommand{\algorithmiccomment}[1]{\hfill // #1} % 将注释符改为 //

杂项

algorithmic 包:提供基本的算法排版命令,但不如 algpseudocode 美观。

posted @ 2024-05-09 01:37  Undefined443  阅读(1407)  评论(0)    收藏  举报