RFR: 8355992: Add unsignedMultiplyExact and *powExact methods to Math and StrictMath [v2]
fabioromano1
duke at openjdk.org
Fri May 2 17:57:47 UTC 2025
On Fri, 2 May 2025 16:57:43 GMT, Shaojin Wen <swen at openjdk.org> wrote:
>> 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
> ```java
> return ((1 << n) ^ -(n & 1)) + (n & 1);
> ```
It should have a comment that explains that this does the two's complement if `n` is odd, and it does nothing otherwise. Anyway, probably the optimization for `x == -2` will not be included.
-------------
PR Review Comment: https://git.openjdk.org/jdk/pull/25003#discussion_r2071960548
More information about the core-libs-dev
mailing list