您可以将算法划分为更小、更易于理解的块。
// Get the array index given the rank, the row, and the column.
int getArrayIndex(int rank, int row, int col)
{
return (row*rank + col - col*(col+1)/2);
}
// Get the term of a matrix, given the rank, the row, and the column.
int getMatrixTerm(int a[], int rank, int row, int col)
{
if ( col < row )
{
return 0;
}
else
{
return a[getArrayIndex(rank, row, col)];
}
}
// Get the term for a row and column resulting from mulitiplication.
int getMultipliedTerm(int a[], int b[], int rank, int row, int col)
{
int term = 0;
int k = 0;
for ( ; k < rank; ++k )
{
term += getMatrixTerm(a, rank, row, k)*getMatrixTerm(b, rank, k, col);
}
return term;
}
// Set the term in c given the rank, the row, and the column.
void setMultipliedTerm(int a[], int b[], int c[], int rank, int row, int col)
{
if ( j >= i )
{
c[getArrayIndex(rank, i, j)] = getMultipliedTerm(a, b, rank, i, j);
}
}
// High level function to multiply two upper triangular matrices
// The lower part of the matrix is not stored at all.
void multiply(int a[], int b[], int c[], int rank)
{
int i = 0;
int j = 0;
for ( i = 0; i < rank; ++i )
{
for ( j = 0; j < rank; ++j )
{
setMultipliedTerm(a, b, c, rank, i, j);
}
}
}