You have overflowed the size of a 32-bit integer.
Consider what happens when I equal 10:
sum = sum + 100000000000 //1 with 11 zeroes
But the maximum positive number that can be stored in a 32-bit integer is only about 2 billion (2 with nine zeros).
This is actually getting worse! Intermediate calculations will be performed with limited accuracy, and as soon as the multiplication 10 * 10 * 10 * 10 ... overflows, then 10s will be multiplied by a strange negative number and will already be erroneous.
Thus, the number you end up with is not like any arithmetic rules, but it actually makes sense if you know that primitive integers have limited storage.
The solution is to use the 64-bit long and I hope that you do not overflow THAT too, if you do, you will need BigInteger .
source share