
使用它algorithmicx
可以輕鬆開啟或關閉行編號或對每第 n 行進行編號。採取這個 MWE(取自文檔)
\documentclass{article}
\usepackage{algpseudocode}
\usepackage{algorithm}
\begin{document}
\begin{algorithm}[H]
\caption{Euclide's algorithm}\label{euclid}
\begin{algorithmic}[5]
\Procedure{Euclide}{$a,b$}\Comment{The g.c.d. of a and b}
\State $r\gets a\bmod b$
\While{$r\not=0$}\Comment{We have the answer if r is 0}
\State $a\gets b$
\State $b\gets r$
\State $r\gets a\bmod b$
\EndWhile\label{euclidendwhile}
\State \Return $b$\Comment{The gcd is b}
\EndProcedure
\end{algorithmic}
\end{algorithm}
\end{document}
在此範例中,第一個編號行是第 5 行。有沒有辦法打開第一行的編號?
接下來的問題是,是否可以在任意行上轉動編號?
答案1
您必須更新特定的巨集才能變更列印條件:
\documentclass{article}
\usepackage{algpseudocode,algorithm}
\makeatletter
\def\ALG@step%
{%
\stepcounter{ALG@line}%
\stepcounter{ALG@rem}%
\ifnum\value{ALG@line}=1
% Print line number if it is 1
\alglinenumber{\arabic{ALG@line}}%
\else\ifnum\value{ALG@rem}=\ALG@numberfreq
% Print line number if the ALG@rem = \ALG@numberfreq
\setcounter{ALG@rem}{0}\alglinenumber{\arabic{ALG@line}}%
\fi\fi
}%
\makeatother
\begin{document}
\begin{algorithm}[H]
\caption{Euclide's algorithm}\label{euclid}
\begin{algorithmic}[5]
\Procedure{Euclide}{$a,b$}\Comment{The g.c.d.\ of~$a$ and~$b$}
\State $r \gets a \bmod b$
\While{$r \neq 0$}\Comment{We have the answer if~$r$ is~$0$}
\State $a \gets b$
\State $b \gets r$
\State $r \gets a \bmod b$
\EndWhile\label{euclidendwhile}
\State \Return $b$\Comment{The g.c.d.\ is~$b$}
\EndProcedure
\end{algorithmic}
\end{algorithm}
\end{document}
調整是\ALG@step
插入一個條件來檢查行號是否為1,並進行對應的列印。
一般來說,可以在任意行上開啟編號,但程式碼並未為此設定。