> 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/more-topics/02-algorithms.md).

# Algorithms

## Introduction

*(To write program code listings, please refer to* [*this help page*](/latex/formatting/11-code-listing.md) *instead.)*

To typeset algorithms or pseudocode in LaTeX you can use one of the following options:

* Choose ONE of the (`algpseudocode` OR `algcompatible` OR `algorithmic`) packages to typeset algorithm bodies, and the `algorithm` package for captioning the algorithm.
* The `algorithm2e` package.

**Note that you should choose only one of the above groups of packages, and use only the commands and syntax provided by the package you choose.** These packages cannot be loaded simultaneously; otherwise you will get lots of errors.

## The algpseudocode and algorithm packages

The `algpseudocode` package provides a `algorithmic` environment and some useful commands. You can [open a full example on Overleaf](https://www.overleaf.com/project/new/template/20763?id=71202437\&templateName=algpseudocode+%2B+algorithm+example\&latexEngine=pdflatex\&texImage=texlive-full%3A2020.1\&mainFile=) , and we'll go into some details in this section.

Here's our first algorithm, using environments and commands from the `algpseudocode` package:

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

[Open this algpseudocode short example in 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)

Here's the result output:

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

*You should not load the `algorithm2e`, `algcompatible`, `algorithmic` packages if you have already loaded `algpseudocode`.*

Note that the command names provided by `algpseudocode` are typically title-cased, e.g. `\State`, `\While`, `\EndWhile`.

If you would like to add line numbers to the algorithm, you can add the first line number to the `algorithmic` environment like this: `\begin{algorithmic}[1]` and get this output:

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

The above algorithm example is not captioned nor numbered. If you need a captioned algorithm, you will also need to load the `algorithm` package, and add

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

around your `algorithmic` environment. You can use `\label{...}` after the `\caption{...}`, so that the algorithm number can be cross-referenced with `\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}
```

[Open this algorithm+algpseudocode short example in 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/li33L8zXafOOXPyKE7V3)

The `algorithm` environment is a [float](/latex/figures-and-tables/02-positioning-images-and-tables.md) like `table` and `figure`, so you can add float placement modifiers `[hbt!]` after `\begin{algorithm}` if necessary. This also means that while a long `algorithmic` environment on its own can break across pages, an `algorithm` environment won't.

The `algorithm` package also provides a `\listofalgorithms` command that works like `\listoffigures`, but for captioned algorithms, like this.

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

[Open a full example on Overleaf](https://www.overleaf.com/project/new/template/20763?id=71202437\&templateName=algpseudocode+%2B+algorithm+example\&latexEngine=pdflatex\&texImage=texlive-full%3A2020.1\&mainFile=)

## The algcompatible/algorithmic and algorithm packages

The `algorithmic` package uses syntax similar to `algpseudocode`; **but** its command names are uppercased, e.g. `\STATE`, `\WHILE`, `\ENDWHILE`.

On the other hand, `algcompatible` will recognise uppercased and title-cased command names, so `\STATE`, `\WHILE`, `\ENDWHILE`, `\State`, `\While`, `\EndWhile` are all recognised. Apart from the command names, `algcompatible` and `algorithmic` commands use the same arguments syntax as `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}
```

[Open this short algcompatible example in 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)

Some older templates or document classes may have loaded `algorithmic`, so you will have to follow the syntax and command names provided. *You should not load the `algorithm2e`, `algpseudocode` packages if the `algorithmic` or `algcompatible` package is already loaded.*

The `algorithm` package can be used with `algorithmic`/`algcompatible` to add numbered captions to the algorithms.

[Open a full example on Overleaf](https://www.overleaf.com/project/new/template/20768?id=71235978\&templateName=algpseudocode+%2B+algorithm+example\&latexEngine=pdflatex\&texImage=texlive-full%3A2020.1\&mainFile=)

## The algorithm2e package

The `algorithm2e` package has quite different syntax structure from the `algpseudocode`, `algcompatible` and `algorithmic` packages, so you will need to be careful about which package you want to use, or which package your template has loaded.

The `algorithm2e` package provides an `algorithm` environment:

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

[Open this short algorithm2e example in 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/ij6RL635EJWow1QMbpVO)

Every line in your source code *must* end with `\;` otherwise your algorithm will continue on the same line of text in the output. Only lines with a macro beginning a block should not end with `\;`.

When using `algorithm2e` you can use `\caption{...}\ref{...}` inside this `algorithm` environment directly, without needing to load any other packages. However if you want to add comments in your algorithm, you'll have to declare the command name to use first:

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

[Open this captioned algorithm2e example in 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/wzy9o9aiOQalbiLavXco)

By default, the `plain` algorithm style is used. But if you prefer lines around the algorithm and caption, you can add the `ruled` package option when loading `algorithm2e`, or write `\RestyleAlgo{ruled}` in your document. Your captioned algorithms will then be typeset like this:

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

The `algorithm2e` package provides many customisation options. For example, if you want to remove the vertical lines that mark the while—end while, if—end if blocks, you can add the `noline` package option when loading `algorithm2e`, or write `\SetNoline`. A `\listofalgorithms` command is also available in `algorithm2e`.

[Open a full example on Overleaf](https://www.overleaf.com/project/new/template/20787?id=71277562\&templateName=algpseudocode+%2B+algorithm+example\&latexEngine=pdflatex\&texImage=texlive-full%3A2020.1\&mainFile=)

## Further Reading

* [`algpseudocode` package documentation](https://texdoc.org/pkg/algorithmicx) (see section 3.1)
* [`algorithmic` and `algorith` package documentation](https://texdoc.org/pkg/algorithms)
* [`algorithm2e` package documentation](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/more-topics/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.
