Why does Java think that the product of all numbers from 10 to 99 is 0?

前端 未结 9 1505
悲哀的现实
悲哀的现实 2020-12-02 05:56

The following block of codes gives the output as 0.

public class HelloWorld{

    public static void main(String []args){
        int product = 1;
        fo         


        
9条回答
  •  旧巷少年郎
    2020-12-02 06:42

    Computer multiplication is really happening modulo 2^32. Once you have accumulated enough powers of two in the multiplicand, then all values will be 0.

    Here we have all the even numbers in the series, along with the maximum power of two that divides the number, and the cumulative power of two

    num   max2  total
    10    2     1
    12    4     3
    14    2     4
    16    16    8
    18    2     9
    20    4    11
    22    2    12
    24    8    15
    26    2    16
    28    4    18
    30    2    19
    32    32   24
    34    2    25
    36    4    27
    38    2    28
    40    8    31
    42    2    32
    

    The product up to 42 is equal to x * 2^32 = 0 (mod 2^32). The sequence of the powers of two is related to Gray codes (among other things), and appears as https://oeis.org/A001511.

    EDIT: to see why other responses to this question are incomplete, consider the fact that the same program, restricted to odd integers only, would not converge to 0, despite all the overflowing.

提交回复
热议问题