arithmetic: companion code for the Add Two Numbers Without Overflow post
Silent int/long overflow reproduced with real numbers, the Math *Exact() family (addExact/subtractExact/multiplyExact/incrementExact/decrementExact/ negateExact/toIntExact/absExact) with the abs(MIN_VALUE) trap absExact exists to catch, widening to long vs BigInteger, and the XOR-based overflow bit trick Math.addExact uses internally, cross-checked against BigInteger ground truth over 100k random int pairs per JUnit repeat. Co-Authored-By: Claude Sonnet 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01FhzLY5p6okFva3qsnsRyvM
This commit is contained in:
@@ -0,0 +1,24 @@
|
||||
$ java ExactArithmeticDemo
|
||||
|
||||
=== addExact / subtractExact / multiplyExact: normal case ===
|
||||
Math.addExact(20, 22) = 42
|
||||
Math.subtractExact(50, 8) = 42
|
||||
Math.multiplyExact(6, 7) = 42
|
||||
|
||||
=== addExact / multiplyExact: overflow case - throws instead of wrapping ===
|
||||
Math.addExact(Integer.MAX_VALUE, 1) threw: integer overflow
|
||||
Math.multiplyExact(100000, 100000) threw: integer overflow
|
||||
|
||||
=== incrementExact / decrementExact / negateExact ===
|
||||
Math.incrementExact(41) = 42
|
||||
Math.decrementExact(43) = 42
|
||||
Math.negateExact(-42) = 42
|
||||
Math.incrementExact(Integer.MAX_VALUE) threw: integer overflow
|
||||
|
||||
=== toIntExact: the safe narrowing cast from long back to int ===
|
||||
Math.toIntExact(2000000000L) = 2000000000
|
||||
Math.toIntExact(3000000000L) threw: integer overflow
|
||||
|
||||
=== The classic trap: Math.abs(Integer.MIN_VALUE) does NOT throw, and is wrong ===
|
||||
Math.abs(Integer.MIN_VALUE) = -2147483648 (still negative! +2147483648 doesn't fit in an int)
|
||||
Math.absExact(Integer.MIN_VALUE) threw: Overflow to represent absolute value of Integer.MIN_VALUE
|
||||
Reference in New Issue
Block a user