Returns b to the kth power. Even if the result overflows, it will be equal to BigInteger.valueOf(b).pow(k).intValue(). This implementation runs in O(log k) time. Compare #checkedPow, which throws an ArithmeticException upon overflow. @throws Illeg
(int b, int k)
| 233 | */ |
| 234 | |
| 235 | @GwtIncompatible // failing tests |
| 236 | public static int pow(int b, int k) { |
| 237 | checkNonNegative("exponent", k); |
| 238 | switch (b) { |
| 239 | case 0: |
| 240 | return (k == 0) ? 1 : 0; |
| 241 | case 1: |
| 242 | return 1; |
| 243 | case (-1): |
| 244 | return ((k & 1) == 0) ? 1 : -1; |
| 245 | case 2: |
| 246 | return (k < Integer.SIZE) ? (1 << k) : 0; |
| 247 | case (-2): |
| 248 | if (k < Integer.SIZE) { |
| 249 | return ((k & 1) == 0) ? (1 << k) : - (1 << k); |
| 250 | } else { |
| 251 | return 0; |
| 252 | } |
| 253 | |
| 254 | default: |
| 255 | // continue below to handle the general case |
| 256 | |
| 257 | } |
| 258 | for (int accum = 1; ; k >>= 1) { |
| 259 | switch (k) { |
| 260 | case 0: |
| 261 | return accum; |
| 262 | case 1: |
| 263 | return b * accum; |
| 264 | default: |
| 265 | accum *= ((k & 1) == 0) ? 1 : b; |
| 266 | b *= b; |
| 267 | } |
| 268 | } |
| 269 | } |
| 270 | |
| 271 | /** |
| 272 | * Returns the square root of {@code x}, rounded with the specified rounding mode. |
no test coverage detected