> For the complete documentation index, see [llms.txt](https://overleaf-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://overleaf-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{带标题的算法}\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{这是一个注释}
\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-biao-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}
% 或 \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
%% 这声明了一个命令 \Comment
%% 参数将被 /* ... */ 包围
\SetKwComment{Comment}{/* }{ */}

\begin{algorithm}
\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]{这是一个注释}
  }{\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://overleaf-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.
