【发布时间】:2016-03-04 15:08:52
【问题描述】:
这是来自 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();
}
}
}
但是我尝试“简化”只是增加了更多步骤。有什么想法吗?
【问题讨论】:
-
检查 j 是否小于 i/2 永远不会有大于 i 一半的因子
-
你也可以计算出它的反因数,然后你就可以把极限设为i的sqrt
标签: java loops for-loop nested continue