我试过 listings 包,但问题是我无法在其中输入数学公式。(左侧的行号从第一行开始,type val
对我来说也可以。)
答案1
尝试一下algorithm2e
。肯定有更好的方法来完成前三行,而且我敢打赌,使用更好的方法可以不编号。但无论如何,这是我的第一次尝试(不是排版算法专家:-)
):
\documentclass{article}
\usepackage{amsmath} % for \text{} in math
\usepackage{geometry} % margin adjust to fit wide comment in one line
\usepackage[
linesnumbered, % number lines
noline, % no vertical rule delimiting blocks
noend, % do not typeset "end" of blocks
nofillcomment, % do not stretch comment width to fill the line
]{algorithm2e}
\SetCommentSty{normalfont}
\SetArgSty{normalfont}
\SetKwComment{tcc}{\texttt{/*} }{ \texttt{*/}}
\SetKwFunction{ptr}{ptr}
\SetKwFunction{ind}{ind}
\SetKwFunction{val}{val}
\SetKwInput{InType}{}
\SetKw{type}{type}
\SetKw{real}{real}
\SetKw{int}{int}
\begin{document}
\begin{algorithm}[H]
\DontPrintSemicolon
{\type $\val : \real [K_{rc} \cdot r \cdot c]$}\;
{\type $\ind : \int [K_{rc}]$}\;
{\type $\ptr : \int [\frac{m}{r} + 1]$}\;
\ForEach{block row $I$}{
$i_o \leftarrow I \cdot r$ \tcc{starting row}
Let $\hat{y} \leftarrow y_{i_{0}:(i_0)+r-1}$ \tcc{Can store in registers}
\For{$L=\ptr [I]$ \KwTo $\ptr [I+1] - 1$}{
$j_0 \leftarrow \ind [L] \cdot c$ \tcc{starting column}
Let $\hat{x} \leftarrow x_{j_0:(j_0+c-1)}$ \tcc{Can store in registers}
Let $\hat{A} \leftarrow a_{i_0:(i_o+r-1), j_0:(j_0+c-1)}$
\tcc{$\hat{A} = \text{block of $A$ stored in $\val [(L \cdot r \cdot c) : ((L+1) \cdot r \cdot c -1)]$}$}
Perform $r \times c$ block multiply, $\hat{y} \leftarrow \hat{y} + \hat{A} \cdot \hat{x}$
}
Store $\hat{y}$
}
\end{algorithm}
\end{document}