001/*
002 * Copyright (C) 2011 The Guava Authors
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
005 * in compliance with the License. You may obtain a copy of the License at
006 *
007 * http://www.apache.org/licenses/LICENSE-2.0
008 *
009 * Unless required by applicable law or agreed to in writing, software distributed under the License
010 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
011 * or implied. See the License for the specific language governing permissions and limitations under
012 * the License.
013 */
014
015package com.google.common.math;
016
017import static com.google.common.base.Preconditions.checkArgument;
018import static com.google.common.base.Preconditions.checkNotNull;
019import static com.google.common.math.MathPreconditions.checkNoOverflow;
020import static com.google.common.math.MathPreconditions.checkNonNegative;
021import static com.google.common.math.MathPreconditions.checkPositive;
022import static com.google.common.math.MathPreconditions.checkRoundingUnnecessary;
023import static java.lang.Math.abs;
024import static java.lang.Math.ceil;
025import static java.lang.Math.floor;
026import static java.lang.Math.min;
027import static java.lang.Math.nextDown;
028import static java.lang.Math.nextUp;
029import static java.math.RoundingMode.HALF_EVEN;
030import static java.math.RoundingMode.HALF_UP;
031
032import com.google.common.annotations.GwtCompatible;
033import com.google.common.annotations.GwtIncompatible;
034import com.google.common.annotations.VisibleForTesting;
035import com.google.common.primitives.UnsignedLongs;
036import com.google.errorprone.annotations.InlineMe;
037import java.math.BigInteger;
038import java.math.RoundingMode;
039
040/**
041 * A class for arithmetic on values of type {@code long}. Where possible, methods are defined and
042 * named analogously to their {@code BigInteger} counterparts.
043 *
044 * <p>The implementations of many methods in this class are based on material from Henry S. Warren,
045 * Jr.'s <i>Hacker's Delight</i>, (Addison Wesley, 2002).
046 *
047 * <p>Similar functionality for {@code int} and for {@link BigInteger} can be found in {@link
048 * IntMath} and {@link BigIntegerMath} respectively. For other common operations on {@code long}
049 * values, see {@link com.google.common.primitives.Longs}.
050 *
051 * @author Louis Wasserman
052 * @since 11.0
053 */
054@GwtCompatible
055public final class LongMath {
056  @VisibleForTesting static final long MAX_SIGNED_POWER_OF_TWO = 1L << (Long.SIZE - 2);
057
058  /**
059   * Returns the smallest power of two greater than or equal to {@code x}. This is equivalent to
060   * {@code checkedPow(2, log2(x, CEILING))}.
061   *
062   * @throws IllegalArgumentException if {@code x <= 0}
063   * @throws ArithmeticException of the next-higher power of two is not representable as a {@code
064   *     long}, i.e. when {@code x > 2^62}
065   * @since 20.0
066   */
067  public static long ceilingPowerOfTwo(long x) {
068    checkPositive("x", x);
069    if (x > MAX_SIGNED_POWER_OF_TWO) {
070      throw new ArithmeticException("ceilingPowerOfTwo(" + x + ") is not representable as a long");
071    }
072    return 1L << -Long.numberOfLeadingZeros(x - 1);
073  }
074
075  /**
076   * Returns the largest power of two less than or equal to {@code x}. This is equivalent to {@code
077   * checkedPow(2, log2(x, FLOOR))}.
078   *
079   * @throws IllegalArgumentException if {@code x <= 0}
080   * @since 20.0
081   */
082  public static long floorPowerOfTwo(long x) {
083    checkPositive("x", x);
084
085    // Long.highestOneBit was buggy on GWT.  We've fixed it, but I'm not certain when the fix will
086    // be released.
087    return 1L << ((Long.SIZE - 1) - Long.numberOfLeadingZeros(x));
088  }
089
090  /**
091   * Returns {@code true} if {@code x} represents a power of two.
092   *
093   * <p>This differs from {@code Long.bitCount(x) == 1}, because {@code
094   * Long.bitCount(Long.MIN_VALUE) == 1}, but {@link Long#MIN_VALUE} is not a power of two.
095   */
096  // Whenever both tests are cheap and functional, it's faster to use &, | instead of &&, ||
097  @SuppressWarnings("ShortCircuitBoolean")
098  public static boolean isPowerOfTwo(long x) {
099    return x > 0 & (x & (x - 1)) == 0;
100  }
101
102  /**
103   * Returns 1 if {@code x < y} as unsigned longs, and 0 otherwise. Assumes that x - y fits into a
104   * signed long. The implementation is branch-free, and benchmarks suggest it is measurably faster
105   * than the straightforward ternary expression.
106   */
107  @VisibleForTesting
108  static int lessThanBranchFree(long x, long y) {
109    // The double negation is optimized away by normal Java, but is necessary for GWT
110    // to make sure bit twiddling works as expected.
111    return (int) (~~(x - y) >>> (Long.SIZE - 1));
112  }
113
114  /**
115   * Returns the base-2 logarithm of {@code x}, rounded according to the specified rounding mode.
116   *
117   * @throws IllegalArgumentException if {@code x <= 0}
118   * @throws ArithmeticException if {@code mode} is {@link RoundingMode#UNNECESSARY} and {@code x}
119   *     is not a power of two
120   */
121  @SuppressWarnings("fallthrough")
122  // TODO(kevinb): remove after this warning is disabled globally
123  public static int log2(long x, RoundingMode mode) {
124    checkPositive("x", x);
125    switch (mode) {
126      case UNNECESSARY:
127        checkRoundingUnnecessary(isPowerOfTwo(x));
128      // fall through
129      case DOWN:
130      case FLOOR:
131        return (Long.SIZE - 1) - Long.numberOfLeadingZeros(x);
132
133      case UP:
134      case CEILING:
135        return Long.SIZE - Long.numberOfLeadingZeros(x - 1);
136
137      case HALF_DOWN:
138      case HALF_UP:
139      case HALF_EVEN:
140        // Since sqrt(2) is irrational, log2(x) - logFloor cannot be exactly 0.5
141        int leadingZeros = Long.numberOfLeadingZeros(x);
142        long cmp = MAX_POWER_OF_SQRT2_UNSIGNED >>> leadingZeros;
143        // floor(2^(logFloor + 0.5))
144        int logFloor = (Long.SIZE - 1) - leadingZeros;
145        return logFloor + lessThanBranchFree(cmp, x);
146    }
147    throw new AssertionError("impossible");
148  }
149
150  /** The biggest half power of two that fits into an unsigned long */
151  @VisibleForTesting static final long MAX_POWER_OF_SQRT2_UNSIGNED = 0xB504F333F9DE6484L;
152
153  /**
154   * Returns the base-10 logarithm of {@code x}, rounded according to the specified rounding mode.
155   *
156   * @throws IllegalArgumentException if {@code x <= 0}
157   * @throws ArithmeticException if {@code mode} is {@link RoundingMode#UNNECESSARY} and {@code x}
158   *     is not a power of ten
159   */
160  @GwtIncompatible // TODO
161  @SuppressWarnings("fallthrough")
162  // TODO(kevinb): remove after this warning is disabled globally
163  public static int log10(long x, RoundingMode mode) {
164    checkPositive("x", x);
165    int logFloor = log10Floor(x);
166    long floorPow = powersOf10[logFloor];
167    switch (mode) {
168      case UNNECESSARY:
169        checkRoundingUnnecessary(x == floorPow);
170      // fall through
171      case FLOOR:
172      case DOWN:
173        return logFloor;
174      case CEILING:
175      case UP:
176        return logFloor + lessThanBranchFree(floorPow, x);
177      case HALF_DOWN:
178      case HALF_UP:
179      case HALF_EVEN:
180        // sqrt(10) is irrational, so log10(x)-logFloor is never exactly 0.5
181        return logFloor + lessThanBranchFree(halfPowersOf10[logFloor], x);
182    }
183    throw new AssertionError();
184  }
185
186  @GwtIncompatible // TODO
187  static int log10Floor(long x) {
188    /*
189     * Based on Hacker's Delight Fig. 11-5, the two-table-lookup, branch-free implementation.
190     *
191     * The key idea is that based on the number of leading zeros (equivalently, floor(log2(x))), we
192     * can narrow the possible floor(log10(x)) values to two. For example, if floor(log2(x)) is 6,
193     * then 64 <= x < 128, so floor(log10(x)) is either 1 or 2.
194     */
195    int y = maxLog10ForLeadingZeros[Long.numberOfLeadingZeros(x)];
196    /*
197     * y is the higher of the two possible values of floor(log10(x)). If x < 10^y, then we want the
198     * lower of the two possible values, or y - 1, otherwise, we want y.
199     */
200    return y - lessThanBranchFree(x, powersOf10[y]);
201  }
202
203  // maxLog10ForLeadingZeros[i] == floor(log10(2^(Long.SIZE - i)))
204  @VisibleForTesting
205  static final byte[] maxLog10ForLeadingZeros = {
206    19, 18, 18, 18, 18, 17, 17, 17, 16, 16, 16, 15, 15, 15, 15, 14, 14, 14, 13, 13, 13, 12, 12, 12,
207    12, 11, 11, 11, 10, 10, 10, 9, 9, 9, 9, 8, 8, 8, 7, 7, 7, 6, 6, 6, 6, 5, 5, 5, 4, 4, 4, 3, 3, 3,
208    3, 2, 2, 2, 1, 1, 1, 0, 0, 0
209  };
210
211  @GwtIncompatible // TODO
212  @VisibleForTesting
213  static final long[] powersOf10 = {
214    1L,
215    10L,
216    100L,
217    1000L,
218    10000L,
219    100000L,
220    1000000L,
221    10000000L,
222    100000000L,
223    1000000000L,
224    10000000000L,
225    100000000000L,
226    1000000000000L,
227    10000000000000L,
228    100000000000000L,
229    1000000000000000L,
230    10000000000000000L,
231    100000000000000000L,
232    1000000000000000000L
233  };
234
235  // halfPowersOf10[i] = largest long less than 10^(i + 0.5)
236  @GwtIncompatible // TODO
237  @VisibleForTesting
238  static final long[] halfPowersOf10 = {
239    3L,
240    31L,
241    316L,
242    3162L,
243    31622L,
244    316227L,
245    3162277L,
246    31622776L,
247    316227766L,
248    3162277660L,
249    31622776601L,
250    316227766016L,
251    3162277660168L,
252    31622776601683L,
253    316227766016837L,
254    3162277660168379L,
255    31622776601683793L,
256    316227766016837933L,
257    3162277660168379331L
258  };
259
260  /**
261   * Returns {@code b} to the {@code k}th power. Even if the result overflows, it will be equal to
262   * {@code BigInteger.valueOf(b).pow(k).longValue()}. This implementation runs in {@code O(log k)}
263   * time.
264   *
265   * @throws IllegalArgumentException if {@code k < 0}
266   */
267  @GwtIncompatible // TODO
268  public static long pow(long b, int k) {
269    checkNonNegative("exponent", k);
270    if (-2 <= b && b <= 2) {
271      switch ((int) b) {
272        case 0:
273          return (k == 0) ? 1 : 0;
274        case 1:
275          return 1;
276        case -1:
277          return ((k & 1) == 0) ? 1 : -1;
278        case 2:
279          return (k < Long.SIZE) ? 1L << k : 0;
280        case -2:
281          if (k < Long.SIZE) {
282            return ((k & 1) == 0) ? 1L << k : -(1L << k);
283          } else {
284            return 0;
285          }
286        default:
287          throw new AssertionError();
288      }
289    }
290    for (long accum = 1; ; k >>= 1) {
291      switch (k) {
292        case 0:
293          return accum;
294        case 1:
295          return accum * b;
296        default:
297          accum *= ((k & 1) == 0) ? 1 : b;
298          b *= b;
299      }
300    }
301  }
302
303  /**
304   * Returns the square root of {@code x}, rounded with the specified rounding mode.
305   *
306   * @throws IllegalArgumentException if {@code x < 0}
307   * @throws ArithmeticException if {@code mode} is {@link RoundingMode#UNNECESSARY} and {@code
308   *     sqrt(x)} is not an integer
309   */
310  @GwtIncompatible // TODO
311  public static long sqrt(long x, RoundingMode mode) {
312    checkNonNegative("x", x);
313    if (fitsInInt(x)) {
314      return IntMath.sqrt((int) x, mode);
315    }
316    /*
317     * Let k be the true value of floor(sqrt(x)), so that
318     *
319     *            k * k <= x          <  (k + 1) * (k + 1)
320     * (double) (k * k) <= (double) x <= (double) ((k + 1) * (k + 1))
321     *          since casting to double is nondecreasing.
322     *          Note that the right-hand inequality is no longer strict.
323     * Math.sqrt(k * k) <= Math.sqrt(x) <= Math.sqrt((k + 1) * (k + 1))
324     *          since Math.sqrt is monotonic.
325     * (long) Math.sqrt(k * k) <= (long) Math.sqrt(x) <= (long) Math.sqrt((k + 1) * (k + 1))
326     *          since casting to long is monotonic
327     * k <= (long) Math.sqrt(x) <= k + 1
328     *          since (long) Math.sqrt(k * k) == k, as checked exhaustively in
329     *          {@link LongMathTest#testSqrtOfPerfectSquareAsDoubleIsPerfect}
330     */
331    long guess = (long) Math.sqrt((double) x);
332    // Note: guess is always <= FLOOR_SQRT_MAX_LONG.
333    long guessSquared = guess * guess;
334    // Note (2013-2-26): benchmarks indicate that, inscrutably enough, using if statements is
335    // faster here than using lessThanBranchFree.
336    switch (mode) {
337      case UNNECESSARY:
338        checkRoundingUnnecessary(guessSquared == x);
339        return guess;
340      case FLOOR:
341      case DOWN:
342        if (x < guessSquared) {
343          return guess - 1;
344        }
345        return guess;
346      case CEILING:
347      case UP:
348        if (x > guessSquared) {
349          return guess + 1;
350        }
351        return guess;
352      case HALF_DOWN:
353      case HALF_UP:
354      case HALF_EVEN:
355        long sqrtFloor = guess - ((x < guessSquared) ? 1 : 0);
356        long halfSquare = sqrtFloor * sqrtFloor + sqrtFloor;
357        /*
358         * We wish to test whether or not x <= (sqrtFloor + 0.5)^2 = halfSquare + 0.25. Since both x
359         * and halfSquare are integers, this is equivalent to testing whether or not x <=
360         * halfSquare. (We have to deal with overflow, though.)
361         *
362         * If we treat halfSquare as an unsigned long, we know that
363         *            sqrtFloor^2 <= x < (sqrtFloor + 1)^2
364         * halfSquare - sqrtFloor <= x < halfSquare + sqrtFloor + 1
365         * so |x - halfSquare| <= sqrtFloor.  Therefore, it's safe to treat x - halfSquare as a
366         * signed long, so lessThanBranchFree is safe for use.
367         */
368        return sqrtFloor + lessThanBranchFree(halfSquare, x);
369    }
370    throw new AssertionError();
371  }
372
373  /**
374   * Returns the result of dividing {@code p} by {@code q}, rounding using the specified {@code
375   * RoundingMode}. If the {@code RoundingMode} is {@link RoundingMode#DOWN}, then this method is
376   * equivalent to regular Java division, {@code p / q}; and if it is {@link RoundingMode#FLOOR},
377   * then this method is equivalent to {@link Math#floorDiv(long,long) Math.floorDiv}{@code (p, q)}.
378   *
379   * @throws ArithmeticException if {@code q == 0}, or if {@code mode == UNNECESSARY} and {@code a}
380   *     is not an integer multiple of {@code b}
381   */
382  @GwtIncompatible // TODO
383  @SuppressWarnings("fallthrough")
384  public static long divide(long p, long q, RoundingMode mode) {
385    checkNotNull(mode);
386    long div = p / q; // throws if q == 0
387    long rem = p - q * div; // equals p % q
388
389    if (rem == 0) {
390      return div;
391    }
392
393    /*
394     * Normal Java division rounds towards 0, consistently with RoundingMode.DOWN. We just have to
395     * deal with the cases where rounding towards 0 is wrong, which typically depends on the sign of
396     * p / q.
397     *
398     * signum is 1 if p and q are both nonnegative or both negative, and -1 otherwise.
399     */
400    int signum = 1 | (int) ((p ^ q) >> (Long.SIZE - 1));
401    boolean increment;
402    switch (mode) {
403      case UNNECESSARY:
404        checkRoundingUnnecessary(rem == 0);
405      // fall through
406      case DOWN:
407        increment = false;
408        break;
409      case UP:
410        increment = true;
411        break;
412      case CEILING:
413        increment = signum > 0;
414        break;
415      case FLOOR:
416        increment = signum < 0;
417        break;
418      case HALF_EVEN:
419      case HALF_DOWN:
420      case HALF_UP:
421        long absRem = abs(rem);
422        long cmpRemToHalfDivisor = absRem - (abs(q) - absRem);
423        // subtracting two nonnegative longs can't overflow
424        // cmpRemToHalfDivisor has the same sign as compare(abs(rem), abs(q) / 2).
425        if (cmpRemToHalfDivisor == 0) { // exactly on the half mark
426          increment = (mode == HALF_UP || (mode == HALF_EVEN && (div & 1) != 0));
427        } else {
428          increment = cmpRemToHalfDivisor > 0; // closer to the UP value
429        }
430        break;
431      default:
432        throw new AssertionError();
433    }
434    return increment ? div + signum : div;
435  }
436
437  /**
438   * Returns {@code x mod m}, a non-negative value less than {@code m}. This differs from {@code x %
439   * m}, which might be negative.
440   *
441   * <p>For example:
442   *
443   * {@snippet :
444   * mod(7, 4) == 3
445   * mod(-7, 4) == 1
446   * mod(-1, 4) == 3
447   * mod(-8, 4) == 0
448   * mod(8, 4) == 0
449   * }
450   *
451   * @throws ArithmeticException if {@code m <= 0}
452   * @see <a href="https://docs.oracle.com/javase/specs/jls/se26/html/jls-15.html#jls-15.17.3">
453   *     Remainder Operator</a>
454   */
455  @GwtIncompatible // TODO
456  public static int mod(long x, int m) {
457    // Cast is safe because the result is guaranteed in the range [0, m)
458    return (int) mod(x, (long) m);
459  }
460
461  /**
462   * Returns {@code x mod m}, a non-negative value less than {@code m}. This differs from {@code x %
463   * m}, which might be negative.
464   *
465   * <p>For example:
466   *
467   * {@snippet :
468   * mod(7, 4) == 3
469   * mod(-7, 4) == 1
470   * mod(-1, 4) == 3
471   * mod(-8, 4) == 0
472   * mod(8, 4) == 0
473   * }
474   *
475   * @throws ArithmeticException if {@code m <= 0}
476   * @see <a href="https://docs.oracle.com/javase/specs/jls/se26/html/jls-15.html#jls-15.17.3">
477   *     Remainder Operator</a>
478   */
479  @GwtIncompatible // TODO
480  public static long mod(long x, long m) {
481    if (m <= 0) {
482      throw new ArithmeticException("Modulus must be positive");
483    }
484    return Math.floorMod(x, m);
485  }
486
487  /**
488   * Returns the greatest common divisor of {@code a, b}. Returns {@code 0} if {@code a == 0 && b ==
489   * 0}.
490   *
491   * @throws IllegalArgumentException if {@code a < 0} or {@code b < 0}
492   */
493  public static long gcd(long a, long b) {
494    /*
495     * The reason we require both arguments to be >= 0 is because otherwise, what do you return on
496     * gcd(0, Long.MIN_VALUE)? BigInteger.gcd would return positive 2^63, but positive 2^63 isn't an
497     * int.
498     */
499    checkNonNegative("a", a);
500    checkNonNegative("b", b);
501    if (a == 0) {
502      // 0 % b == 0, so b divides a, but the converse doesn't hold.
503      // BigInteger.gcd is consistent with this decision.
504      return b;
505    } else if (b == 0) {
506      return a; // similar logic
507    }
508    /*
509     * Uses the binary GCD algorithm; see http://en.wikipedia.org/wiki/Binary_GCD_algorithm. This is
510     * >60% faster than the Euclidean algorithm in benchmarks.
511     */
512    int aTwos = Long.numberOfTrailingZeros(a);
513    a >>= aTwos; // divide out all 2s
514    int bTwos = Long.numberOfTrailingZeros(b);
515    b >>= bTwos; // divide out all 2s
516    while (a != b) { // both a, b are odd
517      // The key to the binary GCD algorithm is as follows:
518      // Both a and b are odd. Assume a > b; then gcd(a - b, b) = gcd(a, b).
519      // But in gcd(a - b, b), a - b is even and b is odd, so we can divide out powers of two.
520
521      // We bend over backwards to avoid branching, adapting a technique from
522      // http://graphics.stanford.edu/~seander/bithacks.html#IntegerMinOrMax
523
524      long delta = a - b; // can't overflow, since a and b are nonnegative
525
526      long minDeltaOrZero = delta & (delta >> (Long.SIZE - 1));
527      // equivalent to Math.min(delta, 0)
528
529      a = delta - minDeltaOrZero - minDeltaOrZero; // sets a to Math.abs(a - b)
530      // a is now nonnegative and even
531
532      b += minDeltaOrZero; // sets b to min(old a, b)
533      a >>= Long.numberOfTrailingZeros(a); // divide out all 2s, since 2 doesn't divide b
534    }
535    return a << min(aTwos, bTwos);
536  }
537
538  /**
539   * Returns the sum of {@code a} and {@code b}, provided it does not overflow.
540   *
541   * <p><b>Note:</b> this method is now unnecessary and should be treated as deprecated; use {@link
542   * Math#addExact(long, long)} instead. Note that if both arguments are {@code int} values, writing
543   * {@code Math.addExact(a, b)} will call the {@link Math#addExact(int, int)} overload, not {@link
544   * Math#addExact(long, long)}. Also note that adding two {@code int} values can <b>never</b>
545   * overflow a {@code long}, so you can just write {@code (long) a + b}.
546   *
547   * @throws ArithmeticException if {@code a + b} overflows in signed {@code long} arithmetic
548   */
549  @InlineMe(replacement = "Math.addExact(a, b)")
550  public static long checkedAdd(long a, long b) {
551    return Math.addExact(a, b);
552  }
553
554  /**
555   * Returns the difference of {@code a} and {@code b}, provided it does not overflow.
556   *
557   * <p><b>Note:</b> this method is now unnecessary and should be treated as deprecated; use {@link
558   * Math#subtractExact(long, long)} instead. Note that if both arguments are {@code int} values,
559   * writing {@code Math.subtractExact(a, b)} will call the {@link Math#subtractExact(int, int)}
560   * overload, not {@link Math#subtractExact(long, long)}. Also note that subtracting two {@code
561   * int} values can <b>never</b> overflow a {@code long}, so you can just write {@code (long) a -
562   * b}.
563   *
564   * @throws ArithmeticException if {@code a - b} overflows in signed {@code long} arithmetic
565   */
566  @InlineMe(replacement = "Math.subtractExact(a, b)")
567  public static long checkedSubtract(long a, long b) {
568    return Math.subtractExact(a, b);
569  }
570
571  /**
572   * Returns the product of {@code a} and {@code b}, provided it does not overflow.
573   *
574   * <p><b>Note:</b> this method is now unnecessary and should be treated as deprecated; use {@link
575   * Math#multiplyExact(long, long)} instead. Note that if both arguments are {@code int} values,
576   * writing {@code Math.multiplyExact(a, b)} will call the {@link Math#multiplyExact(int, int)}
577   * overload, not {@link Math#multiplyExact(long, long)}. Also note that multiplying two {@code
578   * int} values can <b>never</b> overflow a {@code long}, so you can just write {@code (long) a *
579   * b}.
580   *
581   * @throws ArithmeticException if {@code a * b} overflows in signed {@code long} arithmetic
582   */
583  @InlineMe(replacement = "Math.multiplyExact(a, b)")
584  public static long checkedMultiply(long a, long b) {
585    return Math.multiplyExact(a, b);
586  }
587
588  /**
589   * Returns the {@code b} to the {@code k}th power, provided it does not overflow.
590   *
591   * @throws ArithmeticException if {@code b} to the {@code k}th power overflows in signed {@code
592   *     long} arithmetic
593   */
594  @GwtIncompatible // TODO
595  // Whenever both tests are cheap and functional, it's faster to use &, | instead of &&, ||
596  @SuppressWarnings("ShortCircuitBoolean")
597  public static long checkedPow(long b, int k) {
598    checkNonNegative("exponent", k);
599    if (b >= -2 & b <= 2) {
600      switch ((int) b) {
601        case 0:
602          return (k == 0) ? 1 : 0;
603        case 1:
604          return 1;
605        case -1:
606          return ((k & 1) == 0) ? 1 : -1;
607        case 2:
608          checkNoOverflow(k < Long.SIZE - 1, "checkedPow", b, k);
609          return 1L << k;
610        case -2:
611          checkNoOverflow(k < Long.SIZE, "checkedPow", b, k);
612          return ((k & 1) == 0) ? (1L << k) : (-1L << k);
613        default:
614          throw new AssertionError();
615      }
616    }
617    long accum = 1;
618    while (true) {
619      switch (k) {
620        case 0:
621          return accum;
622        case 1:
623          return Math.multiplyExact(accum, b);
624        default:
625          if ((k & 1) != 0) {
626            accum = Math.multiplyExact(accum, b);
627          }
628          k >>= 1;
629          if (k > 0) {
630            checkNoOverflow(
631                -FLOOR_SQRT_MAX_LONG <= b && b <= FLOOR_SQRT_MAX_LONG, "checkedPow", b, k);
632            b *= b;
633          }
634      }
635    }
636  }
637
638  /**
639   * Returns the sum of {@code a} and {@code b} unless it would overflow or underflow in which case
640   * {@code Long.MAX_VALUE} or {@code Long.MIN_VALUE} is returned, respectively.
641   *
642   * @since 20.0
643   */
644  // Whenever both tests are cheap and functional, it's faster to use &, | instead of &&, ||
645  @SuppressWarnings("ShortCircuitBoolean")
646  public static long saturatedAdd(long a, long b) {
647    long naiveSum = a + b;
648    if ((a ^ b) < 0 | (a ^ naiveSum) >= 0) {
649      // If a and b have different signs or a has the same sign as the result then there was no
650      // overflow, return.
651      return naiveSum;
652    }
653    // we did over/under flow, if the sign is negative we should return MAX otherwise MIN
654    return Long.MAX_VALUE + ((naiveSum >>> (Long.SIZE - 1)) ^ 1);
655  }
656
657  /**
658   * Returns the difference of {@code a} and {@code b} unless it would overflow or underflow in
659   * which case {@code Long.MAX_VALUE} or {@code Long.MIN_VALUE} is returned, respectively.
660   *
661   * @since 20.0
662   */
663  // Whenever both tests are cheap and functional, it's faster to use &, | instead of &&, ||
664  @SuppressWarnings("ShortCircuitBoolean")
665  public static long saturatedSubtract(long a, long b) {
666    long naiveDifference = a - b;
667    if ((a ^ b) >= 0 | (a ^ naiveDifference) >= 0) {
668      // If a and b have the same signs or a has the same sign as the result then there was no
669      // overflow, return.
670      return naiveDifference;
671    }
672    // we did over/under flow
673    return Long.MAX_VALUE + ((naiveDifference >>> (Long.SIZE - 1)) ^ 1);
674  }
675
676  /**
677   * Returns the product of {@code a} and {@code b} unless it would overflow or underflow in which
678   * case {@code Long.MAX_VALUE} or {@code Long.MIN_VALUE} is returned, respectively.
679   *
680   * @since 20.0
681   */
682  // Whenever both tests are cheap and functional, it's faster to use &, | instead of &&, ||
683  @SuppressWarnings("ShortCircuitBoolean")
684  public static long saturatedMultiply(long a, long b) {
685    // see checkedMultiply for explanation
686    int leadingZeros =
687        Long.numberOfLeadingZeros(a)
688            + Long.numberOfLeadingZeros(~a)
689            + Long.numberOfLeadingZeros(b)
690            + Long.numberOfLeadingZeros(~b);
691    if (leadingZeros > Long.SIZE + 1) {
692      return a * b;
693    }
694    // the return value if we will overflow (which we calculate by overflowing a long :) )
695    long limit = Long.MAX_VALUE + ((a ^ b) >>> (Long.SIZE - 1));
696    if (leadingZeros < Long.SIZE | (a < 0 & b == Long.MIN_VALUE)) {
697      // overflow
698      return limit;
699    }
700    long result = a * b;
701    if (a == 0 || result / a == b) {
702      return result;
703    }
704    return limit;
705  }
706
707  /**
708   * Returns the {@code b} to the {@code k}th power, unless it would overflow or underflow in which
709   * case {@code Long.MAX_VALUE} or {@code Long.MIN_VALUE} is returned, respectively.
710   *
711   * @since 20.0
712   */
713  // Whenever both tests are cheap and functional, it's faster to use &, | instead of &&, ||
714  @SuppressWarnings("ShortCircuitBoolean")
715  public static long saturatedPow(long b, int k) {
716    checkNonNegative("exponent", k);
717    if (b >= -2 & b <= 2) {
718      switch ((int) b) {
719        case 0:
720          return (k == 0) ? 1 : 0;
721        case 1:
722          return 1;
723        case -1:
724          return ((k & 1) == 0) ? 1 : -1;
725        case 2:
726          if (k >= Long.SIZE - 1) {
727            return Long.MAX_VALUE;
728          }
729          return 1L << k;
730        case -2:
731          if (k >= Long.SIZE) {
732            return Long.MAX_VALUE + (k & 1);
733          }
734          return ((k & 1) == 0) ? (1L << k) : (-1L << k);
735        default:
736          throw new AssertionError();
737      }
738    }
739    long accum = 1;
740    // if b is negative and k is odd then the limit is MIN otherwise the limit is MAX
741    long limit = Long.MAX_VALUE + ((b >>> (Long.SIZE - 1)) & (k & 1));
742    while (true) {
743      switch (k) {
744        case 0:
745          return accum;
746        case 1:
747          return saturatedMultiply(accum, b);
748        default:
749          if ((k & 1) != 0) {
750            accum = saturatedMultiply(accum, b);
751          }
752          k >>= 1;
753          if (k > 0) {
754            if (-FLOOR_SQRT_MAX_LONG > b | b > FLOOR_SQRT_MAX_LONG) {
755              return limit;
756            }
757            b *= b;
758          }
759      }
760    }
761  }
762
763  @VisibleForTesting static final long FLOOR_SQRT_MAX_LONG = 3037000499L;
764
765  /**
766   * Returns {@code n!}, that is, the product of the first {@code n} positive integers, {@code 1} if
767   * {@code n == 0}, or {@link Long#MAX_VALUE} if the result does not fit in a {@code long}.
768   *
769   * @throws IllegalArgumentException if {@code n < 0}
770   */
771  @GwtIncompatible // TODO
772  public static long factorial(int n) {
773    checkNonNegative("n", n);
774    return (n < factorials.length) ? factorials[n] : Long.MAX_VALUE;
775  }
776
777  static final long[] factorials = {
778    1L,
779    1L,
780    1L * 2,
781    1L * 2 * 3,
782    1L * 2 * 3 * 4,
783    1L * 2 * 3 * 4 * 5,
784    1L * 2 * 3 * 4 * 5 * 6,
785    1L * 2 * 3 * 4 * 5 * 6 * 7,
786    1L * 2 * 3 * 4 * 5 * 6 * 7 * 8,
787    1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9,
788    1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10,
789    1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11,
790    1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12,
791    1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 * 13,
792    1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 * 13 * 14,
793    1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 * 13 * 14 * 15,
794    1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 * 13 * 14 * 15 * 16,
795    1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 * 13 * 14 * 15 * 16 * 17,
796    1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 * 13 * 14 * 15 * 16 * 17 * 18,
797    1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 * 13 * 14 * 15 * 16 * 17 * 18 * 19,
798    1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 * 13 * 14 * 15 * 16 * 17 * 18 * 19 * 20
799  };
800
801  /**
802   * Returns {@code n} choose {@code k}, also known as the binomial coefficient of {@code n} and
803   * {@code k}, or {@link Long#MAX_VALUE} if the result does not fit in a {@code long}.
804   *
805   * @throws IllegalArgumentException if {@code n < 0}, {@code k < 0}, or {@code k > n}
806   */
807  public static long binomial(int n, int k) {
808    checkNonNegative("n", n);
809    checkNonNegative("k", k);
810    checkArgument(k <= n, "k (%s) > n (%s)", k, n);
811    if (k > (n >> 1)) {
812      k = n - k;
813    }
814    switch (k) {
815      case 0:
816        return 1;
817      case 1:
818        return n;
819      default:
820        if (n < factorials.length) {
821          return factorials[n] / (factorials[k] * factorials[n - k]);
822        } else if (k >= biggestBinomials.length || n > biggestBinomials[k]) {
823          return Long.MAX_VALUE;
824        } else if (k < biggestSimpleBinomials.length && n <= biggestSimpleBinomials[k]) {
825          // guaranteed not to overflow
826          long result = n--;
827          for (int i = 2; i <= k; n--, i++) {
828            result *= n;
829            result /= i;
830          }
831          return result;
832        } else {
833          int nBits = log2(n, RoundingMode.CEILING);
834
835          long result = 1;
836          long numerator = n--;
837          long denominator = 1;
838
839          int numeratorBits = nBits;
840          // This is an upper bound on log2(numerator, ceiling).
841
842          /*
843           * We want to do this in long math for speed, but want to avoid overflow. We adapt the
844           * technique previously used by BigIntegerMath: maintain separate numerator and
845           * denominator accumulators, multiplying the fraction into result when near overflow.
846           */
847          for (int i = 2; i <= k; i++, n--) {
848            if (numeratorBits + nBits < Long.SIZE - 1) {
849              // It's definitely safe to multiply into numerator and denominator.
850              numerator *= n;
851              denominator *= i;
852              numeratorBits += nBits;
853            } else {
854              // It might not be safe to multiply into numerator and denominator,
855              // so multiply (numerator / denominator) into result.
856              result = multiplyFraction(result, numerator, denominator);
857              numerator = n;
858              denominator = i;
859              numeratorBits = nBits;
860            }
861          }
862          return multiplyFraction(result, numerator, denominator);
863        }
864    }
865  }
866
867  /** Returns (x * numerator / denominator), which is assumed to come out to an integral value. */
868  static long multiplyFraction(long x, long numerator, long denominator) {
869    if (x == 1) {
870      return numerator / denominator;
871    }
872    long commonDivisor = gcd(x, denominator);
873    x /= commonDivisor;
874    denominator /= commonDivisor;
875    // We know gcd(x, denominator) = 1, and x * numerator / denominator is exact,
876    // so denominator must be a divisor of numerator.
877    return x * (numerator / denominator);
878  }
879
880  /*
881   * binomial(biggestBinomials[k], k) fits in a long, but not binomial(biggestBinomials[k] + 1, k).
882   */
883  static final int[] biggestBinomials = {
884    Integer.MAX_VALUE,
885    Integer.MAX_VALUE,
886    Integer.MAX_VALUE,
887    3810779,
888    121977,
889    16175,
890    4337,
891    1733,
892    887,
893    534,
894    361,
895    265,
896    206,
897    169,
898    143,
899    125,
900    111,
901    101,
902    94,
903    88,
904    83,
905    79,
906    76,
907    74,
908    72,
909    70,
910    69,
911    68,
912    67,
913    67,
914    66,
915    66,
916    66,
917    66
918  };
919
920  /*
921   * binomial(biggestSimpleBinomials[k], k) doesn't need to use the slower GCD-based impl, but
922   * binomial(biggestSimpleBinomials[k] + 1, k) does.
923   */
924  @VisibleForTesting
925  static final int[] biggestSimpleBinomials = {
926    Integer.MAX_VALUE,
927    Integer.MAX_VALUE,
928    Integer.MAX_VALUE,
929    2642246,
930    86251,
931    11724,
932    3218,
933    1313,
934    684,
935    419,
936    287,
937    214,
938    169,
939    139,
940    119,
941    105,
942    95,
943    87,
944    81,
945    76,
946    73,
947    70,
948    68,
949    66,
950    64,
951    63,
952    62,
953    62,
954    61,
955    61,
956    61
957  };
958
959  // These values were generated by using checkedMultiply to see when the simple multiply/divide
960  // algorithm would lead to an overflow.
961
962  static boolean fitsInInt(long x) {
963    return (int) x == x;
964  }
965
966  /**
967   * Returns the arithmetic mean of {@code x} and {@code y}, rounded toward negative infinity. This
968   * method is resilient to overflow.
969   *
970   * @since 14.0
971   */
972  public static long mean(long x, long y) {
973    // Efficient method for computing the arithmetic mean.
974    // The alternative (x + y) / 2 fails for large values.
975    // The alternative (x + y) >>> 1 fails for negative values.
976    return (x & y) + ((x ^ y) >> 1);
977  }
978
979  /*
980   * This bitmask is used as an optimization for cheaply testing for divisibility by 2, 3, or 5.
981   * Each bit is set to 1 for all remainders that indicate divisibility by 2, 3, or 5, so
982   * 1, 7, 11, 13, 17, 19, 23, 29 are set to 0. 30 and up don't matter because they won't be hit.
983   */
984  private static final int SIEVE_30 =
985      ~((1 << 1) | (1 << 7) | (1 << 11) | (1 << 13) | (1 << 17) | (1 << 19) | (1 << 23)
986          | (1 << 29));
987
988  /**
989   * Returns {@code true} if {@code n} is a <a
990   * href="http://mathworld.wolfram.com/PrimeNumber.html">prime number</a>: an integer <i>greater
991   * than one</i> that cannot be factored into a product of <i>smaller</i> positive integers.
992   * Returns {@code false} if {@code n} is zero, one, or a composite number (one which <i>can</i> be
993   * factored into smaller positive integers).
994   *
995   * <p>To test larger numbers, use {@link BigInteger#isProbablePrime}.
996   *
997   * @throws IllegalArgumentException if {@code n} is negative
998   * @since 20.0
999   */
1000  @GwtIncompatible // TODO
1001  public static boolean isPrime(long n) {
1002    if (n < 2) {
1003      checkNonNegative("n", n);
1004      return false;
1005    }
1006    if (n < 66) {
1007      // Encode all primes less than 66 into mask without 0 and 1.
1008      long mask =
1009          (1L << (2 - 2))
1010              | (1L << (3 - 2))
1011              | (1L << (5 - 2))
1012              | (1L << (7 - 2))
1013              | (1L << (11 - 2))
1014              | (1L << (13 - 2))
1015              | (1L << (17 - 2))
1016              | (1L << (19 - 2))
1017              | (1L << (23 - 2))
1018              | (1L << (29 - 2))
1019              | (1L << (31 - 2))
1020              | (1L << (37 - 2))
1021              | (1L << (41 - 2))
1022              | (1L << (43 - 2))
1023              | (1L << (47 - 2))
1024              | (1L << (53 - 2))
1025              | (1L << (59 - 2))
1026              | (1L << (61 - 2));
1027      // Look up n within the mask.
1028      return ((mask >> ((int) n - 2)) & 1) != 0;
1029    }
1030
1031    if ((SIEVE_30 & (1 << (n % 30))) != 0) {
1032      return false;
1033    }
1034    if (n % 7 == 0 || n % 11 == 0 || n % 13 == 0) {
1035      return false;
1036    }
1037    if (n < 17 * 17) {
1038      return true;
1039    }
1040
1041    for (long[] baseSet : millerRabinBaseSets) {
1042      if (n <= baseSet[0]) {
1043        for (int i = 1; i < baseSet.length; i++) {
1044          if (!MillerRabinTester.test(baseSet[i], n)) {
1045            return false;
1046          }
1047        }
1048        return true;
1049      }
1050    }
1051    throw new AssertionError();
1052  }
1053
1054  /*
1055   * If n <= millerRabinBases[i][0], then testing n against bases millerRabinBases[i][1..] suffices
1056   * to prove its primality. Values from miller-rabin.appspot.com.
1057   *
1058   * NOTE: We could get slightly better bases that would be treated as unsigned, but benchmarks
1059   * showed negligible performance improvements.
1060   */
1061  private static final long[][] millerRabinBaseSets = {
1062    {291830, 126401071349994536L},
1063    {885594168, 725270293939359937L, 3569819667048198375L},
1064    {273919523040L, 15, 7363882082L, 992620450144556L},
1065    {47636622961200L, 2, 2570940, 211991001, 3749873356L},
1066    {
1067      7999252175582850L,
1068      2,
1069      4130806001517L,
1070      149795463772692060L,
1071      186635894390467037L,
1072      3967304179347715805L
1073    },
1074    {
1075      585226005592931976L,
1076      2,
1077      123635709730000L,
1078      9233062284813009L,
1079      43835965440333360L,
1080      761179012939631437L,
1081      1263739024124850375L
1082    },
1083    {Long.MAX_VALUE, 2, 325, 9375, 28178, 450775, 9780504, 1795265022}
1084  };
1085
1086  private enum MillerRabinTester {
1087    /** Works for inputs ≤ FLOOR_SQRT_MAX_LONG. */
1088    SMALL {
1089      @Override
1090      long mulMod(long a, long b, long m) {
1091        /*
1092         * lowasser, 2015-Feb-12: Benchmarks suggest that changing this to UnsignedLongs.remainder
1093         * and increasing the threshold to 2^32 doesn't pay for itself, and adding another enum
1094         * constant hurts performance further -- I suspect because bimorphic implementation is a
1095         * sweet spot for the JVM.
1096         */
1097        return (a * b) % m;
1098      }
1099
1100      @Override
1101      long squareMod(long a, long m) {
1102        return (a * a) % m;
1103      }
1104    },
1105    /** Works for all nonnegative signed longs. */
1106    LARGE {
1107      /** Returns (a + b) mod m. Precondition: {@code 0 <= a}, {@code b < m < 2^63}. */
1108      private long plusMod(long a, long b, long m) {
1109        return (a >= m - b) ? (a + b - m) : (a + b);
1110      }
1111
1112      /** Returns (a * 2^32) mod m. a may be any unsigned long. */
1113      private long times2ToThe32Mod(long a, long m) {
1114        int remainingPowersOf2 = 32;
1115        do {
1116          int shift = min(remainingPowersOf2, Long.numberOfLeadingZeros(a));
1117          // shift is either the number of powers of 2 left to multiply a by, or the biggest shift
1118          // possible while keeping a in an unsigned long.
1119          a = UnsignedLongs.remainder(a << shift, m);
1120          remainingPowersOf2 -= shift;
1121        } while (remainingPowersOf2 > 0);
1122        return a;
1123      }
1124
1125      @Override
1126      long mulMod(long a, long b, long m) {
1127        long aHi = a >>> 32; // < 2^31
1128        long bHi = b >>> 32; // < 2^31
1129        long aLo = a & 0xFFFFFFFFL; // < 2^32
1130        long bLo = b & 0xFFFFFFFFL; // < 2^32
1131
1132        /*
1133         * a * b == aHi * bHi * 2^64 + (aHi * bLo + aLo * bHi) * 2^32 + aLo * bLo.
1134         *       == (aHi * bHi * 2^32 + aHi * bLo + aLo * bHi) * 2^32 + aLo * bLo
1135         *
1136         * We carry out this computation in modular arithmetic. Since times2ToThe32Mod accepts any
1137         * unsigned long, we don't have to do a mod on every operation, only when intermediate
1138         * results can exceed 2^63.
1139         */
1140        long result = times2ToThe32Mod(aHi * bHi /* < 2^62 */, m); // < m < 2^63
1141        result += aHi * bLo; // aHi * bLo < 2^63, result < 2^64
1142        if (result < 0) {
1143          result = UnsignedLongs.remainder(result, m);
1144        }
1145        // result < 2^63 again
1146        result += aLo * bHi; // aLo * bHi < 2^63, result < 2^64
1147        result = times2ToThe32Mod(result, m); // result < m < 2^63
1148        return plusMod(result, UnsignedLongs.remainder(aLo * bLo /* < 2^64 */, m), m);
1149      }
1150
1151      @Override
1152      long squareMod(long a, long m) {
1153        long aHi = a >>> 32; // < 2^31
1154        long aLo = a & 0xFFFFFFFFL; // < 2^32
1155
1156        /*
1157         * a^2 == aHi^2 * 2^64 + aHi * aLo * 2^33 + aLo^2
1158         *     == (aHi^2 * 2^32 + aHi * aLo * 2) * 2^32 + aLo^2
1159         * We carry out this computation in modular arithmetic.  Since times2ToThe32Mod accepts any
1160         * unsigned long, we don't have to do a mod on every operation, only when intermediate
1161         * results can exceed 2^63.
1162         */
1163        long result = times2ToThe32Mod(aHi * aHi /* < 2^62 */, m); // < m < 2^63
1164        long hiLo = aHi * aLo * 2;
1165        if (hiLo < 0) {
1166          hiLo = UnsignedLongs.remainder(hiLo, m);
1167        }
1168        // hiLo < 2^63
1169        result += hiLo; // result < 2^64
1170        result = times2ToThe32Mod(result, m); // result < m < 2^63
1171        return plusMod(result, UnsignedLongs.remainder(aLo * aLo /* < 2^64 */, m), m);
1172      }
1173    };
1174
1175    static boolean test(long base, long n) {
1176      // Since base will be considered % n, it's okay if base > FLOOR_SQRT_MAX_LONG,
1177      // so long as n <= FLOOR_SQRT_MAX_LONG.
1178      return ((n <= FLOOR_SQRT_MAX_LONG) ? SMALL : LARGE).testWitness(base, n);
1179    }
1180
1181    /** Returns a * b mod m. */
1182    abstract long mulMod(long a, long b, long m);
1183
1184    /** Returns a^2 mod m. */
1185    abstract long squareMod(long a, long m);
1186
1187    /** Returns a^p mod m. */
1188    private long powMod(long a, long p, long m) {
1189      long res = 1;
1190      for (; p != 0; p >>= 1) {
1191        if ((p & 1) != 0) {
1192          res = mulMod(res, a, m);
1193        }
1194        a = squareMod(a, m);
1195      }
1196      return res;
1197    }
1198
1199    /** Returns true if n is a strong probable prime relative to the specified base. */
1200    private boolean testWitness(long base, long n) {
1201      int r = Long.numberOfTrailingZeros(n - 1);
1202      long d = (n - 1) >> r;
1203      base %= n;
1204      if (base == 0) {
1205        return true;
1206      }
1207      // Calculate a := base^d mod n.
1208      long a = powMod(base, d, n);
1209      // n passes this test if
1210      //    base^d = 1 (mod n)
1211      // or base^(2^j * d) = -1 (mod n) for some 0 <= j < r.
1212      if (a == 1) {
1213        return true;
1214      }
1215      int j = 0;
1216      while (a != n - 1) {
1217        if (++j == r) {
1218          return false;
1219        }
1220        a = squareMod(a, n);
1221      }
1222      return true;
1223    }
1224  }
1225
1226  /**
1227   * Returns {@code x}, rounded to a {@code double} with the specified rounding mode. If {@code x}
1228   * is precisely representable as a {@code double}, its {@code double} value will be returned;
1229   * otherwise, the rounding will choose between the two nearest representable values with {@code
1230   * mode}.
1231   *
1232   * <p>For the case of {@link RoundingMode#HALF_EVEN}, this implementation uses the IEEE 754
1233   * default rounding mode: if the two nearest representable values are equally near, the one with
1234   * the least significant bit zero is chosen. (In such cases, both of the nearest representable
1235   * values are even integers; this method returns the one that is a multiple of a greater power of
1236   * two.)
1237   *
1238   * @throws ArithmeticException if {@code mode} is {@link RoundingMode#UNNECESSARY} and {@code x}
1239   *     is not precisely representable as a {@code double}
1240   * @since 30.0
1241   */
1242  @GwtIncompatible
1243  public static double roundToDouble(long x, RoundingMode mode) {
1244    // Logic adapted from ToDoubleRounder.
1245    double roundArbitrarily = (double) x;
1246    long roundArbitrarilyAsLong = (long) roundArbitrarily;
1247    int cmpXToRoundArbitrarily;
1248
1249    if (roundArbitrarilyAsLong == Long.MAX_VALUE) {
1250      /*
1251       * For most values, the conversion from roundArbitrarily to roundArbitrarilyAsLong is
1252       * lossless. In that case we can compare x to roundArbitrarily using Long.compare(x,
1253       * roundArbitrarilyAsLong). The exception is for values where the conversion to double rounds
1254       * up to give roundArbitrarily equal to 2^63, so the conversion back to long overflows and
1255       * roundArbitrarilyAsLong is Long.MAX_VALUE. (This is the only way this condition can occur as
1256       * otherwise the conversion back to long pads with zero bits.) In this case we know that
1257       * roundArbitrarily > x. (This is important when x == Long.MAX_VALUE ==
1258       * roundArbitrarilyAsLong.)
1259       */
1260      cmpXToRoundArbitrarily = -1;
1261    } else {
1262      cmpXToRoundArbitrarily = Long.compare(x, roundArbitrarilyAsLong);
1263    }
1264
1265    switch (mode) {
1266      case UNNECESSARY:
1267        checkRoundingUnnecessary(cmpXToRoundArbitrarily == 0);
1268        return roundArbitrarily;
1269      case FLOOR:
1270        return (cmpXToRoundArbitrarily >= 0) ? roundArbitrarily : nextDown(roundArbitrarily);
1271      case CEILING:
1272        return (cmpXToRoundArbitrarily <= 0) ? roundArbitrarily : nextUp(roundArbitrarily);
1273      case DOWN:
1274        if (x >= 0) {
1275          return (cmpXToRoundArbitrarily >= 0) ? roundArbitrarily : nextDown(roundArbitrarily);
1276        } else {
1277          return (cmpXToRoundArbitrarily <= 0) ? roundArbitrarily : nextUp(roundArbitrarily);
1278        }
1279      case UP:
1280        if (x >= 0) {
1281          return (cmpXToRoundArbitrarily <= 0) ? roundArbitrarily : nextUp(roundArbitrarily);
1282        } else {
1283          return (cmpXToRoundArbitrarily >= 0) ? roundArbitrarily : nextDown(roundArbitrarily);
1284        }
1285      case HALF_DOWN:
1286      case HALF_UP:
1287      case HALF_EVEN:
1288        {
1289          long roundFloor;
1290          double roundFloorAsDouble;
1291          long roundCeiling;
1292          double roundCeilingAsDouble;
1293
1294          if (cmpXToRoundArbitrarily >= 0) {
1295            roundFloorAsDouble = roundArbitrarily;
1296            roundFloor = roundArbitrarilyAsLong;
1297            roundCeilingAsDouble = nextUp(roundArbitrarily);
1298            roundCeiling = (long) ceil(roundCeilingAsDouble);
1299          } else {
1300            roundCeilingAsDouble = roundArbitrarily;
1301            roundCeiling = roundArbitrarilyAsLong;
1302            roundFloorAsDouble = nextDown(roundArbitrarily);
1303            roundFloor = (long) floor(roundFloorAsDouble);
1304          }
1305
1306          long deltaToFloor = x - roundFloor;
1307          long deltaToCeiling = roundCeiling - x;
1308
1309          if (roundCeiling == Long.MAX_VALUE) {
1310            // correct for Long.MAX_VALUE as discussed above: roundCeilingAsDouble must be 2^63, but
1311            // roundCeiling is 2^63-1.
1312            deltaToCeiling++;
1313          }
1314
1315          int diff = Long.compare(deltaToFloor, deltaToCeiling);
1316          if (diff < 0) { // closer to floor
1317            return roundFloorAsDouble;
1318          } else if (diff > 0) { // closer to ceiling
1319            return roundCeilingAsDouble;
1320          }
1321          // halfway between the representable values; do the half-whatever logic
1322          switch (mode) {
1323            case HALF_EVEN:
1324              return ((DoubleUtils.getSignificand(roundFloorAsDouble) & 1L) == 0)
1325                  ? roundFloorAsDouble
1326                  : roundCeilingAsDouble;
1327            case HALF_DOWN:
1328              return (x >= 0) ? roundFloorAsDouble : roundCeilingAsDouble;
1329            case HALF_UP:
1330              return (x >= 0) ? roundCeilingAsDouble : roundFloorAsDouble;
1331            default:
1332              throw new AssertionError("impossible");
1333          }
1334        }
1335    }
1336    throw new AssertionError("impossible");
1337  }
1338
1339  /**
1340   * Returns the closest representable {@code long} to the absolute value of {@code x}.
1341   *
1342   * <p>This is the same thing as the true absolute value of {@code x} except in the case when
1343   * {@code x} is {@link Long#MIN_VALUE}, in which case this returns {@link Long#MAX_VALUE}. (Note
1344   * that {@code Long.MAX_VALUE} is mathematically equal to {@code -Long.MIN_VALUE - 1}.)
1345   *
1346   * <p>There are three common APIs for determining the absolute value of a long, all of which
1347   * behave identically except when passed {@code Long.MIN_VALUE}. Those methods are:
1348   *
1349   * <ul>
1350   *   <li>{@link Math#abs(long)}, which returns {@code Long.MIN_VALUE} when passed {@code
1351   *       Long.MIN_VALUE}
1352   *   <li>{@link Math#absExact(long)}, which throws {@link ArithmeticException} when passed {@code
1353   *       Long.MIN_VALUE}
1354   *   <li>this method, {@code LongMath.saturatedAbs(long)}, which returns {@code Long.MAX_VALUE}
1355   *       when passed {@code Long.MIN_VALUE}
1356   * </ul>
1357   *
1358   * <p>Note that if your only goal is to turn a well-distributed {@code long} (such as a random
1359   * number) into a well-distributed nonnegative number, the most even distribution is achieved not
1360   * by this method or other absolute value methods, but by {@code x & Long.MAX_VALUE}.
1361   *
1362   * @since 33.5.0
1363   */
1364  public static long saturatedAbs(long x) {
1365    return (x == Long.MIN_VALUE) ? Long.MAX_VALUE : Math.abs(x);
1366  }
1367
1368  private LongMath() {}
1369}