This is because you multiply integers x * x , and the result of this will be integer (temporary variable, we are talking here about the result of the operation x * x , not res = ). Since the result will be larger than Integer.MAX_VALUE , you will get some "weird" number. Then you put this number in a variable of type long .
Here is how you fix this problem:
long res = 1l * x * x;
Now it will calculate 1l * x , and since the first number is long , it will calculate it as long , then multiply by x and again, since the first number is long , the result will be long , then this result will be placed in the res variable.
Similarly, you fix the decimal point problem, for example:
int a = 10; int b = 3; double d = a / b;
The result for this will be 3.0 . But if you do this:
double d = (1d *a) / b; d = a / (b * 1d); d = (double) a / d;
Both will be 3.3333333333333335 (this is 5 , well, this is another problem ...). Also, using casting for double for one of the variables also works (thanks @Aconcagua).
source share