> 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-tw/geng-duo-zhu-ti/02-algorithms.md).

# 演算法

## 簡介

*（若要撰寫程式碼清單，請參閱* [*這個說明頁面*](/latex/zh-tw/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/9ac26147cc6aad57244b6960350c7fcac1157226)

*你不應載入 `algorithm2e`, `algcompatible`, `algorithmic` 這些套件，如果你已經載入了 `algpseudocode`.*

請注意，由 `algpseudocode` 所提供的命令名稱通常採用標題式大小寫，例如 `\State`, `\While`, `\EndWhile`.

如果你想為演算法加上行號，可以將第一個行號加到 `algorithmic` 環境中，如下所示： `\begin{algorithmic}[1]` 即可得到以下輸出：

![Algpseudocode-00.png](/files/1cd99b73053902c136a691c1cc2f2c717c937717)

上述演算法範例既沒有標題也沒有編號。若你需要帶標題的演算法，還需要載入 `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$ 為偶數}
    \State $X \gets X \times X$
    \State $N \gets \frac{N}{2}$  \Comment{這是一則註解}
\ElsIf{$N$ 為奇數}
    \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/8d19255ef828e1dac602440c25822f18606b8c37)

該 `algorithm` 環境是一個 [float](/latex/zh-tw/tu-biao-yu-biao-ge/02-positioning-images-and-tables.md) 類似於 `table` 和 `figure`，因此你可以加入浮動位置修飾符 `[hbt!]` 在 `\begin{algorithm}` （如有需要）。這也表示，雖然一個較長的 `algorithmic` 環境本身可以跨頁，但 `algorithm` 環境則不行。

該 `algorithm` 套件也提供一個 `\listofalgorithms` 命令，其作用類似於 `\listoffigures`，但適用於帶標題的演算法，如下所示。

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

[在 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/0e5083b65c7b48814b0f63d561a75f36048e6a40)

你原始碼中的每一行 *必須* 都應以 `\;` 結尾，否則你的演算法在輸出中會繼續出現在同一行文字上。只有以巨集開始一個區塊的行不應以 `\;`.

使用時， `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$ 為偶數}{
    $X \gets X \times X$\;
    $N \gets \frac{N}{2}$ \Comment*[r]{這是一則註解}
  }{\If{$N$ 為奇數}{
      $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/0f625a9812b704bbe7b996331c3dc8fd2806b410)

預設情況下， `plain` 會使用 algorithm 樣式。但如果你偏好在演算法與標題周圍加上線條，可以加入 `ruled` 套件選項，在載入 `algorithm2e`時，或直接寫入 `\RestyleAlgo{ruled}` 到你的文件中。如此一來，你的帶標題演算法將會排版如下：

![Algorithm2e-11.png](/files/59c05c33b0b9f74bb496a2df19c037f263a5ec25)

該 `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` 和 `algorith` 套件說明文件](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-tw/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.
