为什么一个嵌套的循环,同时比其他快嵌套while循环?

问题描述 投票:-1回答:3

于是我就在课堂写作嵌套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) {
        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);

}

}

enter image description here

第二while循环

public class TimeWhile {

public static void main(String[] args) {
    int n = 100000;
    int z = 1;
    long startTime = System.currentTimeMillis();

    int x = 0;
    int y = 0;
    while (x <= n) {
        while (y <= n) {
            z = x * y;
            x++;
            y++;    
        }
    }
    long endTime = System.currentTimeMillis();
    long elapsed = endTime - startTime;
    System.out.println("The time is " + elapsed);
    System.out.println("The number is " + z);

}

}

enter image description here

为什么第二次运行得更快?输出“Z”是一样的。

java algorithm
3个回答
2
投票

我相信有很多事情是不对的代码。

首先,没有必要计算z = x * y环路内侧,每个但最后一次迭代覆盖值。所以,你的代码实际上是一样的:

heatTheUniverseForSomeTime();
int z = n*n;

这意味着一个事实,即z的输出是一样的,其实就是几乎一无所知的循环是如何工作的。

其次int不够大类型持有100000*100000的价值。这就是为什么你1410065408,而不是更多的预期10000000000long将有助于(但要注意,你应该投至少一个参数long右边的!)。如果你需要更大的价值,考虑BigInteger

第三点是,你的第一个例子可以通过使用for循环中重新写在一个更常用,因此可以理解的形式:

for(int x = 0; x <= n; x++) {
    for(int y = 0; y <= n; y++) {
        z = x * y;
    }
}

此代码显然需要在总运行n*n迭代。

同时,我认为现在点#1变得更加清晰。

最后,你的第二个代码并不等同于这2个不同的方面:

  • 所以第一次后内运行循环运行,它永远不会再次运行的指出你永远不会重置y
  • 此外,因为您在内环做x++;为好,这意味着它总是认为x == y,所以外循环的第一次迭代后从不运行为好。

你第二个代码实际上是相同的

for(int x = 0, y = 0; y <= n && x <= n; x++, y++) {
    z = x * y;
}

此代码显然需要只运行n倍,而不是n*n这是更快得多。


2
投票

在第一回路y的值总是被分配到zeroiteration,使得它需要更多的时间和步骤达到n而在第二循环中,y不重置了由此zero它达到n更快,在更短的步骤。

LOOP1

while (x <= n) {
        int y = 0;

环2

 while (x <= n) {
        while (y <= n) {
            z = x * y;
            x++;
            y++;    
        }

1
投票

第二个运行更快,因为你增加在嵌套while循环,而不是在外部时循环X。而循环运行许多比外循环多次,因为它会不断重复,直到外环的条件为假的嵌套。如果你把X的嵌套循环,就会重复多次连续,使得外环的条件为假更快。

© www.soinside.com 2019 - 2024. All rights reserved.