Returns the square root of x, rounded with the specified rounding mode. @throws IllegalArgumentException if x < 0 @throws ArithmeticException if mode is RoundingMode#UNNECESSARY and sqrt(x) is not an integer
(int x, RoundingMode mode)
| 272 | */ |
| 273 | |
| 274 | @GwtIncompatible // need BigIntegerMath to adequately test |
| 275 | @SuppressWarnings("fallthrough") |
| 276 | public static int sqrt(int x, RoundingMode mode) { |
| 277 | checkNonNegative("x", x); |
| 278 | int sqrtFloor = sqrtFloor(x); |
| 279 | switch (mode) { |
| 280 | case UNNECESSARY: |
| 281 | checkRoundingUnnecessary(sqrtFloor * sqrtFloor == x); // fall through |
| 282 | case FLOOR: |
| 283 | case DOWN: |
| 284 | return sqrtFloor; |
| 285 | case CEILING: |
| 286 | case UP: |
| 287 | return sqrtFloor + lessThanBranchFree(sqrtFloor * sqrtFloor, x); |
| 288 | case HALF_DOWN: |
| 289 | case HALF_UP: |
| 290 | case HALF_EVEN: |
| 291 | int halfSquare = sqrtFloor * sqrtFloor + sqrtFloor; |
| 292 | /* |
| 293 | * We wish to test whether or not x <= (sqrtFloor + 0.5)^2 = halfSquare + 0.25. Since both x |
| 294 | * and halfSquare are integers, this is equivalent to testing whether or not x <= |
| 295 | * halfSquare. (We have to deal with overflow, though.) |
| 296 | * |
| 297 | * If we treat halfSquare as an unsigned int, we know that |
| 298 | * sqrtFloor^2 <= x < (sqrtFloor + 1)^2 |
| 299 | * halfSquare - sqrtFloor <= x < halfSquare + sqrtFloor + 1 |
| 300 | * so |x - halfSquare| <= sqrtFloor. Therefore, it's safe to treat x - halfSquare as a |
| 301 | * signed int, so lessThanBranchFree is safe for use. |
| 302 | */ |
| 303 | return sqrtFloor + lessThanBranchFree(halfSquare, x); |
| 304 | default: |
| 305 | throw new AssertionError(); |
| 306 | } |
| 307 | } |
| 308 | |
| 309 | private static int sqrtFloor(int x) { |
| 310 | // There is no loss of precision in converting an int to a double, according to |
no test coverage detected