+ 7

(int)Math.pow(x, y)

So I just made a code to explain something more about int data type that I find interesting. You can see it in my codes. I am a bit confused now. Why (int)Math.pow(2, 31) returns what it should be (2^31) -1 ? I mean if I write this: int x = (int)Math.pow(2, 31); print x. It prints (2^31) -1 instead of (2^31). I always thought that (2^31) - 1 is the biggest int. Am I missing something?

30th Nov 2016, 1:26 AM
R2-D2
R2-D2 - avatar
7 ответов
+ 8
int variables can only hold integer values up till 2,147,483,647 . If you do ' 2^31' the answer is 2,147,483,648. To prevent the system from crashing, the number was reduced to the max amount which the variable can hold. This is also one of the reason why database losses occur in websites, games, etc ,the variable used could not handle the large amount of numbers it was going to store.
30th Nov 2016, 1:57 AM
Wen Qin
Wen Qin - avatar
+ 7
@Samuel Neo Thank you for your answer it makes sense now! I did some extra searching with what you have said in mind. So if you want to typecast a double bigger than 2147483647 to an int it goes to the maximum value of the int data type. Because Math.pow(x, y) returns a double that' s what happens. However if you typecast another data type that is not a double (e.g. a long) to an int, it won' t do this, but some overflowing errors will occur. One mistake you made: the minimum value for int type is -2147483648 not -2147483647. Check my code for more insights about int data types.
30th Nov 2016, 3:51 PM
R2-D2
R2-D2 - avatar
+ 5
I don't think you are right. If you were then every time you try to have an int larger than 2,147,483,647 it would be reduced to the max but that's not the case! For example try to write int x = 2,147,483,647 + 1; and print it. It would print the min value.
30th Nov 2016, 2:05 AM
R2-D2
R2-D2 - avatar
+ 3
As far as I know, the reason why Math.pow(2, 31) and 2147483647 + 1 return different values is this: Math.pow(base, index) might not return an int. (Which is why you have to typecast it). When you typecast the value 2147483648 to an int, it goes to the maximum value of an int (that's what happens when you typecast it). 2147483647 + 1 returns -2147483647 because when you try to add 1 to maximum, it goes down all the way to the smallest (negative) value. (Which is why in certain games, if you increase something beyond 2147483647, it goes to -2147483647...)
30th Nov 2016, 2:43 AM
Samuel Neo
Samuel Neo - avatar
- 1
I don't know your question is confusing Or my English is weak. anyhow it will not print more than 1073741823...if you try to print more than it.it will print -1073741824 then -1073741823 and so on...
30th Nov 2016, 3:22 AM
somnath
somnath - avatar