131

The following block of codes gives the output as 0.

public class HelloWorld{

    public static void main(String []args){
        int product = 1;
        for (int i = 10; i <= 99; i++) {
            product *= i;
        }
        System.out.println(product);
    }
}

Please can somebody explain why this happens?

Salman A
  • 262,204
  • 82
  • 430
  • 521
Aniruddha Sarkar
  • 1,903
  • 2
  • 14
  • 15
  • 106
    You most probably have an integer overflow. – TheLostMind Oct 15 '14 at 06:34
  • 1
    But i have also done the program using long. – Aniruddha Sarkar Oct 15 '14 at 06:36
  • 3
    Max int value is 2147483647, max long value is 9223372036854775807. So you get overflow in both cases – ponomandr Oct 15 '14 at 06:43
  • 68
    If you consider the prime factors in the product, you'll have `2` show up about 90 times. That means you'll need a variable with at least 90 bits to get a non-zero output. 32 and 64 are both less than 90. In order to compute integers larger than the native words, you have to use whatever big integer class is available in your chosen language. – kasperd Oct 15 '14 at 10:51
  • 4
    Feel free to use `BigInteger` instead. – Paul Draper Oct 15 '14 at 13:52
  • 62
    Technically, this is the product of numbers from 10 to 98. – AShelly Oct 15 '14 at 14:14
  • 1
    @PaulDraper Alternatively, use a language that doesn't have integer overflows. – Wlerin Oct 16 '14 at 00:18
  • 45
    What? Why was this question closed as a duplicate of a question _which is being closed as a duplicate of **this** question_? – Salman A Oct 16 '14 at 05:06
  • 3
    This isn't a duplicate in any case. The interesting thing here is not why the answer is wrong but why it's 0, which isn't asked in the other question. – chiastic-security Oct 16 '14 at 06:43
  • 2
    Not a duplicate. Vote for reopen – Ruchira Gayan Ranaweera Oct 16 '14 at 08:50
  • 7
    FYI, the answer is `25977982938941930515945176761070443325092850981258133993315252362474391176210383043658995147728530422794328291965962468114563072000000000000000000000`. So this is definitely an integer overflow issue if you're using `int`! – zamnuts Oct 16 '14 at 16:43
  • Kinda the same reason why factorials can't be calculated to large numbers using just `int`. – ADTC Oct 17 '14 at 00:36
  • 6
    @zamnuts That's the correct answer to the product of all integers from 10 to 98, which is what he coded it to do. The product of all integers from 10 to 99, as stated in the title, is `2571820310955251121078572499345973889184192247144555265338209983884964726444827921322240519625124511856638500904630284343341744128000000000000000000000`. ([source](http://www.wolframalpha.com/input/?i=99!%2F9!)) – Tortoise Oct 17 '14 at 03:58
  • 82
    Got 99 problems and 2147483648 aint 1. – glenatron Oct 17 '14 at 08:53
  • 1
    @aniruddha.sarkar Have you tried moving the print statement inside the loop? What happens? – Colonel Panic Oct 17 '14 at 21:55
  • 1
    This demonstrates the old adage that any language which requires developers to know and care about the number of bits required to store a given numeric value is unsuitable for most programming. And of course a disturbing aspect of this is that no exception was raised, leading to silently getting the answer completely wrong. – Bob Jarvis - Слава Україні Oct 18 '14 at 03:42
  • 2
    Very closely related is this question: [Why does i = i + i give me 0?](http://stackoverflow.com/questions/24173463/why-does-i-i-i-give-me-0) – Qantas 94 Heavy Oct 19 '14 at 06:32
  • Things are much easier in Haskell, you just need: product [10..99], and you get: 2571820310955251121078572499345973889184192247144555265338209983884964726444827921322240519625124511856638500904630284343341744128000000000000000000000 – Martin Capodici Oct 19 '14 at 22:34
  • There are 9 powers of 10 in the series, so the result must at least contain 9 zeroes at the end. And there are multiple combos of numbers with factors of 2 and 5 which, when multiplied, yield powers of 10. There are 45 even numbers, and 9 powers of 5 that is not powers of 10, which means at least 9 combos of numbers with factors of 2 and 5, yield another 9 zeros. So we have at least 19 zeros at the end of the result. – Stephen Chung Oct 22 '14 at 04:29
  • 2
    very basic and academic question.. you could evaluate yourself.. – akjain Oct 22 '14 at 11:01
  • if you want the actual product try BigInteger. – Key_coder Nov 13 '14 at 12:56
  • **Summing up** the methods to avoid this problem: **(1)** use `double` instead of `int`; valid for up to 308 digits in the integer result. **(2)** use [java.math.BigInteger](http://docs.oracle.com/javase/7/docs/api/java/math/BigInteger.html). **(3)** use a language that will switch to arbitrary-length integer automatically when needed, such as [Python](https://docs.python.org/3/library/stdtypes.html#typesnumeric). – Lutz Prechelt Feb 01 '15 at 15:15
  • There are 45 even numbers from 10 to 99, so definitely the last 45 bits of the result must be 0, which overflows int. Counting more factors of 2 in those numbers results in a lot more low 0 bits, which also overflows long – phuclv Mar 02 '15 at 09:51

9 Answers9

425

Here is what the program does at each step:

          1 * 10 =          10
         10 * 11 =         110
        110 * 12 =        1320
       1320 * 13 =       17160
      17160 * 14 =      240240
     240240 * 15 =     3603600
    3603600 * 16 =    57657600
   57657600 * 17 =   980179200
  980179200 * 18 =   463356416
  463356416 * 19 =   213837312
  213837312 * 20 =   -18221056
  -18221056 * 21 =  -382642176
 -382642176 * 22 =   171806720
  171806720 * 23 =  -343412736
 -343412736 * 24 =   348028928
  348028928 * 25 =   110788608
  110788608 * 26 = -1414463488
-1414463488 * 27 =   464191488
  464191488 * 28 =   112459776
  112459776 * 29 = -1033633792
-1033633792 * 30 =  -944242688
 -944242688 * 31 =   793247744
  793247744 * 32 =  -385875968
 -385875968 * 33 =   150994944
  150994944 * 34 =   838860800
  838860800 * 35 =  -704643072
 -704643072 * 36 =   402653184
  402653184 * 37 =  2013265920
 2013265920 * 38 =  -805306368
 -805306368 * 39 = -1342177280
-1342177280 * 40 = -2147483648
-2147483648 * 41 = -2147483648
-2147483648 * 42 =           0
          0 * 43 =           0
          0 * 44 =           0
vvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
vvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
          0 * 97 =           0
          0 * 98 =           0

Notice that on some steps the multiplication results in a smaller number (980179200 * 18 = 463356416) or incorrect sign (213837312 * 20 = -18221056), indicating that there was an integer overflow. But where does the zero come from? Read on.

Keeping in mind that int data type is a 32-bit signed, two's complement integer, here is an explanation of each step:

Operation         Result(1)     Binary Representation(2)                                           Result(3)
----------------  ------------  -----------------------------------------------------------------  ------------
          1 * 10            10                                                               1010            10
         10 * 11           110                                                            1101110           110
        110 * 12          1320                                                        10100101000          1320
       1320 * 13         17160                                                    100001100001000         17160
      17160 * 14        240240                                                 111010101001110000        240240
     240240 * 15       3603600                                             1101101111110010010000       3603600
    3603600 * 16      57657600                                         11011011111100100100000000      57657600
   57657600 * 17     980179200                                     111010011011000101100100000000     980179200
  980179200 * 18   17643225600                               100 00011011100111100100001000000000     463356416
  463356416 * 19    8803771904                                10 00001100101111101110011000000000     213837312
  213837312 * 20    4276746240                                   11111110111010011111100000000000     -18221056
  -18221056 * 21    -382642176  11111111111111111111111111111111 11101001001100010101100000000000    -382642176
 -382642176 * 22   -8418127872  11111111111111111111111111111110 00001010001111011001000000000000     171806720
  171806720 * 23    3951554560                                   11101011100001111111000000000000    -343412736
 -343412736 * 24   -8241905664  11111111111111111111111111111110 00010100101111101000000000000000     348028928
  348028928 * 25    8700723200                                10 00000110100110101000000000000000     110788608
  110788608 * 26    2880503808                                   10101011101100010000000000000000   -1414463488
-1414463488 * 27  -38190514176  11111111111111111111111111110111 00011011101010110000000000000000     464191488
  464191488 * 28   12997361664                                11 00000110101101000000000000000000     112459776
  112459776 * 29    3261333504                                   11000010011001000000000000000000   -1033633792
-1033633792 * 30  -31009013760  11111111111111111111111111111000 11000111101110000000000000000000    -944242688
 -944242688 * 31  -29271523328  11111111111111111111111111111001 00101111010010000000000000000000     793247744
  793247744 * 32   25383927808                               101 11101001000000000000000000000000    -385875968
 -385875968 * 33  -12733906944  11111111111111111111111111111101 00001001000000000000000000000000     150994944
  150994944 * 34    5133828096                                 1 00110010000000000000000000000000     838860800
  838860800 * 35   29360128000                               110 11010110000000000000000000000000    -704643072
 -704643072 * 36  -25367150592  11111111111111111111111111111010 00011000000000000000000000000000     402653184
  402653184 * 37   14898167808                                11 01111000000000000000000000000000    2013265920
 2013265920 * 38   76504104960                             10001 11010000000000000000000000000000    -805306368
 -805306368 * 39  -31406948352  11111111111111111111111111111000 10110000000000000000000000000000   -1342177280
-1342177280 * 40  -53687091200  11111111111111111111111111110011 10000000000000000000000000000000   -2147483648
-2147483648 * 41  -88046829568  11111111111111111111111111101011 10000000000000000000000000000000   -2147483648
-2147483648 * 42  -90194313216  11111111111111111111111111101011 00000000000000000000000000000000             0
          0 * 43             0                                                                  0             0
vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
          0 * 98             0                                                                  0             0
  1. is the correct result
  2. is the internal representation of the result (64 bits are used for illustration)
  3. is the result represented by the two's complement of the lower 32 bits

We know that multiplying a number by an even number:

  • shifts the bits towards left and adds zero bits towards right
  • results in an even number

So basically your program multiplies an even number with another number repeatedly which zeroes out the result bits starting from right.

PS: If the multiplications involved odd numbers only then the result will not become zero.

Salman A
  • 262,204
  • 82
  • 430
  • 521
  • 15
    The Hex Representation is what helped me get my head around what was happening here. Thanks for clarifying! –  Oct 15 '14 at 16:26
  • 1
    Yeah, it would be more instructive if you modified your program to also print out the hex values in the long list. – Hot Licks Oct 15 '14 at 20:25
  • 1
    In the last list of conditions, you also need to specify that "multiplying an even number by an odd number will not change the number of trailing 0s". Otherwise the proof is incomplete. – user295691 Oct 15 '14 at 22:04
  • 4
    This answer is correct but there is _so_ much clutter. The last five lines are the heart of it, and nowhere does it really illustrate where how exactly that comes into play. (But one can puzzle it out from the giant table.) – Rex Kerr Oct 16 '14 at 20:03
  • 1
    I see that 42 strikes again. – NotMe Oct 17 '14 at 19:33
  • 6
    Put another way, you accumulate factors of 2. Some numbers give you multiple factors of 2 all by themselves, like 12, 16, and 20. Every factor of 2 will right-shift all the bits of all your subsequent results, leaving zeroes as placeholders. Once you've right-shifted 32 times, you're left with nothing but 32 placeholder zeroes. – Keen Oct 17 '14 at 20:29
  • 3
    A similar effect can also be seen in base 10. Try multiplying any series of consecutive integers, every time you multiply by a number divisible by 10, you add at least one zero to the end of the product, and it's impossible to remove that zero from the product by multiplication of integers. At some point, all the n-th least significant digits will be filled with zeroes and if you are doing the arithmetic to a modulo 10**m (which has the effect of chopping off everything but the m-th least significant digits), then it'll end up turning to zero. Likewise with any other bases. – Lie Ryan Oct 19 '14 at 03:04
  • I agree with @RexKerr. I'd like to upvote the last five lines, and downvote the rest. This is a seriously mediocre answer. – Dawood ibn Kareem Oct 20 '14 at 08:11
71

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.

user295691
  • 7,108
  • 1
  • 26
  • 35
  • Yay! Finally, the correct answer. People should notice this answer more! – Rex Kerr Oct 16 '14 at 19:57
  • This is the only correct answer. All the others don't explain *why*. – Olivier Grégoire Oct 17 '14 at 10:20
  • 5
    @OlivierGrégoire I disagree; I think the accepted answer is correct and does give a perfectly good explanation. This one is just more direct. – David Z Oct 17 '14 at 21:41
  • 1
    I hope more people see this answer. The root cause is stated here! – lanpa Oct 18 '14 at 17:53
  • 1
    @DavidZ: Agreed; the accepted answer is mostly correct -- my post does not really address the "why" of my opening sentence. But the accepted answer's close is the closest thing to an answer to "why zero", but it doesn't explain "why 42" -- there are only 16 even numbers between 10 and 42 – user295691 Oct 20 '14 at 20:12
34

It looks like an integer overflow.

Take a look at this

BigDecimal product=new BigDecimal(1);
for(int i=10;i<99;i++){
    product=product.multiply(new BigDecimal(i));
}
System.out.println(product);

Output:

25977982938941930515945176761070443325092850981258133993315252362474391176210383043658995147728530422794328291965962468114563072000000000000000000000

Output no longer be a int value. Then you will get wrong value because of the overflow.

If it overflows, it goes back to the minimum value and continues from there. If it underflows, it goes back to the maximum value and continues from there.

More info

Edit.

Let's change your code as follows

int product = 1;
for (int i = 10; i < 99; i++) {
   product *= i;
   System.out.println(product);
}

Out put:

10
110
1320
17160
240240
3603600
57657600
980179200
463356416
213837312
-18221056
-382642176
171806720
-343412736
348028928
110788608
-1414463488
464191488
112459776
-1033633792
-944242688
793247744
-385875968
150994944
838860800
-704643072
402653184
2013265920
-805306368
-1342177280
-2147483648
-2147483648>>>binary representation is 11111111111111111111111111101011 10000000000000000000000000000000 
 0 >>> here binary representation will become 11111111111111111111111111101011 00000000000000000000000000000000 
 ----
 0
Community
  • 1
  • 1
Ruchira Gayan Ranaweera
  • 34,993
  • 17
  • 75
  • 115
23

It's because of integer overflow. When you multiply many even numbers together, the binary number gets a lot of trailing zeroes. When you have over 32 trailing zeroes for an int, it rolls over to 0.

To help you visualize this, here are the multiplications in hex calculated on a number type that won't overflow. See how the trailing zeroes slowly grow, and note that an int is made up of the last 8 hex-digits. After multiplying by 42 (0x2A), all 32 bits of an int are zeroes!

                                     1 (int: 00000001) * 0A =
                                     A (int: 0000000A) * 0B =
                                    6E (int: 0000006E) * 0C =
                                   528 (int: 00000528) * 0D =
                                  4308 (int: 00004308) * 0E =
                                 3AA70 (int: 0003AA70) * 0F =
                                36FC90 (int: 0036FC90) * 10 =
                               36FC900 (int: 036FC900) * 11 =
                              3A6C5900 (int: 3A6C5900) * 12 =
                             41B9E4200 (int: 1B9E4200) * 13 =
                            4E0CBEE600 (int: 0CBEE600) * 14 =
                           618FEE9F800 (int: FEE9F800) * 15 =
                          800CE9315800 (int: E9315800) * 16 =
                         B011C0A3D9000 (int: 0A3D9000) * 17 =
                        FD1984EB87F000 (int: EB87F000) * 18 =
                      17BA647614BE8000 (int: 14BE8000) * 19 =
                     25133CF88069A8000 (int: 069A8000) * 1A =
                    3C3F4313D0ABB10000 (int: ABB10000) * 1B =
                   65AAC1317021BAB0000 (int: 1BAB0000) * 1C =
                  B1EAD216843B06B40000 (int: 06B40000) * 1D =
                142799CC8CFAAFC2640000 (int: C2640000) * 1E =
               25CA405F8856098C7B80000 (int: C7B80000) * 1F =
              4937DCB91826B2802F480000 (int: 2F480000) * 20 =
             926FB972304D65005E9000000 (int: E9000000) * 21 =
           12E066E7B839FA050C309000000 (int: 09000000) * 22 =
          281CDAAC677B334AB9E732000000 (int: 32000000) * 23 =
         57BF1E59225D803376A9BD6000000 (int: D6000000) * 24 =
        C56E04488D526073CAFDEA18000000 (int: 18000000) * 25 =
      1C88E69E7C6CE7F0BC56B2D578000000 (int: 78000000) * 26 =
     43C523B86782A6DBBF4DE8BAFD0000000 (int: D0000000) * 27 =
    A53087117C4E76B7A24DE747C8B0000000 (int: B0000000) * 28 =
  19CF951ABB6C428CB15C2C23375B80000000 (int: 80000000) * 29 =
 4223EE1480456A88867C311A3DDA780000000 (int: 80000000) * 2A =
AD9E50F5D0B637A6610600E4E25D7B00000000 (int: 00000000)
Tim S.
  • 55,448
  • 7
  • 96
  • 122
  • 1
    This is a little bit misleading. While it does correctly demonstrate why it goes to zero, each value is held in a 32-bit int after multiplication, so it should be truncated after each step. The way you wrote your answer implies that it isn't truncated until the for loop terminates. It would be better if you only showed the last 8 digits for each step. – RyNo Oct 16 '14 at 15:52
  • @KamikazeScotsman I've improved my answer based on your suggestion. Less redundant zeroes, more 32-bit int visibility. – Tim S. Oct 16 '14 at 16:25
  • 1
    +1 for showing the actual value vs 32-bit value on each stage, highlighting that the value is being truncated... – kwah Oct 20 '14 at 13:08
15

Somewhere in the middle you get 0 as the product. So, your entire product will be 0.

In your case :

for (int i = 10; i < 99; i++) {
    if (product < Integer.MAX_VALUE)
        System.out.println(product);
    product *= i;
}
// System.out.println(product);

System.out.println(-2147483648 * EvenValueOfi); // --> this is the culprit (Credits : Kocko's answer )

O/P :
1
10
110
1320
17160
240240
3603600
57657600
980179200
463356416
213837312
-18221056
-382642176
171806720
-343412736
348028928
110788608
-1414463488
464191488
112459776
-1033633792
-944242688
793247744
-385875968
150994944
838860800
-704643072
402653184
2013265920
-805306368
-1342177280  --> Multiplying this and the current value of `i` will also give -2147483648 (INT overflow)
-2147483648  --> Multiplying this and the current value of `i` will also give -2147483648 (INT overflow)

-2147483648  ->  Multiplying this and the current value of 'i' will give 0 (INT overflow)
0
0
0

Every time you multiply the current value of i with the number you get 0 as output.

Solomon Slow
  • 25,130
  • 5
  • 37
  • 57
TheLostMind
  • 35,966
  • 12
  • 68
  • 104
  • @KickButtowski - Multiply the numbers.. You will know why :P – TheLostMind Oct 15 '14 at 06:43
  • @KickButtowski - 0 multiplied by any other number will constantly result in 0 forever after the overflow returns 0 at any point. – Mr Moose Oct 15 '14 at 06:44
  • I did but I think you should be more informative so other can learn too – Kick Buttowski Oct 15 '14 at 06:44
  • @KickButtowski - updated the answer. Check the OP part. – TheLostMind Oct 15 '14 at 06:46
  • 8
    @KickButtowski: It's because the overflow-wrapping happens at a power of two. Essentially, the OP is computing {10 x 11 x 12 x ... x 98} modulo 2^32. Since multiples of 2 appear many more than 32 times in that product, the result is zero. – ruakh Oct 15 '14 at 06:48
  • When in integer overflows, it gets the minimum value, from there on, it'll eventually reach 0 in the loop. – Maroun Oct 15 '14 at 06:49
  • @MarounMaroun Not every integer overflow gets to the minimum value, it just happens at some point here. But there are multiple integer overflows before reaching Integer.MIN_VALUE. – Paŭlo Ebermann Oct 15 '14 at 17:30
  • @ruakh: I didn't see this comment until I posted my answer -- it was probably worth posting as an answer, because it adds critical information missing in the post that you have commented on. – user295691 Oct 15 '14 at 21:52
12

Since many of the existing answer point to implementation details of Java and debug output, lets have a look at the math behind binary multiplication to really answer the why.

The comment of @kasperd goes in the right direction. Suppose you do not multiply directly with the number but with the prime factors of that number instead. Than a lot of numbers will have 2 as a prime factor. In binary this is equal to a left shift. By commutativity we can multiply with prime factors of 2 first. That means we just do a left shift.

When having a look at binary multiplication rules, the only case where a 1 will result in a specific digit position is when both operand values are one.

So the effect of a left shift is that the lowest bit position of a 1 when further multiplying the result is increased.

Since integer contains only the lowest order bits, they all will be set to 0 when the prime factor 2 is cotnained often enough in the result.

Note that two's complement representation is not of interest for this analysis, since the sign of the multiplication result can be computed independently from the resulting number. That means if the value overflows and becomes negative, the lowest order bits are represented as 1, but during multiplication they are treated again as being 0.

SpaceTrucker
  • 13,377
  • 6
  • 60
  • 99
7

If I run this code What I get all -

          1 * 10 =          10
         10 * 11 =         110
        110 * 12 =        1320
       1320 * 13 =       17160
      17160 * 14 =      240240
     240240 * 15 =     3603600
    3603600 * 16 =    57657600
   57657600 * 17 =   980179200
  980179200 * 18 =   463356416 <- Integer Overflow (17643225600)
  463356416 * 19 =   213837312
  213837312 * 20 =   -18221056
  -18221056 * 21 =  -382642176
 -382642176 * 22 =   171806720
  171806720 * 23 =  -343412736
 -343412736 * 24 =   348028928
  348028928 * 25 =   110788608
  110788608 * 26 = -1414463488
-1414463488 * 27 =   464191488
  464191488 * 28 =   112459776
  112459776 * 29 = -1033633792
-1033633792 * 30 =  -944242688
 -944242688 * 31 =   793247744
  793247744 * 32 =  -385875968
 -385875968 * 33 =   150994944
  150994944 * 34 =   838860800
  838860800 * 35 =  -704643072
 -704643072 * 36 =   402653184
  402653184 * 37 =  2013265920
 2013265920 * 38 =  -805306368
 -805306368 * 39 = -1342177280
-1342177280 * 40 = -2147483648
-2147483648 * 41 = -2147483648
-2147483648 * 42 =           0 <- produce 0 
          0 * 43 =           0

Integer Overflow cause -

980179200 * 18 =   463356416 (should be 17643225600)

17643225600 : 10000011011100111100100001000000000 <-Actual
MAX_Integer :     1111111111111111111111111111111
463356416   :     0011011100111100100001000000000 <- 32 bit Integer

Produce 0 cause -

-2147483648 * 42 =           0 (should be -90194313216)

-90194313216: 1010100000000000000000000000000000000 <- Actual
MAX_Integer :       1111111111111111111111111111111
0           :      00000000000000000000000000000000 <- 32 bit Integer
Subhrajyoti Majumder
  • 40,646
  • 13
  • 77
  • 103
6

Eventually, the calculation overflows, and eventually that overflow leads to a product of zero; that happens when product == -2147483648 and i == 42. Try this code out to verify it for yourself (or run the code here):

import java.math.BigInteger;

class Ideone {
    public static void main (String[] args) throws java.lang.Exception {
        System.out.println("Result: " + (-2147483648 * 42));
    }
}

Once it's zero, it of course stays zero. Here's some code that will produce a more accurate result (you can run the code here):

import java.math.BigInteger;

class Ideone {
    public static void main (String[] args) throws java.lang.Exception {
        BigInteger p = BigInteger.valueOf(1);
        BigInteger start = BigInteger.valueOf(10);
        BigInteger end = BigInteger.valueOf(99);
        for(BigInteger i = start; i.compareTo(end) < 0; i = i.add(BigInteger.ONE)){
            p = p.multiply(i);
            System.out.println("p: " + p);
        }
        System.out.println("\nProduct: " + p);
    }
}
Trevor
  • 13,085
  • 13
  • 76
  • 99
  • It overflows (in the precise sense of the word) well before the 42nd iteration -- at 19 it is already overflown, since f(19) < f(18) – user295691 Oct 15 '14 at 21:45
  • Yes, but the overflow doesn't lead to or result in a product of zero until the 42nd iteration. – Trevor Oct 15 '14 at 21:48
  • I guess what I'm getting at is that you don't address the "why" -- why would the cumulative product ever pass through 0? Tim S.'s answer gives some indication of why, but the real answer lies in modular arithmetic. – user295691 Oct 15 '14 at 21:50
  • The question doesn't ask why the product pass through zero. It asks why the code produces zero. In other words, I think the OP is more interested in the dynamics of the Java language than in modular arithmetic, but perhaps I'm wrong. It wouldn't be the first time I misinterpreted someone's question. – Trevor Oct 15 '14 at 21:54
  • for example, if this program had taken the product of all odd numbers from 11 to 99, then it would _not_ reach zero. Your answer does not really address why this would happen. – user295691 Oct 15 '14 at 21:54
  • No, it wouldn't reach zero. It would produce some equally confusing result, and eventually someone would post a question about that. Either way, they would come to understand that arithmetic overflow is at fault, and the practical solution is to not use `int`s for calculating such large numbers. If the OP wants a theoretical explanation of how a particular formula reaches zero, I suggest [Mathematics](http://math.stackexchange.com/). – Trevor Oct 15 '14 at 21:59
1

It is an integer overflow.

The int data type is 4 bytes, or 32 bits. Therefore, numbers larger than 2^(32 - 1) - 1 (2,147,483,647) cannot be stored in this data type. Your numerical values will be incorrect.

For very large numbers, you will want to import and use the class java.math.BigInteger:

BigInteger product = BigInteger.ONE;
for (long i = 10; i < 99; i++) 
    product = product.multiply(BigInteger.valueOf(i));
System.out.println(product.toString());

NOTE: For numerical values that are still too large for the int data type, but small enough to fit within 8 bytes (absolute value less than or equal to 2^(64 - 1) - 1), you should probably use the long primitive.

HackerRank's practice problems (www.hackerrank.com), such as the Algorithms practice section, (https://www.hackerrank.com/domains/algorithms/warmup) include some very good large-number questions that give good practice about how to think about the appropriate data type to use.

La-comadreja
  • 5,627
  • 11
  • 36
  • 64