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.min;
025import static java.math.RoundingMode.HALF_EVEN;
026import static java.math.RoundingMode.HALF_UP;
027
028import com.google.common.annotations.GwtCompatible;
029import com.google.common.annotations.GwtIncompatible;
030import com.google.common.annotations.VisibleForTesting;
031import com.google.common.primitives.Ints;
032import java.math.BigInteger;
033import java.math.RoundingMode;
034
035/**
036 * A class for arithmetic on values of type {@code int}. Where possible, methods are defined and
037 * named analogously to their {@code BigInteger} counterparts.
038 *
039 * <p>The implementations of many methods in this class are based on material from Henry S. Warren,
040 * Jr.'s <i>Hacker's Delight</i>, (Addison Wesley, 2002).
041 *
042 * <p>Similar functionality for {@code long} and for {@link BigInteger} can be found in {@link
043 * LongMath} and {@link BigIntegerMath} respectively. For other common operations on {@code int}
044 * values, see {@link com.google.common.primitives.Ints}.
045 *
046 * @author Louis Wasserman
047 * @since 11.0
048 */
049@GwtCompatible(emulated = true)
050public final class IntMath {
051  @VisibleForTesting static final int MAX_SIGNED_POWER_OF_TWO = 1 << (Integer.SIZE - 2);
052
053  /**
054   * Returns the smallest power of two greater than or equal to {@code x}. This is equivalent to
055   * {@code checkedPow(2, log2(x, CEILING))}.
056   *
057   * @throws IllegalArgumentException if {@code x <= 0}
058   * @throws ArithmeticException of the next-higher power of two is not representable as an {@code
059   *     int}, i.e. when {@code x > 2^30}
060   * @since 20.0
061   */
062  public static int ceilingPowerOfTwo(int x) {
063    checkPositive("x", x);
064    if (x > MAX_SIGNED_POWER_OF_TWO) {
065      throw new ArithmeticException("ceilingPowerOfTwo(" + x + ") not representable as an int");
066    }
067    return 1 << -Integer.numberOfLeadingZeros(x - 1);
068  }
069
070  /**
071   * Returns the largest power of two less than or equal to {@code x}. This is equivalent to {@code
072   * checkedPow(2, log2(x, FLOOR))}.
073   *
074   * @throws IllegalArgumentException if {@code x <= 0}
075   * @since 20.0
076   */
077  public static int floorPowerOfTwo(int x) {
078    checkPositive("x", x);
079    return Integer.highestOneBit(x);
080  }
081
082  /**
083   * Returns {@code true} if {@code x} represents a power of two.
084   *
085   * <p>This differs from {@code Integer.bitCount(x) == 1}, because {@code
086   * Integer.bitCount(Integer.MIN_VALUE) == 1}, but {@link Integer#MIN_VALUE} is not a power of two.
087   */
088  // Whenever both tests are cheap and functional, it's faster to use &, | instead of &&, ||
089  @SuppressWarnings("ShortCircuitBoolean")
090  public static boolean isPowerOfTwo(int x) {
091    return x > 0 & (x & (x - 1)) == 0;
092  }
093
094  /**
095   * Returns 1 if {@code x < y} as unsigned integers, and 0 otherwise. Assumes that x - y fits into
096   * a signed int. The implementation is branch-free, and benchmarks suggest it is measurably (if
097   * narrowly) faster than the straightforward ternary expression.
098   */
099  @VisibleForTesting
100  static int lessThanBranchFree(int x, int y) {
101    // The double negation is optimized away by normal Java, but is necessary for GWT
102    // to make sure bit twiddling works as expected.
103    return ~~(x - y) >>> (Integer.SIZE - 1);
104  }
105
106  /**
107   * Returns the base-2 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 two
112   */
113  @SuppressWarnings("fallthrough")
114  // TODO(kevinb): remove after this warning is disabled globally
115  public static int log2(int x, RoundingMode mode) {
116    checkPositive("x", x);
117    switch (mode) {
118      case UNNECESSARY:
119        checkRoundingUnnecessary(isPowerOfTwo(x));
120        // fall through
121      case DOWN:
122      case FLOOR:
123        return (Integer.SIZE - 1) - Integer.numberOfLeadingZeros(x);
124
125      case UP:
126      case CEILING:
127        return Integer.SIZE - Integer.numberOfLeadingZeros(x - 1);
128
129      case HALF_DOWN:
130      case HALF_UP:
131      case HALF_EVEN:
132        // Since sqrt(2) is irrational, log2(x) - logFloor cannot be exactly 0.5
133        int leadingZeros = Integer.numberOfLeadingZeros(x);
134        int cmp = MAX_POWER_OF_SQRT2_UNSIGNED >>> leadingZeros;
135        // floor(2^(logFloor + 0.5))
136        int logFloor = (Integer.SIZE - 1) - leadingZeros;
137        return logFloor + lessThanBranchFree(cmp, x);
138    }
139    throw new AssertionError();
140  }
141
142  /** The biggest half power of two that can fit in an unsigned int. */
143  @VisibleForTesting static final int MAX_POWER_OF_SQRT2_UNSIGNED = 0xB504F333;
144
145  /**
146   * Returns the base-10 logarithm of {@code x}, rounded according to the specified rounding mode.
147   *
148   * @throws IllegalArgumentException if {@code x <= 0}
149   * @throws ArithmeticException if {@code mode} is {@link RoundingMode#UNNECESSARY} and {@code x}
150   *     is not a power of ten
151   */
152  @GwtIncompatible // need BigIntegerMath to adequately test
153  @SuppressWarnings("fallthrough")
154  public static int log10(int x, RoundingMode mode) {
155    checkPositive("x", x);
156    int logFloor = log10Floor(x);
157    int floorPow = powersOf10[logFloor];
158    switch (mode) {
159      case UNNECESSARY:
160        checkRoundingUnnecessary(x == floorPow);
161        // fall through
162      case FLOOR:
163      case DOWN:
164        return logFloor;
165      case CEILING:
166      case UP:
167        return logFloor + lessThanBranchFree(floorPow, x);
168      case HALF_DOWN:
169      case HALF_UP:
170      case HALF_EVEN:
171        // sqrt(10) is irrational, so log10(x) - logFloor is never exactly 0.5
172        return logFloor + lessThanBranchFree(halfPowersOf10[logFloor], x);
173    }
174    throw new AssertionError();
175  }
176
177  private static int log10Floor(int x) {
178    /*
179     * Based on Hacker's Delight Fig. 11-5, the two-table-lookup, branch-free implementation.
180     *
181     * The key idea is that based on the number of leading zeros (equivalently, floor(log2(x))), we
182     * can narrow the possible floor(log10(x)) values to two. For example, if floor(log2(x)) is 6,
183     * then 64 <= x < 128, so floor(log10(x)) is either 1 or 2.
184     */
185    int y = maxLog10ForLeadingZeros[Integer.numberOfLeadingZeros(x)];
186    /*
187     * y is the higher of the two possible values of floor(log10(x)). If x < 10^y, then we want the
188     * lower of the two possible values, or y - 1, otherwise, we want y.
189     */
190    return y - lessThanBranchFree(x, powersOf10[y]);
191  }
192
193  // maxLog10ForLeadingZeros[i] == floor(log10(2^(Long.SIZE - i)))
194  @VisibleForTesting
195  static final byte[] maxLog10ForLeadingZeros = {
196    9, 9, 9, 8, 8, 8, 7, 7, 7, 6, 6, 6, 6, 5, 5, 5, 4, 4, 4, 3, 3, 3, 3, 2, 2, 2, 1, 1, 1, 0, 0, 0,
197    0
198  };
199
200  @VisibleForTesting
201  static final int[] powersOf10 = {
202    1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000
203  };
204
205  // halfPowersOf10[i] = largest int less than 10^(i + 0.5)
206  @VisibleForTesting
207  static final int[] halfPowersOf10 = {
208    3, 31, 316, 3162, 31622, 316227, 3162277, 31622776, 316227766, Integer.MAX_VALUE
209  };
210
211  /**
212   * Returns {@code b} to the {@code k}th power. Even if the result overflows, it will be equal to
213   * {@code BigInteger.valueOf(b).pow(k).intValue()}. This implementation runs in {@code O(log k)}
214   * time.
215   *
216   * <p>Compare {@link #checkedPow}, which throws an {@link ArithmeticException} upon overflow.
217   *
218   * @throws IllegalArgumentException if {@code k < 0}
219   */
220  @GwtIncompatible // failing tests
221  public static int pow(int b, int k) {
222    checkNonNegative("exponent", k);
223    switch (b) {
224      case 0:
225        return (k == 0) ? 1 : 0;
226      case 1:
227        return 1;
228      case (-1):
229        return ((k & 1) == 0) ? 1 : -1;
230      case 2:
231        return (k < Integer.SIZE) ? (1 << k) : 0;
232      case (-2):
233        if (k < Integer.SIZE) {
234          return ((k & 1) == 0) ? (1 << k) : -(1 << k);
235        } else {
236          return 0;
237        }
238      default:
239        // continue below to handle the general case
240    }
241    for (int accum = 1; ; k >>= 1) {
242      switch (k) {
243        case 0:
244          return accum;
245        case 1:
246          return b * accum;
247        default:
248          accum *= ((k & 1) == 0) ? 1 : b;
249          b *= b;
250      }
251    }
252  }
253
254  /**
255   * Returns the square root of {@code x}, rounded with the specified rounding mode.
256   *
257   * @throws IllegalArgumentException if {@code x < 0}
258   * @throws ArithmeticException if {@code mode} is {@link RoundingMode#UNNECESSARY} and {@code
259   *     sqrt(x)} is not an integer
260   */
261  @GwtIncompatible // need BigIntegerMath to adequately test
262  @SuppressWarnings("fallthrough")
263  public static int sqrt(int x, RoundingMode mode) {
264    checkNonNegative("x", x);
265    int sqrtFloor = sqrtFloor(x);
266    switch (mode) {
267      case UNNECESSARY:
268        checkRoundingUnnecessary(sqrtFloor * sqrtFloor == x); // fall through
269      case FLOOR:
270      case DOWN:
271        return sqrtFloor;
272      case CEILING:
273      case UP:
274        return sqrtFloor + lessThanBranchFree(sqrtFloor * sqrtFloor, x);
275      case HALF_DOWN:
276      case HALF_UP:
277      case HALF_EVEN:
278        int halfSquare = sqrtFloor * sqrtFloor + sqrtFloor;
279        /*
280         * We wish to test whether or not x <= (sqrtFloor + 0.5)^2 = halfSquare + 0.25. Since both x
281         * and halfSquare are integers, this is equivalent to testing whether or not x <=
282         * halfSquare. (We have to deal with overflow, though.)
283         *
284         * If we treat halfSquare as an unsigned int, we know that
285         *            sqrtFloor^2 <= x < (sqrtFloor + 1)^2
286         * halfSquare - sqrtFloor <= x < halfSquare + sqrtFloor + 1
287         * so |x - halfSquare| <= sqrtFloor.  Therefore, it's safe to treat x - halfSquare as a
288         * signed int, so lessThanBranchFree is safe for use.
289         */
290        return sqrtFloor + lessThanBranchFree(halfSquare, x);
291    }
292    throw new AssertionError();
293  }
294
295  private static int sqrtFloor(int x) {
296    // There is no loss of precision in converting an int to a double, according to
297    // http://java.sun.com/docs/books/jls/third_edition/html/conversions.html#5.1.2
298    return (int) Math.sqrt(x);
299  }
300
301  /**
302   * Returns the result of dividing {@code p} by {@code q}, rounding using the specified {@code
303   * RoundingMode}.
304   *
305   * @throws ArithmeticException if {@code q == 0}, or if {@code mode == UNNECESSARY} and {@code a}
306   *     is not an integer multiple of {@code b}
307   */
308  // Whenever both tests are cheap and functional, it's faster to use &, | instead of &&, ||
309  @SuppressWarnings({"fallthrough", "ShortCircuitBoolean"})
310  public static int divide(int p, int q, RoundingMode mode) {
311    checkNotNull(mode);
312    if (q == 0) {
313      throw new ArithmeticException("/ by zero"); // for GWT
314    }
315    int div = p / q;
316    int rem = p - q * div; // equal to p % q
317
318    if (rem == 0) {
319      return div;
320    }
321
322    /*
323     * Normal Java division rounds towards 0, consistently with RoundingMode.DOWN. We just have to
324     * deal with the cases where rounding towards 0 is wrong, which typically depends on the sign of
325     * p / q.
326     *
327     * signum is 1 if p and q are both nonnegative or both negative, and -1 otherwise.
328     */
329    int signum = 1 | ((p ^ q) >> (Integer.SIZE - 1));
330    boolean increment;
331    switch (mode) {
332      case UNNECESSARY:
333        checkRoundingUnnecessary(rem == 0);
334        // fall through
335      case DOWN:
336        increment = false;
337        break;
338      case UP:
339        increment = true;
340        break;
341      case CEILING:
342        increment = signum > 0;
343        break;
344      case FLOOR:
345        increment = signum < 0;
346        break;
347      case HALF_EVEN:
348      case HALF_DOWN:
349      case HALF_UP:
350        int absRem = abs(rem);
351        int cmpRemToHalfDivisor = absRem - (abs(q) - absRem);
352        // subtracting two nonnegative ints can't overflow
353        // cmpRemToHalfDivisor has the same sign as compare(abs(rem), abs(q) / 2).
354        if (cmpRemToHalfDivisor == 0) { // exactly on the half mark
355          increment = (mode == HALF_UP || (mode == HALF_EVEN & (div & 1) != 0));
356        } else {
357          increment = cmpRemToHalfDivisor > 0; // closer to the UP value
358        }
359        break;
360      default:
361        throw new AssertionError();
362    }
363    return increment ? div + signum : div;
364  }
365
366  /**
367   * Returns {@code x mod m}, a non-negative value less than {@code m}. This differs from {@code x %
368   * m}, which might be negative.
369   *
370   * <p>For example:
371   *
372   * <pre>{@code
373   * mod(7, 4) == 3
374   * mod(-7, 4) == 1
375   * mod(-1, 4) == 3
376   * mod(-8, 4) == 0
377   * mod(8, 4) == 0
378   * }</pre>
379   *
380   * @throws ArithmeticException if {@code m <= 0}
381   * @see <a href="http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.17.3">
382   *     Remainder Operator</a>
383   */
384  public static int mod(int x, int m) {
385    if (m <= 0) {
386      throw new ArithmeticException("Modulus " + m + " must be > 0");
387    }
388    int result = x % m;
389    return (result >= 0) ? result : result + m;
390  }
391
392  /**
393   * Returns the greatest common divisor of {@code a, b}. Returns {@code 0} if {@code a == 0 && b ==
394   * 0}.
395   *
396   * @throws IllegalArgumentException if {@code a < 0} or {@code b < 0}
397   */
398  public static int gcd(int a, int b) {
399    /*
400     * The reason we require both arguments to be >= 0 is because otherwise, what do you return on
401     * gcd(0, Integer.MIN_VALUE)? BigInteger.gcd would return positive 2^31, but positive 2^31 isn't
402     * an int.
403     */
404    checkNonNegative("a", a);
405    checkNonNegative("b", b);
406    if (a == 0) {
407      // 0 % b == 0, so b divides a, but the converse doesn't hold.
408      // BigInteger.gcd is consistent with this decision.
409      return b;
410    } else if (b == 0) {
411      return a; // similar logic
412    }
413    /*
414     * Uses the binary GCD algorithm; see http://en.wikipedia.org/wiki/Binary_GCD_algorithm. This is
415     * >40% faster than the Euclidean algorithm in benchmarks.
416     */
417    int aTwos = Integer.numberOfTrailingZeros(a);
418    a >>= aTwos; // divide out all 2s
419    int bTwos = Integer.numberOfTrailingZeros(b);
420    b >>= bTwos; // divide out all 2s
421    while (a != b) { // both a, b are odd
422      // The key to the binary GCD algorithm is as follows:
423      // Both a and b are odd. Assume a > b; then gcd(a - b, b) = gcd(a, b).
424      // But in gcd(a - b, b), a - b is even and b is odd, so we can divide out powers of two.
425
426      // We bend over backwards to avoid branching, adapting a technique from
427      // http://graphics.stanford.edu/~seander/bithacks.html#IntegerMinOrMax
428
429      int delta = a - b; // can't overflow, since a and b are nonnegative
430
431      int minDeltaOrZero = delta & (delta >> (Integer.SIZE - 1));
432      // equivalent to Math.min(delta, 0)
433
434      a = delta - minDeltaOrZero - minDeltaOrZero; // sets a to Math.abs(a - b)
435      // a is now nonnegative and even
436
437      b += minDeltaOrZero; // sets b to min(old a, b)
438      a >>= Integer.numberOfTrailingZeros(a); // divide out all 2s, since 2 doesn't divide b
439    }
440    return a << min(aTwos, bTwos);
441  }
442
443  /**
444   * Returns the sum of {@code a} and {@code b}, provided it does not overflow.
445   *
446   * @throws ArithmeticException if {@code a + b} overflows in signed {@code int} arithmetic
447   */
448  public static int checkedAdd(int a, int b) {
449    long result = (long) a + b;
450    checkNoOverflow(result == (int) result, "checkedAdd", a, b);
451    return (int) result;
452  }
453
454  /**
455   * Returns the difference of {@code a} and {@code b}, provided it does not overflow.
456   *
457   * @throws ArithmeticException if {@code a - b} overflows in signed {@code int} arithmetic
458   */
459  public static int checkedSubtract(int a, int b) {
460    long result = (long) a - b;
461    checkNoOverflow(result == (int) result, "checkedSubtract", a, b);
462    return (int) result;
463  }
464
465  /**
466   * Returns the product of {@code a} and {@code b}, provided it does not overflow.
467   *
468   * @throws ArithmeticException if {@code a * b} overflows in signed {@code int} arithmetic
469   */
470  public static int checkedMultiply(int a, int b) {
471    long result = (long) a * b;
472    checkNoOverflow(result == (int) result, "checkedMultiply", a, b);
473    return (int) result;
474  }
475
476  /**
477   * Returns the {@code b} to the {@code k}th power, provided it does not overflow.
478   *
479   * <p>{@link #pow} may be faster, but does not check for overflow.
480   *
481   * @throws ArithmeticException if {@code b} to the {@code k}th power overflows in signed {@code
482   *     int} arithmetic
483   */
484  // Whenever both tests are cheap and functional, it's faster to use &, | instead of &&, ||
485  @SuppressWarnings("ShortCircuitBoolean")
486  public static int checkedPow(int b, int k) {
487    checkNonNegative("exponent", k);
488    switch (b) {
489      case 0:
490        return (k == 0) ? 1 : 0;
491      case 1:
492        return 1;
493      case (-1):
494        return ((k & 1) == 0) ? 1 : -1;
495      case 2:
496        checkNoOverflow(k < Integer.SIZE - 1, "checkedPow", b, k);
497        return 1 << k;
498      case (-2):
499        checkNoOverflow(k < Integer.SIZE, "checkedPow", b, k);
500        return ((k & 1) == 0) ? 1 << k : -1 << k;
501      default:
502        // continue below to handle the general case
503    }
504    int accum = 1;
505    while (true) {
506      switch (k) {
507        case 0:
508          return accum;
509        case 1:
510          return checkedMultiply(accum, b);
511        default:
512          if ((k & 1) != 0) {
513            accum = checkedMultiply(accum, b);
514          }
515          k >>= 1;
516          if (k > 0) {
517            checkNoOverflow(-FLOOR_SQRT_MAX_INT <= b & b <= FLOOR_SQRT_MAX_INT, "checkedPow", b, k);
518            b *= b;
519          }
520      }
521    }
522  }
523
524  /**
525   * Returns the sum of {@code a} and {@code b} unless it would overflow or underflow in which case
526   * {@code Integer.MAX_VALUE} or {@code Integer.MIN_VALUE} is returned, respectively.
527   *
528   * @since 20.0
529   */
530  public static int saturatedAdd(int a, int b) {
531    return Ints.saturatedCast((long) a + b);
532  }
533
534  /**
535   * Returns the difference of {@code a} and {@code b} unless it would overflow or underflow in
536   * which case {@code Integer.MAX_VALUE} or {@code Integer.MIN_VALUE} is returned, respectively.
537   *
538   * @since 20.0
539   */
540  public static int saturatedSubtract(int a, int b) {
541    return Ints.saturatedCast((long) a - b);
542  }
543
544  /**
545   * Returns the product of {@code a} and {@code b} unless it would overflow or underflow in which
546   * case {@code Integer.MAX_VALUE} or {@code Integer.MIN_VALUE} is returned, respectively.
547   *
548   * @since 20.0
549   */
550  public static int saturatedMultiply(int a, int b) {
551    return Ints.saturatedCast((long) a * b);
552  }
553
554  /**
555   * Returns the {@code b} to the {@code k}th power, unless it would overflow or underflow in which
556   * case {@code Integer.MAX_VALUE} or {@code Integer.MIN_VALUE} is returned, respectively.
557   *
558   * @since 20.0
559   */
560  // Whenever both tests are cheap and functional, it's faster to use &, | instead of &&, ||
561  @SuppressWarnings("ShortCircuitBoolean")
562  public static int saturatedPow(int b, int k) {
563    checkNonNegative("exponent", k);
564    switch (b) {
565      case 0:
566        return (k == 0) ? 1 : 0;
567      case 1:
568        return 1;
569      case (-1):
570        return ((k & 1) == 0) ? 1 : -1;
571      case 2:
572        if (k >= Integer.SIZE - 1) {
573          return Integer.MAX_VALUE;
574        }
575        return 1 << k;
576      case (-2):
577        if (k >= Integer.SIZE) {
578          return Integer.MAX_VALUE + (k & 1);
579        }
580        return ((k & 1) == 0) ? 1 << k : -1 << k;
581      default:
582        // continue below to handle the general case
583    }
584    int accum = 1;
585    // if b is negative and k is odd then the limit is MIN otherwise the limit is MAX
586    int limit = Integer.MAX_VALUE + ((b >>> Integer.SIZE - 1) & (k & 1));
587    while (true) {
588      switch (k) {
589        case 0:
590          return accum;
591        case 1:
592          return saturatedMultiply(accum, b);
593        default:
594          if ((k & 1) != 0) {
595            accum = saturatedMultiply(accum, b);
596          }
597          k >>= 1;
598          if (k > 0) {
599            if (-FLOOR_SQRT_MAX_INT > b | b > FLOOR_SQRT_MAX_INT) {
600              return limit;
601            }
602            b *= b;
603          }
604      }
605    }
606  }
607
608  @VisibleForTesting static final int FLOOR_SQRT_MAX_INT = 46340;
609
610  /**
611   * Returns {@code n!}, that is, the product of the first {@code n} positive integers, {@code 1} if
612   * {@code n == 0}, or {@link Integer#MAX_VALUE} if the result does not fit in a {@code int}.
613   *
614   * @throws IllegalArgumentException if {@code n < 0}
615   */
616  public static int factorial(int n) {
617    checkNonNegative("n", n);
618    return (n < factorials.length) ? factorials[n] : Integer.MAX_VALUE;
619  }
620
621  private static final int[] factorials = {
622    1,
623    1,
624    1 * 2,
625    1 * 2 * 3,
626    1 * 2 * 3 * 4,
627    1 * 2 * 3 * 4 * 5,
628    1 * 2 * 3 * 4 * 5 * 6,
629    1 * 2 * 3 * 4 * 5 * 6 * 7,
630    1 * 2 * 3 * 4 * 5 * 6 * 7 * 8,
631    1 * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9,
632    1 * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10,
633    1 * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11,
634    1 * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12
635  };
636
637  /**
638   * Returns {@code n} choose {@code k}, also known as the binomial coefficient of {@code n} and
639   * {@code k}, or {@link Integer#MAX_VALUE} if the result does not fit in an {@code int}.
640   *
641   * @throws IllegalArgumentException if {@code n < 0}, {@code k < 0} or {@code k > n}
642   */
643  public static int binomial(int n, int k) {
644    checkNonNegative("n", n);
645    checkNonNegative("k", k);
646    checkArgument(k <= n, "k (%s) > n (%s)", k, n);
647    if (k > (n >> 1)) {
648      k = n - k;
649    }
650    if (k >= biggestBinomials.length || n > biggestBinomials[k]) {
651      return Integer.MAX_VALUE;
652    }
653    switch (k) {
654      case 0:
655        return 1;
656      case 1:
657        return n;
658      default:
659        long result = 1;
660        for (int i = 0; i < k; i++) {
661          result *= n - i;
662          result /= i + 1;
663        }
664        return (int) result;
665    }
666  }
667
668  // binomial(biggestBinomials[k], k) fits in an int, but not binomial(biggestBinomials[k]+1,k).
669  @VisibleForTesting
670  static int[] biggestBinomials = {
671    Integer.MAX_VALUE,
672    Integer.MAX_VALUE,
673    65536,
674    2345,
675    477,
676    193,
677    110,
678    75,
679    58,
680    49,
681    43,
682    39,
683    37,
684    35,
685    34,
686    34,
687    33
688  };
689
690  /**
691   * Returns the arithmetic mean of {@code x} and {@code y}, rounded towards negative infinity. This
692   * method is overflow resilient.
693   *
694   * @since 14.0
695   */
696  public static int mean(int x, int y) {
697    // Efficient method for computing the arithmetic mean.
698    // The alternative (x + y) / 2 fails for large values.
699    // The alternative (x + y) >>> 1 fails for negative values.
700    return (x & y) + ((x ^ y) >> 1);
701  }
702
703  /**
704   * Returns {@code true} if {@code n} is a <a
705   * href="http://mathworld.wolfram.com/PrimeNumber.html">prime number</a>: an integer <i>greater
706   * than one</i> that cannot be factored into a product of <i>smaller</i> positive integers.
707   * Returns {@code false} if {@code n} is zero, one, or a composite number (one which <i>can</i> be
708   * factored into smaller positive integers).
709   *
710   * <p>To test larger numbers, use {@link LongMath#isPrime} or {@link BigInteger#isProbablePrime}.
711   *
712   * @throws IllegalArgumentException if {@code n} is negative
713   * @since 20.0
714   */
715  @GwtIncompatible // TODO
716  public static boolean isPrime(int n) {
717    return LongMath.isPrime(n);
718  }
719
720  private IntMath() {}
721}