Returns dividend % divisor, where the dividend and divisor are treated as unsigned 64-bit quantities. @param dividend the dividend (numerator) @param divisor the divisor (denominator) @throws ArithmeticException if divisor is 0 @since 11.0
(long dividend, long divisor)
| 234 | |
| 235 | |
| 236 | public static long remainder(long dividend, long divisor) { |
| 237 | if (divisor < 0) { // i.e., divisor >= 2^63: |
| 238 | if (compare(dividend, divisor) < 0) { |
| 239 | return dividend; // dividend < divisor |
| 240 | } else { |
| 241 | return dividend - divisor; // dividend >= divisor |
| 242 | } |
| 243 | } |
| 244 | |
| 245 | // Optimization - use signed modulus if dividend < 2^63 |
| 246 | if (dividend >= 0) { |
| 247 | return dividend % divisor; |
| 248 | } |
| 249 | |
| 250 | /* |
| 251 | * Otherwise, approximate the quotient, check, and correct if necessary. Our approximation is |
| 252 | * guaranteed to be either exact or one less than the correct value. This follows from fact that |
| 253 | * floor(floor(x)/i) == floor(x/i) for any real x and integer i != 0. The proof is not quite |
| 254 | * trivial. |
| 255 | */ |
| 256 | |
| 257 | long quotient = ((dividend >>> 1) / divisor) << 1; |
| 258 | long rem = dividend - quotient * divisor; |
| 259 | return rem - (compare(rem, divisor) >= 0 ? divisor : 0); |
| 260 | } |
| 261 | |
| 262 | /** |
| 263 | * Returns the unsigned {@code long} value represented by the given decimal string. |
no test coverage detected