为什么此值的输出结果始终为零?

时间:2013-06-13 19:59:14

标签: java algorithm

我正在运行此代码,但为什么m的输出结果总是为零?

这很奇怪,因为m被初始化为2。

public class ScalabilityTest {

public static void main(String[] args) {
    long oldTime = System.currentTimeMillis();
    double[] array = new double[100000];
    int p = 2;
    int m = 2;
    for ( int i = 0; i < array.length; i++ ) {
        p += p * 12348;
        for ( int j = 0; j < i; j++ ) {
            double x = array[j] + array[i];
            m += m * 12381923;
        }
    }

    System.out.println( (System.currentTimeMillis()-oldTime) / 1000 );
    System.out.println( p + ", " + m );
    }

}

3 个答案:

答案 0 :(得分:8)

由于您始终将m的值乘以数字并添加到m,因此在第16次迭代时它会溢出为0

实际上,由于您将数字乘以奇数,然后将其添加到原始数字,您将其乘以偶数,这使得尾随0位至少向左移动一步,因此它以0

结尾
1 1011110011101110111001000 24763848
2 1111011100110010111011000100000 2073654816
3 1111111111111101111010010000000 2147415168
4 10010100011000001100001000000000 -1805598208
5 10010010100010001100100000000000 -1836529664
6 10001011110000100010000000000000 -1950212096
7 1110010101001001000000000000000 1923383296
8 1001100000100000000000000000 159514624
9 1010011110010000000000000000000 1405616128
10 10001110001000000000000000000000 -1910505472
11 1010100100000000000000000000000 1417674752
12 1000010000000000000000000000000 1107296256
13 11001000000000000000000000000000 -939524096
14 100000000000000000000000000000 536870912
15 10000000000000000000000000000000 -2147483648
16 0 0

答案 1 :(得分:4)

这是一个观察:一旦m达到0,执行

m += m * 12381923;

m保持为0。

我编写了一个程序来输出m的值,这是我发现的:

2
24763848
2073654816
2147415168
-1805598208
-1836529664
-1950212096
1923383296
159514624
1405616128
-1910505472
1417674752
1107296256
-939524096
536870912
-2147483648
0
Converged after 16 iterations.

供参考,这是来源:

public class Converge {
    public static void main(String[] args) {
        int m = 2;
        long counter = 0; // Unnecessary, but I didn't know how many iterations we'd need!

        while (m != 0) {
            System.out.println(m);
            m += m * 12381923;
            counter++;
        }
        System.out.println(m);
        System.out.println("Converged after " + counter + " iterations.");
    }
}

希望这有帮助!

答案 2 :(得分:0)

这是因为int值溢出。以下documentation表明int的最大值为2,147,483,647,并且在第16次迭代发生时,m大于此值,因此溢出。