更新时间:2023-01-02 10:15:51
新答案
您可以找到行
和列
使用以下公式:
You can find the row
and column
using the following formulas:
int row = floor(-0.5 + sqrt(0.25 + 2 * index));
int triangularNumber = row * (row + 1) / 2;
int column = index - triangularNumber;
之所以有用,是因为每一行的第一项是三角数(0、1、3、6、10、15 ...)。因此,低于 index
的最大三角数为我们提供了 row
行。那么列
就是索引
与该三角形之间的差。
This works because the first item in each row is a triangular number (0, 1, 3, 6, 10, 15, ...). So the biggest triangular number that is lower than index
gives us the row
. Then column
is simply the difference between index
and that triangular number.
此外,请注意,您不需要参数 M
。
Also, note that you don't need the parameter M
.
旧答案
此代码将为您提供行
和索引
的列
。
This code will give you both the row
and column
of index
.
int triangularNumber = 0;
int row = 0;
while (triangularNumber + row < index) {
row ++;
triangularNumber += row;
}
int column = index - triangularNumber;