I have found in documentation that range of long is from -2^63 to 2^63-1.
When I run this for cycle I'm unable to get over cca 2 000 000 000.
Log.d(TAG, "Long MAX = " + Long.MAX_VALUE);
for (int i = 1; i < 45; i++) {
long result = i * 184528125;
Log.d(TAG, "" + result);
}
Output is "Long MAX = 9223372036854775807" and result values in graph is below.
Sample Java project on codingground.com is here.
What am I missing?
The problem is this line:
long result = i * 184528125;
The right hand side is evaluated in 32-bit integer arithmetic, because both operands are int
. There's then an implicit conversion to long
. To fix it, just make the RHS a long
constant:
long result = i * 184528125L;
Note that this is similar to the common problem of doing something like:
int x = 1;
double d = x / 2; // d is 0, not 0.5...
See more on this question at Stackoverflow