> 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/ja/sononotopikku/02-algorithms.md).

# アルゴリズム

## はじめに

*（プログラムコード一覧を書くには、* [*このヘルプページ*](/latex/ja/shu-shi-she-ding/11-code-listing.md) *代わりにご参照ください。）*

LaTeX でアルゴリズムや擬似コードを組版するには、以下のいずれかの方法を使えます：

* 次のうち1つの（`algpseudocode` または `algcompatible` または `algorithmic`) パッケージのどれかを使ってアルゴリズム本体を組版し、 `algorithm` パッケージを使ってアルゴリズムにキャプションを付けます。
* この `algorithm2e` xr

**上記のパッケージ群は1つだけ選び、その選んだパッケージで提供されるコマンドと構文だけを使うようにしてください。** これらのパッケージは同時には読み込めません。そうしないと大量のエラーが発生します。

## 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}
```

[この algpseudocode の短い例を Overleaf で開く](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/0b2e8ebe54e267778f21ff226ac3effe71d03aeb)

*あなたが `algorithm2e`, `algcompatible`, `algorithmic` パッケージをすでに読み込んでいる場合は、 `algpseudocode`.*

なお、 `algpseudocode` で提供されるコマンド名は通常タイトルケースで、たとえば `\State`, `\While`, `\EndWhile`.

アルゴリズムに行番号を追加したい場合は、最初の行番号を `algorithmic` 環境に次のように追加できます： `\begin{algorithmic}[1]` 、すると次の出力が得られます：

![Algpseudocode-00.png](/files/0077d398ecc1ea83d7530e1ab08b2b4a69e39b57)

上のアルゴリズムの例にはキャプションも番号も付いていません。キャプション付きアルゴリズムが必要なら、 `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}
```

[この algorithm+algpseudocode の短い例を Overleaf で開く](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/775a621752c9c1eaff60c8783ee1d41f74c429fc)

この `algorithm` 環境は [float](/latex/ja/to/02-positioning-images-and-tables.md) のような `table` や `figure`です。そのため、フロート配置修飾子を `[hbt!]` 後に `\begin{algorithm}` 必要に応じて追加できます。これは、長い `algorithmic` 環境単体はページをまたいで分割できますが、 `algorithm` 環境はできないことも意味します。

この `algorithm` パッケージには `\listofalgorithms` コマンドもあり、 `\listoffigures`のように、

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

[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`.

一方で、 `algcompatible` は大文字表記とタイトルケース表記のコマンド名を認識するので、 `そのコマンド名は大文字表記で、たとえば`, `\STATE`, `\WHILE`, `\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}
```

[この algcompatible の短い例を Overleaf で開く](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}
```

[この algorithm2e の短い例を Overleaf で開く](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/85fdd30941d693a425b9cd7629ddaef7da614a1c)

ソースコードの各行は *必要があります* で終わらせてください。 `\;` そうしないと、アルゴリズムが出力中の同じ行に続いてしまいます。ブロックを開始するマクロで始まる行だけは `\;`.

を使用する場合、 `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}
```

[キャプション付きのこの algorithm2e の例を Overleaf で開く](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/2fb747107d67d86fae4be2de0e8d92b9b5412b61)

デフォルトでは、 `plain` アルゴリズムスタイルが使用されます。ただし、アルゴリズムとキャプションの周りに線を表示したい場合は、 `ruled` を読み込むときのパッケージオプションとして追加するか、 `algorithm2e`または `\RestyleAlgo{ruled}` を文書内に書いてください。すると、キャプション付きアルゴリズムは次のように組版されます：

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

この `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/ja/sononotopikku/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.
