> 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/es/mas-temas/02-algorithms.md).

# Algoritmos

## Introducción

*(Para escribir listados de código de programa, consulte* [*esta página de ayuda*](/latex/es/formato/11-code-listing.md) *en su lugar.)*

Para componer algoritmos o pseudocódigo en LaTeX puede usar una de las siguientes opciones:

* Elija UNO de los (`algpseudocode` O `algcompatible` O `algorithmic`) paquetes para componer el cuerpo de los algoritmos, y el `algorithm` paquete para poner el título al algoritmo.
* El `algorithm2e` paquete.

**Tenga en cuenta que debe elegir solo uno de los grupos de paquetes anteriores y usar solo los comandos y la sintaxis que proporciona el paquete que elija.** Estos paquetes no pueden cargarse simultáneamente; de lo contrario, obtendrá muchos errores.

## Los paquetes algpseudocode y algorithm

El `algpseudocode` paquete proporciona un `algorithmic` entorno y algunos comandos útiles. Puede [abrir un ejemplo completo en Overleaf](https://www.overleaf.com/project/new/template/20763?id=71202437\&templateName=algpseudocode+%2B+algorithm+example\&latexEngine=pdflatex\&texImage=texlive-full%3A2020.1\&mainFile=) , y veremos algunos detalles en esta sección.

Aquí está nuestro primer algoritmo, usando entornos y comandos del `algpseudocode` paquete:

```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 ejemplo de algpseudocode en 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)

Aquí está el resultado:

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

*No debe cargar los `algorithm2e`, `algcompatible`, `algorithmic` paquetes si ya ha cargado `algpseudocode`.*

Tenga en cuenta que los nombres de comandos proporcionados por `algpseudocode` suelen escribirse en mayúscula inicial, por ejemplo `\State`, `\While`, `\EndWhile`.

Si desea añadir números de línea al algoritmo, puede añadir el primer número de línea al `algorithmic` entorno así: `\begin{algorithmic}[1]` y obtendrá este resultado:

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

El ejemplo de algoritmo anterior no tiene título ni número. Si necesita un algoritmo con título, también deberá cargar el `algorithm` paquete, y añadir

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

alrededor de su `algorithmic` entorno. Puede usar `\label{...}` después del `\caption{...}`, para que el número del algoritmo pueda cruzarse con `\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 es un comentario}
\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 ejemplo de algorithm+algpseudocode en 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/3e8269475532f868bb6298606258e1e072bfdd63)

El `algorithm` entorno es un [float](/latex/es/figuras-y-tablas/02-positioning-images-and-tables.md) como `table` y `entorno`, así que puede añadir modificadores de colocación de flotantes `[hbt!]` después de `\begin{algorithm}` si es necesario. Esto también significa que, aunque un largo `algorithmic` entorno por sí solo puede partirse entre páginas, un `algorithm` entorno no.

El `algorithm` paquete también proporciona un `\listofalgorithms` comando que funciona como `\listoffigures`, pero para algoritmos con título, como este.

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

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

## Los paquetes algcompatible/algorithmic y algorithm

El `algorithmic` paquete usa una sintaxis similar a `algpseudocode`; **pero** sus nombres de comando están en mayúsculas, por ejemplo `\STATE`, `\WHILE`, `\ENDWHILE`.

Por otro lado, `algcompatible` reconocerá nombres de comandos en mayúsculas y en mayúscula inicial, así que `\STATE`, `\WHILE`, `\ENDWHILE`, `\State`, `\While`, `\EndWhile` todos son reconocidos. Aparte de los nombres de comando, `algcompatible` y `algorithmic` los comandos usan la misma sintaxis de argumentos que `algpseudocode`.

```latex
\documentclass{article}
\usepackage{algcompatible}
% O \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 ejemplo de algcompatible en 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)

Es posible que algunas plantillas o clases de documento antiguas hayan cargado `algorithmic`, así que tendrá que seguir la sintaxis y los nombres de comando proporcionados. *No debe cargar los `algorithm2e`, `algpseudocode` paquetes si el `algorithmic` o `algcompatible` paquete ya está cargado.*

El `algorithm` paquete puede usarse con `algorithmic`/`algcompatible` para añadir títulos numerados a los algoritmos.

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

## El paquete algorithm2e

El `algorithm2e` paquete tiene una estructura de sintaxis bastante diferente de los `algpseudocode`, `algcompatible` y `algorithmic` paquetes, así que deberá tener cuidado con el paquete que desea usar, o con el paquete que haya cargado su plantilla.

El `algorithm2e` paquete proporciona un `algorithm` entorno:

```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 ejemplo de algorithm2e en 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/bb5e652e2d3523603dd76549ccf5b92bd4135f39)

Cada línea en su código fuente *debe* debe terminar con `\;` de lo contrario, su algoritmo continuará en la misma línea de texto en la salida. Solo las líneas con una macro que comience un bloque no deben terminar con `\;`.

Al usar `algorithm2e` puede usar `\caption{...}\ref{...}` directamente dentro de este `algorithm` entorno, sin necesidad de cargar ningún otro paquete. Sin embargo, si desea añadir comentarios en su algoritmo, primero tendrá que declarar el nombre del comando que se usará:

```latex
%% Esto declara un comando \Comment
%% El argumento estará 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 es un comentario}
  }{\If{$N$ is odd}{
      $y \gets y \times X$\;
      $N \gets N - 1$\;
    }
  }
}
\end{algorithm}
```

[Abra este ejemplo con título de algorithm2e en 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/d27a482161d428842acf841feb0761eb9b9f601e)

De forma predeterminada, se usa el `plain` estilo algorithm. Pero si prefiere líneas alrededor del algoritmo y del título, puede añadir la `ruled` opción de paquete al cargar `algorithm2e`, o escribir `\RestyleAlgo{ruled}` en su documento. Entonces sus algoritmos con título se compondrán así:

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

El `algorithm2e` paquete ofrece muchas opciones de personalización. Por ejemplo, si desea eliminar las líneas verticales que marcan los bloques while—end while, if—end if, puede añadir la `noline` opción de paquete al cargar `algorithm2e`, o escribir `\SetNoline`. Un `\listofalgorithms` comando también está disponible en `algorithm2e`.

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

## Lectura adicional

* [`algpseudocode` documentación del paquete](https://texdoc.org/pkg/algorithmicx) (véase la sección 3.1)
* [`algorithmic` y `algoritmo` documentación del paquete](https://texdoc.org/pkg/algorithms)
* [`algorithm2e` documentación del paquete](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/es/mas-temas/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.
