减少 Java 中的内循环迭代次数以提高效率

Reducing the number of inner loop iterations in Java for efficiency

这是来自 Java 教科书的小挑战。 可以使以下代码更高效(通过减少内部循环迭代的次数,可能使用 continue 语句)。

/*
    Use nested loops to find factors of numbers
    between 2 and 100. 

    In the program, the outer loop runs i from 2 through 100. The inner loop successively tests
    all numbers from 2 up to i, printing those that evenly divide i.

*/

class FindFactors {
    public static void main (String args[]) {

        for (int i = 2; i <= 100; i++) {
            System.out.print("Factors of " + i + ": ");
            for (int j = 2; j < i; j++) 
                if ((i%j) == 0) System.out.print(j + " ");


            System.out.println();
        }
    }
}

但是我尝试 "simplify" 只是增加了更多的步骤。有什么想法吗?

在内循环中测试不是所有数字都达到 i。如果你只测试 i

的一半就足够了
 for (int j = 2; j <= i/2; j++)
for (int j = 2; j < i; j++)

在不剧透的情况下,考虑一个自然数 N,您将为其计算因数。也许您可以减少必须检查的数字数量?

查找整数因式分解以获得更多 information/different 算法。

在外循环索引的平方上设置内循环的长度 每个数字的最大因子是它的平方