> 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/overleaf-learn-latex-pt/mais-topicos/02-algorithms.md).

# Algoritmos

## Introdução

*(Para escrever listagens de código de programas, consulte* [*esta página de ajuda*](/latex/overleaf-learn-latex-pt/formatacao/11-code-listing.md) *em vez disso.)*

Para compor algoritmos ou pseudocódigo em LaTeX, pode usar uma das seguintes opções:

* Escolha UM dos (`algpseudocode` OU `algcompatible` OU `algorithmic`) pacotes para compor o corpo do algoritmo, e o `algorithm` pacote para a legenda do algoritmo.
* O `algorithm2e` pacote.

**Note que deve escolher apenas um dos grupos de pacotes acima e usar apenas os comandos e a sintaxe fornecidos pelo pacote que escolher.** Estes pacotes não podem ser carregados em simultâneo; caso contrário, terá muitos erros.

## Os pacotes algpseudocode e algorithm

O `algpseudocode` pacote fornece um `algorithmic` ambiente e alguns comandos úteis. Pode [abrir um exemplo completo no Overleaf](https://www.overleaf.com/project/new/template/20763?id=71202437\&templateName=algpseudocode+%2B+algorithm+example\&latexEngine=pdflatex\&texImage=texlive-full%3A2020.1\&mainFile=) , e vamos abordar alguns detalhes nesta seção.

Aqui está o nosso primeiro algoritmo, usando ambientes e comandos do `algpseudocode` pacote:

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

[Abra este breve exemplo algpseudocode no 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)

Aqui está a saída resultante:

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

*Não deve carregar os `algorithm2e`, `algcompatible`, `algorithmic` pacotes se já tiver carregado `algpseudocode`.*

Note que os nomes dos comandos fornecidos por `algpseudocode` costumam estar em maiúscula inicial, por ex. `\State`, `\While`, `\EndWhile`.

Se quiser adicionar números de linha ao algoritmo, pode adicionar o primeiro número de linha ao `algorithmic` ambiente assim: `\begin{algorithmic}[1]` e obter esta saída:

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

O exemplo de algoritmo acima não tem legenda nem numeração. Se precisar de um algoritmo com legenda, também terá de carregar o `algorithm` pacote e adicionar

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

em torno do seu `algorithmic` ambiente. Pode usar `\label{...}` após o `\caption{...}`, para que o número do algoritmo possa ser referenciado cruzadamente com `\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{Este é um comentário}
\ElsIf{$N$ is odd}
    \State $y \gets y \times X$
    \State $N \gets N - 1$
\EndIf
\EndWhile
\end{algorithmic}
\end{algorithm}

\end{document}
```

[Abra este breve exemplo algorithm+algpseudocode no 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/3ac3b15bea40a4e437c823baa084ab801a5c0102)

O `algorithm` ambiente é um [float](/latex/overleaf-learn-latex-pt/figuras-e-tabelas/02-positioning-images-and-tables.md) como `table` e `figure`, por isso pode adicionar modificadores de posicionamento de flutuantes `[hbt!]` depois de `\begin{algorithm}` se necessário. Isto também significa que, embora um longo `algorithmic` ambiente por si só possa dividir-se entre páginas, um `algorithm` ambiente não.

O `algorithm` pacote também fornece um `\listofalgorithms` comando que funciona como `\listoffigures`, mas para algoritmos com legenda, como este.

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

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

## Os pacotes algcompatible/algorithmic e algorithm

O `algorithmic` pacote usa sintaxe semelhante à de `algpseudocode`; **mas** os nomes dos seus comandos estão em maiúsculas, por ex. `\STATE`, `\WHILE`, `\ENDWHILE`.

Por outro lado, `algcompatible` reconhecerá nomes de comandos em maiúsculas e com maiúscula inicial, por isso `\STATE`, `\WHILE`, `\ENDWHILE`, `\State`, `\While`, `\EndWhile` todos são reconhecidos. Além dos nomes dos comandos, `algcompatible` e `algorithmic` os comandos usam a mesma sintaxe de argumentos que `algpseudocode`.

```latex
\documentclass{article}
\usepackage{algcompatible}
% OU \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}
```

[Abra este breve exemplo algcompatible no 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)

Alguns modelos ou classes de documento mais antigos podem ter carregado `algorithmic`, por isso terá de seguir a sintaxe e os nomes dos comandos fornecidos. *Não deve carregar os `algorithm2e`, `algpseudocode` pacotes se o `algorithmic` ou `algcompatible` pacote já estiver carregado.*

O `algorithm` pacote pode ser usado com `algorithmic`/`algcompatible` para adicionar legendas numeradas aos algoritmos.

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

## O pacote algorithm2e

O `algorithm2e` pacote tem uma estrutura de sintaxe bastante diferente da dos `algpseudocode`, `algcompatible` e `algorithmic` pacotes, por isso terá de ter cuidado com o pacote que quer usar, ou com o pacote que o seu modelo carregou.

O `algorithm2e` pacote fornece um `algorithm` ambiente:

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

[Abra este breve exemplo algorithm2e no 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/1c848eed21b959ad2b22fa775f6759ff6b7c2654)

Cada linha no seu código-fonte *deve* deve terminar com `\;` caso contrário, o seu algoritmo continuará na mesma linha de texto na saída. Apenas as linhas com uma macro que inicia um bloco não devem terminar com `\;`.

Ao usar `algorithm2e` pode usar `\caption{...}\ref{...}` diretamente dentro deste `algorithm` ambiente, sem precisar de carregar quaisquer outros pacotes. No entanto, se quiser adicionar comentários ao seu algoritmo, terá de declarar primeiro o nome do comando a usar:

```latex
%% Isto declara um comando \Comment
%% O argumento será rodeado por /* ... */
\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]{Este é um comentário}
  }{\If{$N$ is odd}{
      $y \gets y \times X$\;
      $N \gets N - 1$\;
    }
  }
}
\end{algorithm}
```

[Abra este exemplo com legenda de algorithm2e no 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/f02f5e504f81bf41bf2b5f15bba6cb5f17b373cc)

Por predefinição, o `plain` estilo algorithm é usado. Mas se preferir linhas à volta do algoritmo e da legenda, pode adicionar a opção `ruled` ao carregar `algorithm2e`, ou escrever `\RestyleAlgo{ruled}` no seu documento. Os seus algoritmos com legenda serão então compostos assim:

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

O `algorithm2e` pacote oferece muitas opções de personalização. Por exemplo, se quiser remover as linhas verticais que marcam os blocos while—end while, if—end if, pode adicionar o `noline` ao carregar `algorithm2e`, ou escrever `\SetNoline`. Um `\listofalgorithms` comando também está disponível em `algorithm2e`.

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

## Leitura adicional

* [`algpseudocode` documentação do pacote](https://texdoc.org/pkg/algorithmicx) (veja a secção 3.1)
* [`algorithmic` e `algoritm` documentação do pacote](https://texdoc.org/pkg/algorithms)
* [`algorithm2e` documentação do pacote](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/overleaf-learn-latex-pt/mais-topicos/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.
