RFR: 8355992: Add unsignedMultiplyExact and *powExact methods to Math and StrictMath [v2]
Shaojin Wen
swen at openjdk.org
Fri May 2 17:01:14 UTC 2025
On Fri, 2 May 2025 16:04:18 GMT, fabioromano1 <duke at openjdk.org> wrote:
>> Raffaello Giulietti has updated the pull request incrementally with one additional commit since the last revision:
>>
>> Clearer and more complete spec of the *pow* methods.
>
> src/java.base/share/classes/java/lang/Math.java line 3500:
>
>> 3498: return (n & 0b1) == 0 ? 1 : -1;
>> 3499: }
>> 3500:
>
> Suggestion:
>
>
> if (x == 2) {
> if (n >= Integer.SIZE - 1)
> throw new ArithmeticException("integer overflow");
> return 1 << n;
> }
> if (x == -2) {
> if (n >= Integer.SIZE)
> throw new ArithmeticException("integer overflow");
> // if n == Integer.SIZE - 1, result is correct
> return (n & 0b1) == 0 ? 1 << n : -(1 << n);
> }
>
> if ((java.math.BigInteger.bitLengthForInt(Math.abs(x)) - 1L) * n + 1L > Integer.SIZE) {
> throw new ArithmeticException("integer overflow");
> }
>
> With also a check for the condition `java.math.BigInteger.bitLengthForInt(Math.abs(x)) * n < Integer.SIZE`, when it is true the path could be led to a loop that skips the checks.
return (n & 0b1) == 0 ? 1 << n : -(1 << n);
Equivalent to
return ((1 << n) ^ -(n & 1)) + (n & 1);
Without branches it should be faster
-------------
PR Review Comment: https://git.openjdk.org/jdk/pull/25003#discussion_r2071898882
More information about the core-libs-dev
mailing list