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