> For the complete documentation index, see [llms.txt](https://ayakaleaf-pro.ayaka.space/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://ayakaleaf-pro.ayaka.space/latex/zh-cn/geng-duo-zhu-ti/02-algorithms.md).

# 算法

## 引言

*(要编写程序代码清单，请参见* [*此帮助页面*](/latex/zh-cn/ge-shi-hua/11-code-listing.md) *而不是。）*

在 LaTeX 中排版算法或伪代码时，你可以使用以下选项之一：

* 请选择以下其中一个（`algpseudocode` 或 `algcompatible` 或 `algorithmic`) 宏包来排版算法主体，并使用 `algorithm` 宏包为算法添加标题。
* 该 `algorithm2e` 宏包。

**请注意，你应当只选择上述其中一组宏包，并且只使用你所选宏包提供的命令和语法。** 这些宏包不能同时加载；否则你会得到大量错误。

## algpseudocode 和 algorithm 宏包

该 `algpseudocode` 宏包提供了一个 `algorithmic` 环境和一些有用的命令。你可以 [在 Overleaf 上打开完整示例](https://www.overleaf.com/project/new/template/20763?id=71202437\&templateName=algpseudocode+%2B+algorithm+example\&latexEngine=pdflatex\&texImage=texlive-full%3A2020.1\&mainFile=) ，本节中我们会介绍一些细节。

这是我们的第一个算法，使用来自以下宏包的环境和命令： `algpseudocode` 宏包的示例代码：

```latex
\documentclass{article}
\usepackage{algpseudocode}
\begin{document}
\begin{algorithmic}
\State $i \gets 10$
\If{$i\geq 5$}
    \State $i \gets i-1$
\Else
    \If{$i\leq 3$}
        \State $i \gets i+2$
    \EndIf
\EndIf
\end{algorithmic}

\end{document}
```

[在 Overleaf 中打开这个 algpseudocode 简短示例](https://www.overleaf.com/docs?engine=\&snip_name=algpseudocode+short+example\&snip=%5Cdocumentclass%7Barticle%7D%0A%5Cusepackage%7Balgpseudocode%7D%0A%5Cbegin%7Bdocument%7D%0A%5Cbegin%7Balgorithmic%7D%0A%5CState+%24i+%5Cgets+10%24%0A%5CIf%7B%24i%5Cgeq+5%24%7D+%0A++++%5CState+%24i+%5Cgets+i-1%24%0A%5CElse%0A++++%5CIf%7B%24i%5Cleq+3%24%7D%0A++++++++%5CState+%24i+%5Cgets+i%2B2%24%0A++++%5CEndIf%0A%5CEndIf+%0A%5Cend%7Balgorithmic%7D%0A%0A%5Cend%7Bdocument%7D)

结果如下：

![Algpseudocode-0.png](/files/dee89466df064feff8ba9bed28e862c70930f57a)

*你不应加载 `algorithm2e`, `algcompatible`, `algorithmic` 这些宏包，如果你已经加载了 `algpseudocode`.*

请注意，由该宏包提供的命令名称 `algpseudocode` 通常采用首字母大写形式，例如 `\State`, `\While`, `\EndWhile`.

如果你想为算法添加行号，可以将第一行行号加到 `algorithmic` 环境中，如下所示： `\begin{algorithmic}[1]` 并得到如下输出：

![Algpseudocode-00.png](/files/684b7f1f3b01950554c0644feb82fd8dbc665872)

上面的算法示例既没有标题也没有编号。如果你需要带标题的算法，还需要加载 `algorithm` 宏包，并添加

```latex
\begin{algorithm}
\caption{...}
...
\end{algorithm}
```

围绕你的 `algorithmic` 环境。你可以使用 `\label{...}` 放在上一行的 `\caption{...}`，这样算法编号就可以与……交叉引用 `\ref{...}`.

```latex
\documentclass{article}
\usepackage{algorithm}
\usepackage{algpseudocode}
\begin{document}
\begin{algorithm}
\caption{An algorithm with caption}\label{alg:cap}
\begin{algorithmic}
\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}

\end{document}
```

[在 Overleaf 中打开这个 algorithm+algpseudocode 简短示例](https://www.overleaf.com/docs?engine=\&snip_name=Captioned+algorithm%2Balgpseudocode+example\&snip=%5Cdocumentclass%7Barticle%7D%0A%5Cusepackage%7Balgorithm%7D%0A%5Cusepackage%7Balgpseudocode%7D%0A%5Cbegin%7Bdocument%7D%0A%5Cbegin%7Balgorithm%7D%0A%5Ccaption%7BAn+algorithm+with+caption%7D%5Clabel%7Balg%3Acap%7D%0A%5Cbegin%7Balgorithmic%7D%0A%5CRequire+%24n+%5Cgeq+0%24%0A%5CEnsure+%24y+%3D+x%5En%24%0A%5CState+%24y+%5Cgets+1%24%0A%5CState+%24X+%5Cgets+x%24%0A%5CState+%24N+%5Cgets+n%24%0A%5CWhile%7B%24N+%5Cneq+0%24%7D%0A%5CIf%7B%24N%24+is+even%7D%0A++++%5CState+%24X+%5Cgets+X+%5Ctimes+X%24%0A++++%5CState+%24N+%5Cgets+%5Cfrac%7BN%7D%7B2%7D%24++%5CComment%7BThis+is+a+comment%7D%0A%5CElsIf%7B%24N%24+is+odd%7D%0A++++%5CState+%24y+%5Cgets+y+%5Ctimes+X%24%0A++++%5CState+%24N+%5Cgets+N+-+1%24%0A%5CEndIf%0A%5CEndWhile%0A%5Cend%7Balgorithmic%7D%0A%5Cend%7Balgorithm%7D%0A%0A%5Cend%7Bdocument%7D)

![Algpseudocode-1.png](/files/87a8422cff534de7251614db6327b215abe6857f)

该 `algorithm` 环境是一个 [float](/latex/zh-cn/tu-xing-he-biao-ge/02-positioning-images-and-tables.md) 类似于 `table` 和 `figure`，因此你可以添加浮动体位置修饰符 `[hbt!]` 在 `\begin{algorithm}` （如有必要）。这也意味着，虽然一个较长的 `algorithmic` 环境本身可以跨页断开，但一个 `algorithm` 环境则不行。

该 `algorithm` 宏包还提供了一个 `\listofalgorithms` 命令，其作用类似于 `\listoffigures`，但用于带标题的算法，如下所示。

![Algpseudocode-2.png](/files/78a5d3173711ec2681ecb1582a2158d81f341f0e)

[在 Overleaf 上打开完整示例](https://www.overleaf.com/project/new/template/20763?id=71202437\&templateName=algpseudocode+%2B+algorithm+example\&latexEngine=pdflatex\&texImage=texlive-full%3A2020.1\&mainFile=)

## algcompatible/algorithmic 和 algorithm 宏包

该 `algorithmic` 宏包使用类似于……的语法 `algpseudocode`; **但是** 其命令名称采用全大写形式，例如 `\STATE`, `\WHILE`, `\ENDWHILE`.

另一方面， `algcompatible` 会识别全大写和首字母大写的命令名称，因此 `\STATE`, `\WHILE`, `\ENDWHILE`, `\State`, `\While`, `\EndWhile` 都会被识别。除了命令名称之外， `algcompatible` 和 `algorithmic` 命令使用与……相同的参数语法 `algpseudocode`.

```latex
\documentclass{article}
\usepackage{algcompatible}
% OR \usepackage{algorithmic}
\begin{document}
\begin{algorithmic}
\STATE $i\gets 10$
\IF {$i\geq 5$}
  \STATE $i\gets i-1$
\ELSE
  \IF {$i\leq 3$}
    \STATE $i\gets i+2$
  \ENDIF
\ENDIF
\end{algorithmic}

\end{document}
```

[在 Overleaf 中打开这个 algcompatible 简短示例](https://www.overleaf.com/docs?engine=\&snip_name=algcompatible\&snip=%5Cdocumentclass%7Barticle%7D%0A%5Cusepackage%7Balgcompatible%7D%0A%25+OR+%5Cusepackage%7Balgorithmic%7D%0A%5Cbegin%7Bdocument%7D%0A%5Cbegin%7Balgorithmic%7D%0A%5CSTATE+%24i%5Cgets+10%24%0A%5CIF+%7B%24i%5Cgeq+5%24%7D+%0A++%5CSTATE+%24i%5Cgets+i-1%24%0A%5CELSE%0A++%5CIF+%7B%24i%5Cleq+3%24%7D%0A++++%5CSTATE+%24i%5Cgets+i%2B2%24%0A++%5CENDIF%0A%5CENDIF+%0A%5Cend%7Balgorithmic%7D%0A%0A%5Cend%7Bdocument%7D)

某些较旧的模板或文档类可能已经加载了 `algorithmic`，因此你必须遵循所提供的语法和命令名称。 *你不应加载 `algorithm2e`, `algpseudocode` 这些宏包，如果 `algorithmic` 或 `algcompatible` 该宏包已经加载。*

该 `algorithm` 宏包可以与……一起使用 `algorithmic`/`algcompatible` 以便为算法添加带编号的标题。

[在 Overleaf 上打开完整示例](https://www.overleaf.com/project/new/template/20768?id=71235978\&templateName=algpseudocode+%2B+algorithm+example\&latexEngine=pdflatex\&texImage=texlive-full%3A2020.1\&mainFile=)

## algorithm2e 宏包

该 `algorithm2e` 宏包的语法结构与……有很大不同 `algpseudocode`, `algcompatible` 和 `algorithmic` 宏包，因此你需要注意自己想使用哪个宏包，或者你的模板已经加载了哪个宏包。

该 `algorithm2e` 宏包提供了一个 `algorithm` 环境：

```latex
\documentclass{article}
\usepackage{algorithm2e}
\begin{document}
\begin{algorithm}
$i\gets 10$\;
\eIf{$i\geq 5$}
{
    $i\gets i-1$\;
}{
    \If{$i\leq 3$}
    {
        $i\gets i+2$\;
    }
}
\end{algorithm}

\end{document}
```

[在 Overleaf 中打开这个 algorithm2e 简短示例](https://www.overleaf.com/docs?engine=\&snip_name=algorithm2e+example\&snip=%5Cdocumentclass%7Barticle%7D%0A%5Cusepackage%7Balgorithm2e%7D%0A%5Cbegin%7Bdocument%7D%0A%5Cbegin%7Balgorithm%7D%0A%24i%5Cgets+10%24%5C%3B%0A%5CeIf%7B%24i%5Cgeq+5%24%7D%0A%7B%0A++++%24i%5Cgets+i-1%24%5C%3B%0A%7D%7B%0A++++%5CIf%7B%24i%5Cleq+3%24%7D%0A++++%7B%0A++++++++%24i%5Cgets+i%2B2%24%5C%3B%0A++++%7D%0A%7D%0A%5Cend%7Balgorithm%7D%0A%0A%5Cend%7Bdocument%7D)

![Algorithm2e-0.png](/files/e3f38975934bd40fcd7e85d6cb87acee8d4a7a75)

你源代码中的每一行 *必须* 都应以……结尾 `\;` 否则你的算法会在输出中继续占用同一行文本。只有以宏开始一个代码块的行才不应以……结尾 `\;`.

使用时 `algorithm2e` 你可以使用 `\caption{...}\ref{...}` 在这个 `algorithm` 环境中直接使用，无需加载任何其他宏包。不过，如果你想在算法中添加注释，就必须先声明要使用的命令名称：

```latex
%% This declares a command \Comment
%% The argument will be surrounded by /* ... */
\SetKwComment{Comment}{/* }{ */}

\begin{algorithm}
\caption{An algorithm with caption}\label{alg:two}
\KwData{$n \geq 0$}
\KwResult{$y = x^n$}
$y \gets 1$\;
$X \gets x$\;
$N \gets n$\;
\While{$N \neq 0$}{
  \eIf{$N$ is even}{
    $X \gets X \times X$\;
    $N \gets \frac{N}{2}$ \Comment*[r]{This is a comment}
  }{\If{$N$ is odd}{
      $y \gets y \times X$\;
      $N \gets N - 1$\;
    }
  }
}
\end{algorithm}
```

[在 Overleaf 中打开这个带标题的 algorithm2e 示例](https://www.overleaf.com/docs?engine=\&snip_name=Captioned+algorithm2e+example\&snip=%5Cdocumentclass%7Barticle%7D%0A%5Cusepackage%7Balgorithm2e%7D%0A%5Cbegin%7Bdocument%7D%0A%25%25+This+declares+a+command+%5CComment%0A%25%25+The+argument+will+be+surrounded+by+%2F%2A+...+%2A%2F%0A%5CSetKwComment%7BComment%7D%7B%2F%2A+%7D%7B+%2A%2F%7D%0A%0A%5Cbegin%7Balgorithm%7D%0A%5Ccaption%7BAn+algorithm+with+caption%7D%5Clabel%7Balg%3Atwo%7D%0A%5CKwData%7B%24n+%5Cgeq+0%24%7D%0A%5CKwResult%7B%24y+%3D+x%5En%24%7D%0A%24y+%5Cgets+1%24%5C%3B%0A%24X+%5Cgets+x%24%5C%3B%0A%24N+%5Cgets+n%24%5C%3B%0A%5CWhile%7B%24N+%5Cneq+0%24%7D%7B%0A++%5CeIf%7B%24N%24+is+even%7D%7B%0A++++%24X+%5Cgets+X+%5Ctimes+X%24%5C%3B%0A++++%24N+%5Cgets+%5Cfrac%7BN%7D%7B2%7D%24+%5CComment%2A%5Br%5D%7BThis+is+a+comment%7D%0A++%7D%7B%5CIf%7B%24N%24+is+odd%7D%7B%0A++++++%24y+%5Cgets+y+%5Ctimes+X%24%5C%3B%0A++++++%24N+%5Cgets+N+-+1%24%5C%3B%0A++++%7D%0A++%7D%0A%7D%0A%5Cend%7Balgorithm%7D%0A%0A%5Cend%7Bdocument%7D)

![Algorithm2e-1.png](/files/67e12c0032f3638e87bc76029c90313c5e052e82)

默认情况下， `plain` 会使用 algorithm 样式。但如果你希望算法和标题周围有边线，可以添加 `ruled` 宏包选项，在加载 `algorithm2e`，或者在文档中写入 `\RestyleAlgo{ruled}` 。这样，你的带标题算法就会排版成如下样式：

![Algorithm2e-11.png](/files/9b7410f91953ddec6d8f571d352da855162cd522)

该 `algorithm2e` 宏包提供了许多自定义选项。例如，如果你想移除标记 while—end while、if—end if 代码块的竖线，可以添加 `noline` 宏包选项，在加载 `algorithm2e`，或者在文档中写入 `\SetNoline`。一个 `\listofalgorithms` 命令在……中也可用 `algorithm2e`.

[在 Overleaf 上打开完整示例](https://www.overleaf.com/project/new/template/20787?id=71277562\&templateName=algpseudocode+%2B+algorithm+example\&latexEngine=pdflatex\&texImage=texlive-full%3A2020.1\&mainFile=)

## 延伸阅读

* [`algpseudocode` 包文档](https://texdoc.org/pkg/algorithmicx) （见第 3.1 节）
* [`algorithmic` 和 `算法` 包文档](https://texdoc.org/pkg/algorithms)
* [`algorithm2e` 包文档](https://texdoc.org/pkg/algorithm2e)


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://ayakaleaf-pro.ayaka.space/latex/zh-cn/geng-duo-zhu-ti/02-algorithms.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
