在Java 初学者指南第 5 版中,FindFac
类使用嵌套循环来查找 2 到 100 之间的因子。
package examples; public class FindFac { 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(); } } }
它提到:
The preceding program can be made more efficient. Can you see how? (Hint: The number of iterations in the inner loop can be reduced)
据我所知,它暗示“j++”,但我不确定如何改进代码。
最佳答案
从 2 到 i-1 的内循环迭代器。
假设 i 为 100,j 为 2。此代码中的内部循环将从 2 迭代到 99。
但是你只需要迭代直到 i 的 sqrt 为 10。
这是因为当你得到 i 的一个因数(例如 5)时,100/5 是另一个因数,即 20。
因此,通过在内循环中迭代直到 10,您应该获得所有因子。
关于Java 初学者指南 : FindFac & Nested Loops,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22239525/