Java 为什么一个嵌套的while循环比另一个嵌套的while循环快?
所以我在课堂上写了一个嵌套的while循环来计算z的值。我需要输出z和获得它所需的时间 结果如下Java 为什么一个嵌套的while循环比另一个嵌套的while循环快?,java,algorithm,Java,Algorithm,所以我在课堂上写了一个嵌套的while循环来计算z的值。我需要输出z和获得它所需的时间 结果如下 public class TimeWhile { public static void main(String[] args) { int n = 100000; int z = 1; long startTime = System.currentTimeMillis(); int x = 0; while (x <= n) { in
public class TimeWhile {
public static void main(String[] args) {
int n = 100000;
int z = 1;
long startTime = System.currentTimeMillis();
int x = 0;
while (x <= n) {
int y = 0;
while (y <= n) {
z = x * y;
y++;
}
x++;
}
long endTime = System.currentTimeMillis();
long elapsed = endTime - startTime;
System.out.println("The time is " + elapsed);
System.out.println("The number is " + z);
}
}
公共类TimeWhile{
公共静态void main(字符串[]args){
int n=100000;
intz=1;
long startTime=System.currentTimeMillis();
int x=0;
(x在第一个循环中,y
的值总是在每次迭代中分配给0
,使得达到n
需要更多的时间和步骤,而在第二个循环中,y
没有重置为0
,因此它达到n的速度更快,步骤更少
loop1
while (x <= n) {
int y = 0;
while(x我相信这个代码有很多地方是错误的
首先,无需在循环内计算z=x*y
,因为每次迭代都会覆盖该值。因此,您的代码实际上与:
heatTheUniverseForSomeTime();
int z = n*n;
这意味着z
的输出是相同的,这实际上与循环的工作方式无关
其次,int
的类型不够大,无法容纳100000*100000
的值。这就是为什么您选择了1410065408
而不是更期望的1000000000
long
会有所帮助的原因(但请注意,您也应该在右侧对long
至少使用一个参数!)如果你需要更大的价值,考虑一下。< /P>
第三点是,通过使用for
循环,您的第一个示例可以以更常见、更容易理解的形式重新编写,如下所示:
for(int x = 0; x <= n; x++) {
for(int y = 0; y <= n; y++) {
z = x * y;
}
}
这段代码显然只需要运行n
次,而不是运行快得多的n*n
。第二段运行快得多,因为您在嵌套的while循环中增加了x,而不是在外部while循环中。嵌套的while循环运行的次数比外部循环多,因为它会一直重复到外部loop的条件为false。如果将x放入嵌套循环,它将连续重复更多次,使外部循环的条件更快为false。因为在后者中从不重置y
,所以在外部while
的第一次迭代后,内部while
循环将永远不会执行。这意味着第一个算法ithm有运行时O(n^2),而后者有运行时O(n)。学习使用调试器,然后使用调试器逐步完成代码的好时机。一个更好的技巧是,在心里练习遍历代码,就像你是计算机/JVM一样,问问自己每一步代码都在做什么。
heatTheUniverseForSomeTime();
int z = n*n;
for(int x = 0; x <= n; x++) {
for(int y = 0; y <= n; y++) {
z = x * y;
}
}
for(int x = 0, y = 0; y <= n && x <= n; x++, y++) {
z = x * y;
}