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