如何为未知数量的数字显示正方形 table

How to display square table for an unknown amount of numbers

我正在编写一个程序来计算质数序列,然后将它们显示在 table 中。

程序要求用户输入 2 个整数:第一个是序列开始的数字,第二个是要找到的素数的数量。到这里为止,程序运行完美。 问题是素数应该显示在 "squarish" table 中,这意味着如果可能的话,table 应该是完美的正方形。如果那不可能,那么行数和列数的差异不应超过 1。

这是我尝试过的示例:

   int columns = 0;
   int rows = 0;
   int element = 0;

   rows = (int) Math.sqrt(numberOfPrimes);
   columns = (rows * rows) < numberOfPrimes ? rows + 1 : rows;

   if(numberOfPrimes%3 - 1.0 < 0.001)
   {
       columns = rows + 1;
       rows = rows + 1;
   }

   if (numberOfPrimes > 100)
   {
       columns = 10;
       if (rows * rows < numberOfPrimes)
       {
           rows = numberOfPrimes / 10;
       }

   }
   System.out.println(numberOfPrimes + " = [" + rows + "," + columns + "]");


   for (int r = 0; r < rows; r++) 
   {
      for (int c = 0; c < columns; c++)
      {
          System.out.printf("%6s", primesArray[element] + "\t");
          if (element == primesArray.length - 1)
          {
              break;
          }
          element++;
      }
      System.out.println();
   }

table 对某些输入正确显示,但对其他输入不正确。我知道此代码不正确,但我不知道如何编写正确的代码来执行此操作。 任何帮助将不胜感激。

编辑:我将代码更新为现在的代码。 table 对于奇数(例如 33)无法正常工作。它只打印 30 个数字,而不打印剩余的 3 个数字。我需要一个额外的行来打印剩余的数字,即使该行不完整。 我试图解决这个问题,但我创建了一个数组越界错误。 另外,我添加了一个 if 语句,因为如果素数的数量超过 100,那么 table 应该只有 10 列并且不会是正方形。

编辑 2:我设法解决了问题,并且更新了代码以显示解决方案。但是,我不得不休息,而我的教授不允许我们休息。一旦我们到达数组中的最后一个元素,是否有任何其他方法可以退出循环?

这是一种方式

    int primeNumbersToBeFound = 33;

    int rows = (int) Math.ceil(Math.sqrt(primeNumbersToBeFound));
    int cols = rows;
    if (rows * (rows - 1) >= primeNumbersToBeFound) {
        cols--;
    }

    System.out.println(primeNumbersToBeFound + " = [" + rows + "," + cols + "]");

然后你可以遍历打印素数的行和列。

    for (int r = 0; r < rows; r++) {
        for (int c = 0; c < cols && element < primesArray.length; c++, element++) {
            System.out.print(primesArray[element]);
        }
        System.out.println();
    }