Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java : large integer numbers error

I am trying to do the following math equation in Java:

(44334*(220*220))+ (81744*220) + 39416)

When I enter the same equation in WolframAlpha (or in Google) I get:

2163788696

In java I get negative number..

I have been struggling to find out why this is happening but with no luck. I also tried saving the answer in a BigInteger, but then I get negative values because the digits are too large.

What should I do?

like image 313
phedon rousou Avatar asked Jun 16 '26 08:06

phedon rousou


2 Answers

EDIT: To deal with the integer wrap-around, use a long:

System.out.println("Result: " +
    (44334L * 220 * 220 + 81744 * 220 + 39416));  // 2163788696

The plus operator is left-associative (whether it's being used for string concatenation or addition), so if the entire arithmetic expression weren't parenthesized, it would be concatenating the results of the sub-expressions as individual strings from left to right.

The left operand determines whether + is used for string concatenation or addition. In this case, the first operand is a string, so the right side ((44334*(220*220))) is converted into a string as well. The result of the first + operator is a string and is used as the left side of another + string concatenation operation. the next operand ((81744*220)) gets converted to a string again.

You can put parentheses around the entire arithmetic expression to avoid that.

like image 197
jspcal Avatar answered Jun 17 '26 22:06

jspcal


Right now, what you are doing is equivalent to:

System.out.println(("result="+(44334*220*220)) + (81744*220 + 39416) );
// = "result=2145765600" + 18023096
// = "result=214576560018023096"

Parentheses are important! Here is your code fixed:

System.out.println("result=" + (44334*220*220+ 81744*220 + 39416) );
// = "result=2163788696"

EDIT:

Also beware of automatic int casting. Use longs because your result is bigger than MAX_INT (but smaller than MAX_LONG which is 9223372036854775807).

(long)((long)44334*220*220 + (long)81744*220 + 39416)

Or put the suffix L after your numbers (so they're considered as longs).

like image 33
mbinette Avatar answered Jun 17 '26 22:06

mbinette



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!