001/*
002 * Copyright (C) 2011 The Guava Authors
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 * http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package com.google.common.math;
018
019import static com.google.common.base.Preconditions.checkArgument;
020import static com.google.common.base.Preconditions.checkNotNull;
021import static com.google.common.math.MathPreconditions.checkNoOverflow;
022import static com.google.common.math.MathPreconditions.checkNonNegative;
023import static com.google.common.math.MathPreconditions.checkPositive;
024import static com.google.common.math.MathPreconditions.checkRoundingUnnecessary;
025import static java.lang.Math.abs;
026import static java.lang.Math.min;
027import static java.math.RoundingMode.HALF_EVEN;
028import static java.math.RoundingMode.HALF_UP;
029
030import com.google.common.annotations.GwtCompatible;
031import com.google.common.annotations.GwtIncompatible;
032import com.google.common.annotations.VisibleForTesting;
033
034import java.math.BigInteger;
035import java.math.RoundingMode;
036
037/**
038 * A class for arithmetic on values of type {@code long}. Where possible, methods are defined and
039 * named analogously to their {@code BigInteger} counterparts.
040 *
041 * <p>The implementations of many methods in this class are based on material from Henry S. Warren,
042 * Jr.'s <i>Hacker's Delight</i>, (Addison Wesley, 2002).
043 *
044 * <p>Similar functionality for {@code int} and for {@link BigInteger} can be found in
045 * {@link IntMath} and {@link BigIntegerMath} respectively.  For other common operations on
046 * {@code long} values, see {@link com.google.common.primitives.Longs}.
047 *
048 * @author Louis Wasserman
049 * @since 11.0
050 */
051@GwtCompatible(emulated = true)
052public final class LongMath {
053  // NOTE: Whenever both tests are cheap and functional, it's faster to use &, | instead of &&, ||
054
055  /**
056   * Returns {@code true} if {@code x} represents a power of two.
057   *
058   * <p>This differs from {@code Long.bitCount(x) == 1}, because
059   * {@code Long.bitCount(Long.MIN_VALUE) == 1}, but {@link Long#MIN_VALUE} is not a power of two.
060   */
061  public static boolean isPowerOfTwo(long x) {
062    return x > 0 & (x & (x - 1)) == 0;
063  }
064
065  /**
066   * Returns the base-2 logarithm of {@code x}, rounded according to the specified rounding mode.
067   *
068   * @throws IllegalArgumentException if {@code x <= 0}
069   * @throws ArithmeticException if {@code mode} is {@link RoundingMode#UNNECESSARY} and {@code x}
070   *         is not a power of two
071   */
072  @SuppressWarnings("fallthrough")
073  // TODO(kevinb): remove after this warning is disabled globally
074  public static int log2(long x, RoundingMode mode) {
075    checkPositive("x", x);
076    switch (mode) {
077      case UNNECESSARY:
078        checkRoundingUnnecessary(isPowerOfTwo(x));
079        // fall through
080      case DOWN:
081      case FLOOR:
082        return (Long.SIZE - 1) - Long.numberOfLeadingZeros(x);
083
084      case UP:
085      case CEILING:
086        return Long.SIZE - Long.numberOfLeadingZeros(x - 1);
087
088      case HALF_DOWN:
089      case HALF_UP:
090      case HALF_EVEN:
091        // Since sqrt(2) is irrational, log2(x) - logFloor cannot be exactly 0.5
092        int leadingZeros = Long.numberOfLeadingZeros(x);
093        long cmp = MAX_POWER_OF_SQRT2_UNSIGNED >>> leadingZeros;
094        // floor(2^(logFloor + 0.5))
095        int logFloor = (Long.SIZE - 1) - leadingZeros;
096        return (x <= cmp) ? logFloor : logFloor + 1;
097
098      default:
099        throw new AssertionError("impossible");
100    }
101  }
102
103  /** The biggest half power of two that fits into an unsigned long */
104  @VisibleForTesting static final long MAX_POWER_OF_SQRT2_UNSIGNED = 0xB504F333F9DE6484L;
105
106  /**
107   * Returns the base-10 logarithm of {@code x}, rounded according to the specified rounding mode.
108   *
109   * @throws IllegalArgumentException if {@code x <= 0}
110   * @throws ArithmeticException if {@code mode} is {@link RoundingMode#UNNECESSARY} and {@code x}
111   *         is not a power of ten
112   */
113  @GwtIncompatible("TODO")
114  @SuppressWarnings("fallthrough")
115  // TODO(kevinb): remove after this warning is disabled globally
116  public static int log10(long x, RoundingMode mode) {
117    checkPositive("x", x);
118    if (fitsInInt(x)) {
119      return IntMath.log10((int) x, mode);
120    }
121    int logFloor = log10Floor(x);
122    long floorPow = powersOf10[logFloor];
123    switch (mode) {
124      case UNNECESSARY:
125        checkRoundingUnnecessary(x == floorPow);
126        // fall through
127      case FLOOR:
128      case DOWN:
129        return logFloor;
130      case CEILING:
131      case UP:
132        return (x == floorPow) ? logFloor : logFloor + 1;
133      case HALF_DOWN:
134      case HALF_UP:
135      case HALF_EVEN:
136        // sqrt(10) is irrational, so log10(x)-logFloor is never exactly 0.5
137        return (x <= halfPowersOf10[logFloor]) ? logFloor : logFloor + 1;
138      default:
139        throw new AssertionError();
140    }
141  }
142
143  @GwtIncompatible("TODO")
144  static int log10Floor(long x) {
145    /*
146     * Based on Hacker's Delight Fig. 11-5, the two-table-lookup, branch-free implementation.
147     *
148     * The key idea is that based on the number of leading zeros (equivalently, floor(log2(x))),
149     * we can narrow the possible floor(log10(x)) values to two.  For example, if floor(log2(x))
150     * is 6, then 64 <= x < 128, so floor(log10(x)) is either 1 or 2.
151     */
152    int y = maxLog10ForLeadingZeros[Long.numberOfLeadingZeros(x)];
153    // y is the higher of the two possible values of floor(log10(x))
154
155    long sgn = (x - powersOf10[y]) >>> (Long.SIZE - 1);
156    /*
157     * sgn is the sign bit of x - 10^y; it is 1 if x < 10^y, and 0 otherwise. If x < 10^y, then we
158     * want the lower of the two possible values, or y - 1, otherwise, we want y.
159     */
160    return y - (int) sgn;
161  }
162
163  // maxLog10ForLeadingZeros[i] == floor(log10(2^(Long.SIZE - i)))
164  @VisibleForTesting static final byte[] maxLog10ForLeadingZeros = {
165      19, 18, 18, 18, 18, 17, 17, 17, 16, 16, 16, 15, 15, 15, 15, 14, 14, 14, 13, 13, 13, 12, 12,
166      12, 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,
167      3, 3, 3, 3, 2, 2, 2, 1, 1, 1, 0, 0, 0 };
168
169  @GwtIncompatible("TODO")
170  @VisibleForTesting
171  static final long[] powersOf10 = {
172    1L,
173    10L,
174    100L,
175    1000L,
176    10000L,
177    100000L,
178    1000000L,
179    10000000L,
180    100000000L,
181    1000000000L,
182    10000000000L,
183    100000000000L,
184    1000000000000L,
185    10000000000000L,
186    100000000000000L,
187    1000000000000000L,
188    10000000000000000L,
189    100000000000000000L,
190    1000000000000000000L
191  };
192
193  // halfPowersOf10[i] = largest long less than 10^(i + 0.5)
194  @GwtIncompatible("TODO")
195  @VisibleForTesting
196  static final long[] halfPowersOf10 = {
197    3L,
198    31L,
199    316L,
200    3162L,
201    31622L,
202    316227L,
203    3162277L,
204    31622776L,
205    316227766L,
206    3162277660L,
207    31622776601L,
208    316227766016L,
209    3162277660168L,
210    31622776601683L,
211    316227766016837L,
212    3162277660168379L,
213    31622776601683793L,
214    316227766016837933L,
215    3162277660168379331L
216  };
217
218  /**
219   * Returns {@code b} to the {@code k}th power. Even if the result overflows, it will be equal to
220   * {@code BigInteger.valueOf(b).pow(k).longValue()}. This implementation runs in {@code O(log k)}
221   * time.
222   *
223   * @throws IllegalArgumentException if {@code k < 0}
224   */
225  @GwtIncompatible("TODO")
226  public static long pow(long b, int k) {
227    checkNonNegative("exponent", k);
228    if (-2 <= b && b <= 2) {
229      switch ((int) b) {
230        case 0:
231          return (k == 0) ? 1 : 0;
232        case 1:
233          return 1;
234        case (-1):
235          return ((k & 1) == 0) ? 1 : -1;
236        case 2:
237          return (k < Long.SIZE) ? 1L << k : 0;
238        case (-2):
239          if (k < Long.SIZE) {
240            return ((k & 1) == 0) ? 1L << k : -(1L << k);
241          } else {
242            return 0;
243          }
244        default:
245          throw new AssertionError();
246      }
247    }
248    for (long accum = 1;; k >>= 1) {
249      switch (k) {
250        case 0:
251          return accum;
252        case 1:
253          return accum * b;
254        default:
255          accum *= ((k & 1) == 0) ? 1 : b;
256          b *= b;
257      }
258    }
259  }
260
261  /**
262   * Returns the square root of {@code x}, rounded with the specified rounding mode.
263   *
264   * @throws IllegalArgumentException if {@code x < 0}
265   * @throws ArithmeticException if {@code mode} is {@link RoundingMode#UNNECESSARY} and
266   *         {@code sqrt(x)} is not an integer
267   */
268  @GwtIncompatible("TODO")
269  @SuppressWarnings("fallthrough")
270  public static long sqrt(long x, RoundingMode mode) {
271    checkNonNegative("x", x);
272    if (fitsInInt(x)) {
273      return IntMath.sqrt((int) x, mode);
274    }
275    long sqrtFloor = sqrtFloor(x);
276    switch (mode) {
277      case UNNECESSARY:
278        checkRoundingUnnecessary(sqrtFloor * sqrtFloor == x); // fall through
279      case FLOOR:
280      case DOWN:
281        return sqrtFloor;
282      case CEILING:
283      case UP:
284        return (sqrtFloor * sqrtFloor == x) ? sqrtFloor : sqrtFloor + 1;
285      case HALF_DOWN:
286      case HALF_UP:
287      case HALF_EVEN:
288        long halfSquare = sqrtFloor * sqrtFloor + sqrtFloor;
289        /*
290         * We wish to test whether or not x <= (sqrtFloor + 0.5)^2 = halfSquare + 0.25. Since both
291         * x and halfSquare are integers, this is equivalent to testing whether or not x <=
292         * halfSquare. (We have to deal with overflow, though.)
293         */
294        return (halfSquare >= x | halfSquare < 0) ? sqrtFloor : sqrtFloor + 1;
295      default:
296        throw new AssertionError();
297    }
298  }
299
300  @GwtIncompatible("TODO")
301  private static long sqrtFloor(long x) {
302    long guess = (long) Math.sqrt(x);
303    /*
304     * Lemma: For all a, b, if |a - b| <= 1, then |floor(a) - floor(b)| <= 1.
305     * 
306     * Proof: 
307     *           -1 <=        a - b        <= 1
308     *        b - 1 <=          a          <= b + 1
309     * floor(b - 1) <=       floor(a)      <= floor(b + 1)
310     * floor(b) - 1 <=       floor(a)      <= floor(b) + 1
311     *           -1 <= floor(a) - floor(b) <= 1
312     * 
313     * Theorem: |floor(sqrt(x)) - guess| <= 1.
314     * 
315     * Proof:  By the lemma, it suffices to show that |sqrt(x) - Math.sqrt(x)| <= 1.
316     * We consider two cases: x <= 2^53 and x > 2^53.
317     * 
318     * If x <= 2^53, then x is exactly representable as a double, so the only error is in rounding
319     * sqrt(x) to a double, which introduces at most 2^-52 relative error.  Since sqrt(x) < 2^27,
320     * the absolute error is at most 2^(27-52) = 2^-25 < 1.
321     * 
322     * Otherwise, x > 2^53.  The rounding error introduced by casting x to a double is at most
323     * 2^63 * 2^-52 = 2^11.  Noting that sqrt(x) > 2^26,
324     * 
325     * sqrt(x) - 0.5 =  sqrt((sqrt(x) - 0.5)^2)
326     *               =  sqrt(x - sqrt(x) + 0.25)
327     *               <  sqrt(x - 2^26 + 0.25)
328     *               <  sqrt(x - 2^11)
329     *               <= sqrt((double) x)
330     * sqrt(x) + 0.5 =  sqrt((sqrt(x) + 0.5)^2)
331     *               =  sqrt(x + sqrt(x) + 0.25)
332     *               >  sqrt(x + 2^26 + 0.25)
333     *               >  sqrt(x + 2^11)
334     *               >= sqrt((double) x)     
335     * sqrt(x) - 0.5 < sqrt((double) x) < sqrt(x) + 0.5
336     * 
337     * Math.sqrt((double) x) is obtained by rounding sqrt((double) x) to a double, increasing the
338     * error by at most 2^-52 * sqrt(x) <= 2^(32 - 52) <= 2^-20, so clearly
339     * 
340     * sqrt(x) - 0.5 - 2^-20 <= Math.sqrt((double) x) <= sqrt(x) + 0.5 + 2^-20 
341     * 
342     * Therefore, |sqrt(x) - Math.sqrt((double) x)| <= 1, so
343     *            |floor(sqrt(x)) - (long) Math.sqrt((double) x)| <= 1
344     *            as desired.
345     */
346    long guessSquared = guess * guess;
347    if (x - guessSquared >= guess + guess + 1) {
348      // The condition is equivalent to x >= (guess + 1) * (guess + 1), but doesn't overflow.
349      guess++;
350    } else if (x < guessSquared) {
351      guess--;
352    }
353    return guess;
354  }
355
356  /**
357   * Returns the result of dividing {@code p} by {@code q}, rounding using the specified
358   * {@code RoundingMode}.
359   *
360   * @throws ArithmeticException if {@code q == 0}, or if {@code mode == UNNECESSARY} and {@code a}
361   *         is not an integer multiple of {@code b}
362   */
363  @GwtIncompatible("TODO")
364  @SuppressWarnings("fallthrough")
365  public static long divide(long p, long q, RoundingMode mode) {
366    checkNotNull(mode);
367    long div = p / q; // throws if q == 0
368    long rem = p - q * div; // equals p % q
369
370    if (rem == 0) {
371      return div;
372    }
373
374    /*
375     * Normal Java division rounds towards 0, consistently with RoundingMode.DOWN. We just have to
376     * deal with the cases where rounding towards 0 is wrong, which typically depends on the sign of
377     * p / q.
378     *
379     * signum is 1 if p and q are both nonnegative or both negative, and -1 otherwise.
380     */
381    int signum = 1 | (int) ((p ^ q) >> (Long.SIZE - 1));
382    boolean increment;
383    switch (mode) {
384      case UNNECESSARY:
385        checkRoundingUnnecessary(rem == 0);
386        // fall through
387      case DOWN:
388        increment = false;
389        break;
390      case UP:
391        increment = true;
392        break;
393      case CEILING:
394        increment = signum > 0;
395        break;
396      case FLOOR:
397        increment = signum < 0;
398        break;
399      case HALF_EVEN:
400      case HALF_DOWN:
401      case HALF_UP:
402        long absRem = abs(rem);
403        long cmpRemToHalfDivisor = absRem - (abs(q) - absRem);
404        // subtracting two nonnegative longs can't overflow
405        // cmpRemToHalfDivisor has the same sign as compare(abs(rem), abs(q) / 2).
406        if (cmpRemToHalfDivisor == 0) { // exactly on the half mark
407          increment = (mode == HALF_UP | (mode == HALF_EVEN & (div & 1) != 0));
408        } else {
409          increment = cmpRemToHalfDivisor > 0; // closer to the UP value
410        }
411        break;
412      default:
413        throw new AssertionError();
414    }
415    return increment ? div + signum : div;
416  }
417
418  /**
419   * Returns {@code x mod m}. This differs from {@code x % m} in that it always returns a
420   * non-negative result.
421   *
422   * <p>For example:
423   *
424   * <pre> {@code
425   *
426   * mod(7, 4) == 3
427   * mod(-7, 4) == 1
428   * mod(-1, 4) == 3
429   * mod(-8, 4) == 0
430   * mod(8, 4) == 0}</pre>
431   *
432   * @throws ArithmeticException if {@code m <= 0}
433   */
434  @GwtIncompatible("TODO")
435  public static int mod(long x, int m) {
436    // Cast is safe because the result is guaranteed in the range [0, m)
437    return (int) mod(x, (long) m);
438  }
439
440  /**
441   * Returns {@code x mod m}. This differs from {@code x % m} in that it always returns a
442   * non-negative result.
443   *
444   * <p>For example:
445   *
446   * <pre> {@code
447   *
448   * mod(7, 4) == 3
449   * mod(-7, 4) == 1
450   * mod(-1, 4) == 3
451   * mod(-8, 4) == 0
452   * mod(8, 4) == 0}</pre>
453   *
454   * @throws ArithmeticException if {@code m <= 0}
455   */
456  @GwtIncompatible("TODO")
457  public static long mod(long x, long m) {
458    if (m <= 0) {
459      throw new ArithmeticException("Modulus " + m + " must be > 0");
460    }
461    long result = x % m;
462    return (result >= 0) ? result : result + m;
463  }
464
465  /**
466   * Returns the greatest common divisor of {@code a, b}. Returns {@code 0} if
467   * {@code a == 0 && b == 0}.
468   *
469   * @throws IllegalArgumentException if {@code a < 0} or {@code b < 0}
470   */
471  public static long gcd(long a, long b) {
472    /*
473     * The reason we require both arguments to be >= 0 is because otherwise, what do you return on
474     * gcd(0, Long.MIN_VALUE)? BigInteger.gcd would return positive 2^63, but positive 2^63 isn't
475     * an int.
476     */
477    checkNonNegative("a", a);
478    checkNonNegative("b", b);
479    if (a == 0) {
480      // 0 % b == 0, so b divides a, but the converse doesn't hold.
481      // BigInteger.gcd is consistent with this decision.
482      return b;
483    } else if (b == 0) {
484      return a; // similar logic
485    }
486    /*
487     * Uses the binary GCD algorithm; see http://en.wikipedia.org/wiki/Binary_GCD_algorithm.
488     * This is >60% faster than the Euclidean algorithm in benchmarks.
489     */
490    int aTwos = Long.numberOfTrailingZeros(a);
491    a >>= aTwos; // divide out all 2s
492    int bTwos = Long.numberOfTrailingZeros(b);
493    b >>= bTwos; // divide out all 2s
494    while (a != b) { // both a, b are odd
495      // The key to the binary GCD algorithm is as follows:
496      // Both a and b are odd.  Assume a > b; then gcd(a - b, b) = gcd(a, b).
497      // But in gcd(a - b, b), a - b is even and b is odd, so we can divide out powers of two.
498
499      // We bend over backwards to avoid branching, adapting a technique from
500      // http://graphics.stanford.edu/~seander/bithacks.html#IntegerMinOrMax
501
502      long delta = a - b; // can't overflow, since a and b are nonnegative
503
504      long minDeltaOrZero = delta & (delta >> (Long.SIZE - 1));
505      // equivalent to Math.min(delta, 0)
506
507      a = delta - minDeltaOrZero - minDeltaOrZero; // sets a to Math.abs(a - b)
508      // a is now nonnegative and even
509
510      b += minDeltaOrZero; // sets b to min(old a, b)
511      a >>= Long.numberOfTrailingZeros(a); // divide out all 2s, since 2 doesn't divide b
512    }
513    return a << min(aTwos, bTwos);
514  }
515
516  /**
517   * Returns the sum of {@code a} and {@code b}, provided it does not overflow.
518   *
519   * @throws ArithmeticException if {@code a + b} overflows in signed {@code long} arithmetic
520   */
521  @GwtIncompatible("TODO")
522  public static long checkedAdd(long a, long b) {
523    long result = a + b;
524    checkNoOverflow((a ^ b) < 0 | (a ^ result) >= 0);
525    return result;
526  }
527
528  /**
529   * Returns the difference of {@code a} and {@code b}, provided it does not overflow.
530   *
531   * @throws ArithmeticException if {@code a - b} overflows in signed {@code long} arithmetic
532   */
533  @GwtIncompatible("TODO")
534  public static long checkedSubtract(long a, long b) {
535    long result = a - b;
536    checkNoOverflow((a ^ b) >= 0 | (a ^ result) >= 0);
537    return result;
538  }
539
540  /**
541   * Returns the product of {@code a} and {@code b}, provided it does not overflow.
542   *
543   * @throws ArithmeticException if {@code a * b} overflows in signed {@code long} arithmetic
544   */
545  @GwtIncompatible("TODO")
546  public static long checkedMultiply(long a, long b) {
547    // Hacker's Delight, Section 2-12
548    int leadingZeros = Long.numberOfLeadingZeros(a) + Long.numberOfLeadingZeros(~a)
549        + Long.numberOfLeadingZeros(b) + Long.numberOfLeadingZeros(~b);
550    /*
551     * If leadingZeros > Long.SIZE + 1 it's definitely fine, if it's < Long.SIZE it's definitely
552     * bad. We do the leadingZeros check to avoid the division below if at all possible.
553     *
554     * Otherwise, if b == Long.MIN_VALUE, then the only allowed values of a are 0 and 1. We take
555     * care of all a < 0 with their own check, because in particular, the case a == -1 will
556     * incorrectly pass the division check below.
557     *
558     * In all other cases, we check that either a is 0 or the result is consistent with division.
559     */
560    if (leadingZeros > Long.SIZE + 1) {
561      return a * b;
562    }
563    checkNoOverflow(leadingZeros >= Long.SIZE);
564    checkNoOverflow(a >= 0 | b != Long.MIN_VALUE);
565    long result = a * b;
566    checkNoOverflow(a == 0 || result / a == b);
567    return result;
568  }
569
570  /**
571   * Returns the {@code b} to the {@code k}th power, provided it does not overflow.
572   *
573   * @throws ArithmeticException if {@code b} to the {@code k}th power overflows in signed
574   *         {@code long} arithmetic
575   */
576  @GwtIncompatible("TODO")
577  public static long checkedPow(long b, int k) {
578    checkNonNegative("exponent", k);
579    if (b >= -2 & b <= 2) {
580      switch ((int) b) {
581        case 0:
582          return (k == 0) ? 1 : 0;
583        case 1:
584          return 1;
585        case (-1):
586          return ((k & 1) == 0) ? 1 : -1;
587        case 2:
588          checkNoOverflow(k < Long.SIZE - 1);
589          return 1L << k;
590        case (-2):
591          checkNoOverflow(k < Long.SIZE);
592          return ((k & 1) == 0) ? (1L << k) : (-1L << k);
593        default:
594          throw new AssertionError();
595      }
596    }
597    long accum = 1;
598    while (true) {
599      switch (k) {
600        case 0:
601          return accum;
602        case 1:
603          return checkedMultiply(accum, b);
604        default:
605          if ((k & 1) != 0) {
606            accum = checkedMultiply(accum, b);
607          }
608          k >>= 1;
609          if (k > 0) {
610            checkNoOverflow(b <= FLOOR_SQRT_MAX_LONG);
611            b *= b;
612          }
613      }
614    }
615  }
616
617  @GwtIncompatible("TODO")
618  @VisibleForTesting static final long FLOOR_SQRT_MAX_LONG = 3037000499L;
619
620  /**
621   * Returns {@code n!}, that is, the product of the first {@code n} positive
622   * integers, {@code 1} if {@code n == 0}, or {@link Long#MAX_VALUE} if the
623   * result does not fit in a {@code long}.
624   *
625   * @throws IllegalArgumentException if {@code n < 0}
626   */
627  @GwtIncompatible("TODO")
628  public static long factorial(int n) {
629    checkNonNegative("n", n);
630    return (n < factorials.length) ? factorials[n] : Long.MAX_VALUE;
631  }
632
633  static final long[] factorials = {
634      1L,
635      1L,
636      1L * 2,
637      1L * 2 * 3,
638      1L * 2 * 3 * 4,
639      1L * 2 * 3 * 4 * 5,
640      1L * 2 * 3 * 4 * 5 * 6,
641      1L * 2 * 3 * 4 * 5 * 6 * 7,
642      1L * 2 * 3 * 4 * 5 * 6 * 7 * 8,
643      1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9,
644      1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10,
645      1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11,
646      1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12,
647      1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 * 13,
648      1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 * 13 * 14,
649      1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 * 13 * 14 * 15,
650      1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 * 13 * 14 * 15 * 16,
651      1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 * 13 * 14 * 15 * 16 * 17,
652      1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 * 13 * 14 * 15 * 16 * 17 * 18,
653      1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 * 13 * 14 * 15 * 16 * 17 * 18 * 19,
654      1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 * 13 * 14 * 15 * 16 * 17 * 18 * 19 * 20
655  };
656
657  /**
658   * Returns {@code n} choose {@code k}, also known as the binomial coefficient of {@code n} and
659   * {@code k}, or {@link Long#MAX_VALUE} if the result does not fit in a {@code long}.
660   *
661   * @throws IllegalArgumentException if {@code n < 0}, {@code k < 0}, or {@code k > n}
662   */
663  public static long binomial(int n, int k) {
664    checkNonNegative("n", n);
665    checkNonNegative("k", k);
666    checkArgument(k <= n, "k (%s) > n (%s)", k, n);
667    if (k > (n >> 1)) {
668      k = n - k;
669    }
670    switch (k) {
671      case 0:
672        return 1;
673      case 1:
674        return n;
675      default:
676        if (n < factorials.length) {
677          return factorials[n] / (factorials[k] * factorials[n - k]);
678        } else if (k >= biggestBinomials.length || n > biggestBinomials[k]) {
679          return Long.MAX_VALUE;
680        } else if (k < biggestSimpleBinomials.length && n <= biggestSimpleBinomials[k]) {
681          // guaranteed not to overflow
682          long result = n--;
683          for (int i = 2; i <= k; n--, i++) {
684            result *= n;
685            result /= i;
686          }
687          return result;
688        } else {
689          int nBits = LongMath.log2(n, RoundingMode.CEILING);
690          
691          long result = 1;
692          long numerator = n--;
693          long denominator = 1;
694          
695          int numeratorBits = nBits;
696          // This is an upper bound on log2(numerator, ceiling).
697          
698          /*
699           * We want to do this in long math for speed, but want to avoid overflow. We adapt the
700           * technique previously used by BigIntegerMath: maintain separate numerator and
701           * denominator accumulators, multiplying the fraction into result when near overflow.
702           */
703          for (int i = 2; i <= k; i++, n--) {
704            if (numeratorBits + nBits < Long.SIZE - 1) {
705              // It's definitely safe to multiply into numerator and denominator.
706              numerator *= n;
707              denominator *= i;
708              numeratorBits += nBits;
709            } else {
710              // It might not be safe to multiply into numerator and denominator,
711              // so multiply (numerator / denominator) into result.
712              result = multiplyFraction(result, numerator, denominator);
713              numerator = n;
714              denominator = i;
715              numeratorBits = nBits;
716            }
717          }
718          return multiplyFraction(result, numerator, denominator);
719        }
720    }
721  }
722  
723  /**
724   * Returns (x * numerator / denominator), which is assumed to come out to an integral value.
725   */
726  static long multiplyFraction(long x, long numerator, long denominator) {
727    if (x == 1) {
728      return numerator / denominator;
729    }
730    long commonDivisor = gcd(x, denominator);
731    x /= commonDivisor;
732    denominator /= commonDivisor;
733    // We know gcd(x, denominator) = 1, and x * numerator / denominator is exact,
734    // so denominator must be a divisor of numerator.
735    return x * (numerator / denominator);
736  }
737
738  /*
739   * binomial(biggestBinomials[k], k) fits in a long, but not
740   * binomial(biggestBinomials[k] + 1, k).
741   */
742  static final int[] biggestBinomials =
743      {Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE, 3810779, 121977, 16175, 4337, 1733,
744          887, 534, 361, 265, 206, 169, 143, 125, 111, 101, 94, 88, 83, 79, 76, 74, 72, 70, 69, 68,
745          67, 67, 66, 66, 66, 66};
746
747  /*
748   * binomial(biggestSimpleBinomials[k], k) doesn't need to use the slower GCD-based impl,
749   * but binomial(biggestSimpleBinomials[k] + 1, k) does.
750   */
751  @VisibleForTesting static final int[] biggestSimpleBinomials =
752      {Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE, 2642246, 86251, 11724, 3218, 1313,
753          684, 419, 287, 214, 169, 139, 119, 105, 95, 87, 81, 76, 73, 70, 68, 66, 64, 63, 62, 62,
754          61, 61, 61};
755  // These values were generated by using checkedMultiply to see when the simple multiply/divide
756  // algorithm would lead to an overflow.
757
758  @GwtIncompatible("TODO")
759  static boolean fitsInInt(long x) {
760    return (int) x == x;
761  }
762
763  /**
764   * Returns the arithmetic mean of {@code x} and {@code y}, rounded toward
765   * negative infinity. This method is resilient to overflow.
766   *
767   * @since 14.0
768   */
769  public static long mean(long x, long y) {
770    // Efficient method for computing the arithmetic mean.
771    // The alternative (x + y) / 2 fails for large values.
772    // The alternative (x + y) >>> 1 fails for negative values.
773    return (x & y) + ((x ^ y) >> 1);
774  }
775
776  private LongMath() {}
777}