Returns the b to the kth power, unless it would overflow or underflow in which case Integer.MAX_VALUE or Integer.MIN_VALUE is returned, respectively. @since 20.0
(int b, int k)
| 593 | */ |
| 594 | |
| 595 | @Beta |
| 596 | public static int saturatedPow(int b, int k) { |
| 597 | checkNonNegative("exponent", k); |
| 598 | switch (b) { |
| 599 | case 0: |
| 600 | return (k == 0) ? 1 : 0; |
| 601 | case 1: |
| 602 | return 1; |
| 603 | case (-1): |
| 604 | return ((k & 1) == 0) ? 1 : -1; |
| 605 | case 2: |
| 606 | if (k >= Integer.SIZE - 1) { |
| 607 | return Integer.MAX_VALUE; |
| 608 | } |
| 609 | return 1 << k; |
| 610 | case (-2): |
| 611 | if (k >= Integer.SIZE) { |
| 612 | return Integer.MAX_VALUE + (k & 1); |
| 613 | } |
| 614 | return ((k & 1) == 0) ? 1 << k : -1 << k; |
| 615 | default: |
| 616 | // continue below to handle the general case |
| 617 | |
| 618 | } |
| 619 | |
| 620 | int accum = 1; |
| 621 | // if b is negative and k is odd then the limit is MIN otherwise the limit is MAX |
| 622 | int limit = Integer.MAX_VALUE + ((b >>> Integer.SIZE - 1) & (k & 1)); |
| 623 | while (true) { |
| 624 | switch (k) { |
| 625 | case 0: |
| 626 | return accum; |
| 627 | case 1: |
| 628 | return saturatedMultiply(accum, b); |
| 629 | default: |
| 630 | if ((k & 1) != 0) { |
| 631 | accum = saturatedMultiply(accum, b); |
| 632 | } |
| 633 | k >>= 1; |
| 634 | if (k > 0) { |
| 635 | if (-FLOOR_SQRT_MAX_INT > b | b > FLOOR_SQRT_MAX_INT) { |
| 636 | return limit; |
| 637 | } |
| 638 | b *= b; |
| 639 | } |
| 640 | } |
| 641 | } |
| 642 | } |
| 643 | |
| 644 | @VisibleForTesting |
| 645 | static final int FLOOR_SQRT_MAX_INT = 46340; |
nothing calls this directly
no test coverage detected