[Tex/LaTex] Line number error using “Require” and “Ensure” in package{algorithmicx}

algorithmicxalgorithmsline-numbering

I’m using the packages algorithmicx and algpseudocode to write algorithms in my paper. It’s more convenient and beautiful to specify comments than with the algorithmic.

But I encounter an error while using “Require and Ensure.” The line's number is always wrong.

MWE

\documentclass{article}
\usepackage{amsmath}
\usepackage{algorithm}
\usepackage{algpseudocode}
\begin{document}

\begin{algorithm}[ht]
\caption{My first algorithm}
\label{alg:algorithm1}

\begin{algorithmic}[1]
\Require~~\\
 If there are multiple lines here, line's number will be wrong.\\
 This error doesn't happen in package\{algorithmic\}
\Ensure~~\\
 If I write $\setminus\setminus$ here, line's number will be wrong too.
\Statex
\If{$i = 1 \to n$} \Comment{This line's number should be 1}
  \State ${\textit{HU}}_{i} \gets {\textit{NGU}}_{i} + {HU}_{i}$ \Comment{Comment}
\EndIf

\end{algorithmic}
\end{algorithm}
\end{document}

Output

Pdf image is here

Question

I need to write two lines in item “Require.” How can I tackle this line number problem?

Best Answer

algorithmicx maintains the algorithmic environment as a list. You could therefore use the \Statex command to insert an unnumbered item, similar to inserting an empty line:

enter image description here

\documentclass{article}
\usepackage{algorithm,algpseudocode}% http://ctan.org/pkg/{algorithms,algorithmicx}
\begin{document}

\begin{algorithm}[ht]
  \caption{My first algorithm}\label{alg:algorithm1}
  \begin{algorithmic}[1]
    \Require
      \Statex If there are multiple lines here, line's number will be wrong.
      \Statex This error doesn't happen in package \verb|algorithmic|.
    \Ensure
      \Statex If I write \verb|\\| here, line's number will be wrong too.
    \Statex
    \If{$i = 1 \to n$} \Comment{This line's number should be 1}
      \State ${\textit{HU}}_{i} \gets {\textit{NGU}}_{i} + {HU}_{i}$ \Comment{Comment}
    \EndIf
  \end{algorithmic}
\end{algorithm}
\end{document}