Finding the optimum column and row size for a table with n elements and a given range for its proportion

吃可爱长大的小学妹 提交于 2019-12-02 00:45:19

Instead of doing a prime factorization of n, start from the square root and find the next larger (or smaller -- makes no difference) factor. That pair of factors will the closest to the square root, and therefore the closest to a proportion of 1:1.

Here is some pseudocode for how I've implemented something similarly:

int rowCount;
int colCount;

double tempSQR = SquareRoot(cellCount);
int maxRowCount = RoundAwayFromZero(tempSQR);

if(tempSQR == maxRowCount)
{
   rowCount = maxRowCount;
   colCount = rowCount;
}
else if(cellCount is Even)
{
   rowCount = Min(cellCount/2, maxRowCount);
   colCount = RoundAwayFromZero(cellCount/rowCount);
}
else if(cellCount> 1)
{
   rowCount = Min((cellCount+ 1)/2, maxRowCount);
   colCount = RoundAwayFromZero((cellCount+ 1)/rowCount);
}

if(rowCount * colCount < cellCount)
    rowCount++;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!