+ 1

Can someone help me with this code?

This code prints "2 4 16 256 65536" and then just a bunch of 0. And I dunno why. Can someone tell me the reason? https://code.sololearn.com/cDy6Yy8Tiyok/?ref=app

5th Oct 2017, 2:28 AM
PaĂșl Morimoto
PaĂșl Morimoto - avatar
8 Answers
+ 7
What you've observed is known as integer overflow. It happens when the no of bits required to represent the number exceeds its memory space. Let's say we have a 2-bit number, so: 0 0 0 1 1 0 1 1 The number after 11 would be 00 (the leading 1 overflows) since we can't have 100 as it requires 3-bit. Integer is 32-bit by default and I hope you get the idea. 😉
5th Oct 2017, 3:24 AM
Zephyr Koo
Zephyr Koo - avatar
+ 4
I believe it's because Java's integer value limit, which is the 32 bit integer limit, 2,147,483,647. 65536 squared is 2 ** 32, which is higher than 2,147,483,647. :D
5th Oct 2017, 2:38 AM
LunarCoffee
LunarCoffee - avatar
+ 3
There is a very painful work around but it is not suitable for more than one value at a time. Google unsigned integer in java. Java hurt my feelings with that one.
5th Oct 2017, 3:18 AM
Dark Angel
Dark Angel - avatar
+ 3
quoting Andrew G Change, "int" to "long" and it shows then next answer but the rest are all 0's, then I tested changing "int" to "double" and it worked but it gave me decimal form so, 4,294,967,296 was shown as 4.294967296 end quote Try bigDecimal.
5th Oct 2017, 3:30 AM
Dark Angel
Dark Angel - avatar
0
Try this: import java.math.BigInteger; public class Program { public static void main(String[] args) { for(BigInteger x = BigInteger.valueOf(2); (x.toString()).length() < Integer.MAX_VALUE; x = x.multiply(x)) { System.out.println(x.toString()); } } } Code Playground may time out before Integer.MAX_VALUE is reached.
5th Oct 2017, 5:31 AM
ChaoticDawg
ChaoticDawg - avatar
0
Thanks to everyone :D
5th Oct 2017, 7:21 AM
PaĂșl Morimoto
PaĂșl Morimoto - avatar