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 int}. 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 long} and for {@link BigInteger} can be found in
045 * {@link LongMath} and {@link BigIntegerMath} respectively.  For other common operations on
046 * {@code int} values, see {@link com.google.common.primitives.Ints}.
047 *
048 * @author Louis Wasserman
049 * @since 11.0
050 */
051@GwtCompatible(emulated = true)
052public final class IntMath {
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 Integer.bitCount(x) == 1}, because
059   * {@code Integer.bitCount(Integer.MIN_VALUE) == 1}, but {@link Integer#MIN_VALUE} is not a power
060   * of two.
061   */
062  public static boolean isPowerOfTwo(int x) {
063    return x > 0 & (x & (x - 1)) == 0;
064  }
065
066  /**
067   * Returns the base-2 logarithm of {@code x}, rounded according to the specified rounding mode.
068   *
069   * @throws IllegalArgumentException if {@code x <= 0}
070   * @throws ArithmeticException if {@code mode} is {@link RoundingMode#UNNECESSARY} and {@code x}
071   *         is not a power of two
072   */
073  @SuppressWarnings("fallthrough")
074  // TODO(kevinb): remove after this warning is disabled globally
075  public static int log2(int x, RoundingMode mode) {
076    checkPositive("x", x);
077    switch (mode) {
078      case UNNECESSARY:
079        checkRoundingUnnecessary(isPowerOfTwo(x));
080        // fall through
081      case DOWN:
082      case FLOOR:
083        return (Integer.SIZE - 1) - Integer.numberOfLeadingZeros(x);
084
085      case UP:
086      case CEILING:
087        return Integer.SIZE - Integer.numberOfLeadingZeros(x - 1);
088
089      case HALF_DOWN:
090      case HALF_UP:
091      case HALF_EVEN:
092        // Since sqrt(2) is irrational, log2(x) - logFloor cannot be exactly 0.5
093        int leadingZeros = Integer.numberOfLeadingZeros(x);
094        int cmp = MAX_POWER_OF_SQRT2_UNSIGNED >>> leadingZeros;
095          // floor(2^(logFloor + 0.5))
096        int logFloor = (Integer.SIZE - 1) - leadingZeros;
097        return (x <= cmp) ? logFloor : logFloor + 1;
098
099      default:
100        throw new AssertionError();
101    }
102  }
103
104  /** The biggest half power of two that can fit in an unsigned int. */
105  @VisibleForTesting static final int MAX_POWER_OF_SQRT2_UNSIGNED = 0xB504F333;
106
107  /**
108   * Returns the base-10 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 ten
113   */
114  @GwtIncompatible("need BigIntegerMath to adequately test")
115  @SuppressWarnings("fallthrough")
116  public static int log10(int x, RoundingMode mode) {
117    checkPositive("x", x);
118    int logFloor = log10Floor(x);
119    int floorPow = powersOf10[logFloor];
120    switch (mode) {
121      case UNNECESSARY:
122        checkRoundingUnnecessary(x == floorPow);
123        // fall through
124      case FLOOR:
125      case DOWN:
126        return logFloor;
127      case CEILING:
128      case UP:
129        return (x == floorPow) ? logFloor : logFloor + 1;
130      case HALF_DOWN:
131      case HALF_UP:
132      case HALF_EVEN:
133        // sqrt(10) is irrational, so log10(x) - logFloor is never exactly 0.5
134        return (x <= halfPowersOf10[logFloor]) ? logFloor : logFloor + 1;
135      default:
136        throw new AssertionError();
137    }
138  }
139
140  private static int log10Floor(int x) {
141    /*
142     * Based on Hacker's Delight Fig. 11-5, the two-table-lookup, branch-free implementation.
143     *
144     * The key idea is that based on the number of leading zeros (equivalently, floor(log2(x))),
145     * we can narrow the possible floor(log10(x)) values to two.  For example, if floor(log2(x))
146     * is 6, then 64 <= x < 128, so floor(log10(x)) is either 1 or 2.
147     */
148    int y = maxLog10ForLeadingZeros[Integer.numberOfLeadingZeros(x)];
149    // y is the higher of the two possible values of floor(log10(x))
150
151    int sgn = (x - powersOf10[y]) >>> (Integer.SIZE - 1);
152    /*
153     * 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
154     * want the lower of the two possible values, or y - 1, otherwise, we want y.
155     */
156    return y - sgn;
157  }
158
159  // maxLog10ForLeadingZeros[i] == floor(log10(2^(Long.SIZE - i)))
160  @VisibleForTesting static final byte[] maxLog10ForLeadingZeros = {9, 9, 9, 8, 8, 8,
161    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, 0};
162
163  @VisibleForTesting static final int[] powersOf10 = {1, 10, 100, 1000, 10000,
164    100000, 1000000, 10000000, 100000000, 1000000000};
165
166  // halfPowersOf10[i] = largest int less than 10^(i + 0.5)
167  @VisibleForTesting static final int[] halfPowersOf10 =
168      {3, 31, 316, 3162, 31622, 316227, 3162277, 31622776, 316227766, Integer.MAX_VALUE};
169
170  /**
171   * Returns {@code b} to the {@code k}th power. Even if the result overflows, it will be equal to
172   * {@code BigInteger.valueOf(b).pow(k).intValue()}. This implementation runs in {@code O(log k)}
173   * time.
174   *
175   * <p>Compare {@link #checkedPow}, which throws an {@link ArithmeticException} upon overflow.
176   *
177   * @throws IllegalArgumentException if {@code k < 0}
178   */
179  @GwtIncompatible("failing tests")
180  public static int pow(int b, int k) {
181    checkNonNegative("exponent", k);
182    switch (b) {
183      case 0:
184        return (k == 0) ? 1 : 0;
185      case 1:
186        return 1;
187      case (-1):
188        return ((k & 1) == 0) ? 1 : -1;
189      case 2:
190        return (k < Integer.SIZE) ? (1 << k) : 0;
191      case (-2):
192        if (k < Integer.SIZE) {
193          return ((k & 1) == 0) ? (1 << k) : -(1 << k);
194        } else {
195          return 0;
196        }
197      default:
198        // continue below to handle the general case
199    }
200    for (int accum = 1;; k >>= 1) {
201      switch (k) {
202        case 0:
203          return accum;
204        case 1:
205          return b * accum;
206        default:
207          accum *= ((k & 1) == 0) ? 1 : b;
208          b *= b;
209      }
210    }
211  }
212
213  /**
214   * Returns the square root of {@code x}, rounded with the specified rounding mode.
215   *
216   * @throws IllegalArgumentException if {@code x < 0}
217   * @throws ArithmeticException if {@code mode} is {@link RoundingMode#UNNECESSARY} and
218   *         {@code sqrt(x)} is not an integer
219   */
220  @GwtIncompatible("need BigIntegerMath to adequately test")
221  @SuppressWarnings("fallthrough")
222  public static int sqrt(int x, RoundingMode mode) {
223    checkNonNegative("x", x);
224    int sqrtFloor = sqrtFloor(x);
225    switch (mode) {
226      case UNNECESSARY:
227        checkRoundingUnnecessary(sqrtFloor * sqrtFloor == x); // fall through
228      case FLOOR:
229      case DOWN:
230        return sqrtFloor;
231      case CEILING:
232      case UP:
233        return (sqrtFloor * sqrtFloor == x) ? sqrtFloor : sqrtFloor + 1;
234      case HALF_DOWN:
235      case HALF_UP:
236      case HALF_EVEN:
237        int halfSquare = sqrtFloor * sqrtFloor + sqrtFloor;
238        /*
239         * We wish to test whether or not x <= (sqrtFloor + 0.5)^2 = halfSquare + 0.25.
240         * Since both x and halfSquare are integers, this is equivalent to testing whether or not
241         * x <= halfSquare.  (We have to deal with overflow, though.)
242         */
243        return (x <= halfSquare | halfSquare < 0) ? sqrtFloor : sqrtFloor + 1;
244      default:
245        throw new AssertionError();
246    }
247  }
248
249  private static int sqrtFloor(int x) {
250    // There is no loss of precision in converting an int to a double, according to
251    // http://java.sun.com/docs/books/jls/third_edition/html/conversions.html#5.1.2
252    return (int) Math.sqrt(x);
253  }
254
255  /**
256   * Returns the result of dividing {@code p} by {@code q}, rounding using the specified
257   * {@code RoundingMode}.
258   *
259   * @throws ArithmeticException if {@code q == 0}, or if {@code mode == UNNECESSARY} and {@code a}
260   *         is not an integer multiple of {@code b}
261   */
262  @SuppressWarnings("fallthrough")
263  public static int divide(int p, int q, RoundingMode mode) {
264    checkNotNull(mode);
265    if (q == 0) {
266      throw new ArithmeticException("/ by zero"); // for GWT
267    }
268    int div = p / q;
269    int rem = p - q * div; // equal to p % q
270
271    if (rem == 0) {
272      return div;
273    }
274
275    /*
276     * Normal Java division rounds towards 0, consistently with RoundingMode.DOWN. We just have to
277     * deal with the cases where rounding towards 0 is wrong, which typically depends on the sign of
278     * p / q.
279     *
280     * signum is 1 if p and q are both nonnegative or both negative, and -1 otherwise.
281     */
282    int signum = 1 | ((p ^ q) >> (Integer.SIZE - 1));
283    boolean increment;
284    switch (mode) {
285      case UNNECESSARY:
286        checkRoundingUnnecessary(rem == 0);
287        // fall through
288      case DOWN:
289        increment = false;
290        break;
291      case UP:
292        increment = true;
293        break;
294      case CEILING:
295        increment = signum > 0;
296        break;
297      case FLOOR:
298        increment = signum < 0;
299        break;
300      case HALF_EVEN:
301      case HALF_DOWN:
302      case HALF_UP:
303        int absRem = abs(rem);
304        int cmpRemToHalfDivisor = absRem - (abs(q) - absRem);
305        // subtracting two nonnegative ints can't overflow
306        // cmpRemToHalfDivisor has the same sign as compare(abs(rem), abs(q) / 2).
307        if (cmpRemToHalfDivisor == 0) { // exactly on the half mark
308          increment = (mode == HALF_UP || (mode == HALF_EVEN & (div & 1) != 0));
309        } else {
310          increment = cmpRemToHalfDivisor > 0; // closer to the UP value
311        }
312        break;
313      default:
314        throw new AssertionError();
315    }
316    return increment ? div + signum : div;
317  }
318
319  /**
320   * Returns {@code x mod m}. This differs from {@code x % m} in that it always returns a
321   * non-negative result.
322   *
323   * <p>For example:<pre> {@code
324   *
325   * mod(7, 4) == 3
326   * mod(-7, 4) == 1
327   * mod(-1, 4) == 3
328   * mod(-8, 4) == 0
329   * mod(8, 4) == 0}</pre>
330   *
331   * @throws ArithmeticException if {@code m <= 0}
332   */
333  public static int mod(int x, int m) {
334    if (m <= 0) {
335      throw new ArithmeticException("Modulus " + m + " must be > 0");
336    }
337    int result = x % m;
338    return (result >= 0) ? result : result + m;
339  }
340
341  /**
342   * Returns the greatest common divisor of {@code a, b}. Returns {@code 0} if
343   * {@code a == 0 && b == 0}.
344   *
345   * @throws IllegalArgumentException if {@code a < 0} or {@code b < 0}
346   */
347  public static int gcd(int a, int b) {
348    /*
349     * The reason we require both arguments to be >= 0 is because otherwise, what do you return on
350     * gcd(0, Integer.MIN_VALUE)? BigInteger.gcd would return positive 2^31, but positive 2^31
351     * isn't an int.
352     */
353    checkNonNegative("a", a);
354    checkNonNegative("b", b);
355    if (a == 0) {
356      // 0 % b == 0, so b divides a, but the converse doesn't hold.
357      // BigInteger.gcd is consistent with this decision.
358      return b;
359    } else if (b == 0) {
360      return a; // similar logic
361    }
362    /*
363     * Uses the binary GCD algorithm; see http://en.wikipedia.org/wiki/Binary_GCD_algorithm.
364     * This is >40% faster than the Euclidean algorithm in benchmarks.
365     */
366    int aTwos = Integer.numberOfTrailingZeros(a);
367    a >>= aTwos; // divide out all 2s
368    int bTwos = Integer.numberOfTrailingZeros(b);
369    b >>= bTwos; // divide out all 2s
370    while (a != b) { // both a, b are odd
371      // The key to the binary GCD algorithm is as follows:
372      // Both a and b are odd.  Assume a > b; then gcd(a - b, b) = gcd(a, b).
373      // But in gcd(a - b, b), a - b is even and b is odd, so we can divide out powers of two.
374
375      // We bend over backwards to avoid branching, adapting a technique from
376      // http://graphics.stanford.edu/~seander/bithacks.html#IntegerMinOrMax
377
378      int delta = a - b; // can't overflow, since a and b are nonnegative
379
380      int minDeltaOrZero = delta & (delta >> (Integer.SIZE - 1));
381      // equivalent to Math.min(delta, 0)
382
383      a = delta - minDeltaOrZero - minDeltaOrZero; // sets a to Math.abs(a - b)
384      // a is now nonnegative and even
385
386      b += minDeltaOrZero; // sets b to min(old a, b)
387      a >>= Integer.numberOfTrailingZeros(a); // divide out all 2s, since 2 doesn't divide b
388    }
389    return a << min(aTwos, bTwos);
390  }
391
392  /**
393   * Returns the sum of {@code a} and {@code b}, provided it does not overflow.
394   *
395   * @throws ArithmeticException if {@code a + b} overflows in signed {@code int} arithmetic
396   */
397  public static int checkedAdd(int a, int b) {
398    long result = (long) a + b;
399    checkNoOverflow(result == (int) result);
400    return (int) result;
401  }
402
403  /**
404   * Returns the difference of {@code a} and {@code b}, provided it does not overflow.
405   *
406   * @throws ArithmeticException if {@code a - b} overflows in signed {@code int} arithmetic
407   */
408  public static int checkedSubtract(int a, int b) {
409    long result = (long) a - b;
410    checkNoOverflow(result == (int) result);
411    return (int) result;
412  }
413
414  /**
415   * Returns the product of {@code a} and {@code b}, provided it does not overflow.
416   *
417   * @throws ArithmeticException if {@code a * b} overflows in signed {@code int} arithmetic
418   */
419  public static int checkedMultiply(int a, int b) {
420    long result = (long) a * b;
421    checkNoOverflow(result == (int) result);
422    return (int) result;
423  }
424
425  /**
426   * Returns the {@code b} to the {@code k}th power, provided it does not overflow.
427   *
428   * <p>{@link #pow} may be faster, but does not check for overflow.
429   *
430   * @throws ArithmeticException if {@code b} to the {@code k}th power overflows in signed
431   *         {@code int} arithmetic
432   */
433  public static int checkedPow(int b, int k) {
434    checkNonNegative("exponent", k);
435    switch (b) {
436      case 0:
437        return (k == 0) ? 1 : 0;
438      case 1:
439        return 1;
440      case (-1):
441        return ((k & 1) == 0) ? 1 : -1;
442      case 2:
443        checkNoOverflow(k < Integer.SIZE - 1);
444        return 1 << k;
445      case (-2):
446        checkNoOverflow(k < Integer.SIZE);
447        return ((k & 1) == 0) ? 1 << k : -1 << k;
448      default:
449        // continue below to handle the general case
450    }
451    int accum = 1;
452    while (true) {
453      switch (k) {
454        case 0:
455          return accum;
456        case 1:
457          return checkedMultiply(accum, b);
458        default:
459          if ((k & 1) != 0) {
460            accum = checkedMultiply(accum, b);
461          }
462          k >>= 1;
463          if (k > 0) {
464            checkNoOverflow(-FLOOR_SQRT_MAX_INT <= b & b <= FLOOR_SQRT_MAX_INT);
465            b *= b;
466          }
467      }
468    }
469  }
470
471  @VisibleForTesting static final int FLOOR_SQRT_MAX_INT = 46340;
472
473  /**
474   * Returns {@code n!}, that is, the product of the first {@code n} positive
475   * integers, {@code 1} if {@code n == 0}, or {@link Integer#MAX_VALUE} if the
476   * result does not fit in a {@code int}.
477   *
478   * @throws IllegalArgumentException if {@code n < 0}
479   */
480  public static int factorial(int n) {
481    checkNonNegative("n", n);
482    return (n < factorials.length) ? factorials[n] : Integer.MAX_VALUE;
483  }
484
485  private static final int[] factorials = {
486      1,
487      1,
488      1 * 2,
489      1 * 2 * 3,
490      1 * 2 * 3 * 4,
491      1 * 2 * 3 * 4 * 5,
492      1 * 2 * 3 * 4 * 5 * 6,
493      1 * 2 * 3 * 4 * 5 * 6 * 7,
494      1 * 2 * 3 * 4 * 5 * 6 * 7 * 8,
495      1 * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9,
496      1 * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10,
497      1 * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11,
498      1 * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12};
499
500  /**
501   * Returns {@code n} choose {@code k}, also known as the binomial coefficient of {@code n} and
502   * {@code k}, or {@link Integer#MAX_VALUE} if the result does not fit in an {@code int}.
503   *
504   * @throws IllegalArgumentException if {@code n < 0}, {@code k < 0} or {@code k > n}
505   */
506  @GwtIncompatible("need BigIntegerMath to adequately test")
507  public static int binomial(int n, int k) {
508    checkNonNegative("n", n);
509    checkNonNegative("k", k);
510    checkArgument(k <= n, "k (%s) > n (%s)", k, n);
511    if (k > (n >> 1)) {
512      k = n - k;
513    }
514    if (k >= biggestBinomials.length || n > biggestBinomials[k]) {
515      return Integer.MAX_VALUE;
516    }
517    switch (k) {
518      case 0:
519        return 1;
520      case 1:
521        return n;
522      default:
523        long result = 1;
524        for (int i = 0; i < k; i++) {
525          result *= n - i;
526          result /= i + 1;
527        }
528        return (int) result;
529    }
530  }
531
532  // binomial(biggestBinomials[k], k) fits in an int, but not binomial(biggestBinomials[k]+1,k).
533  @VisibleForTesting static int[] biggestBinomials = {
534    Integer.MAX_VALUE,
535    Integer.MAX_VALUE,
536    65536,
537    2345,
538    477,
539    193,
540    110,
541    75,
542    58,
543    49,
544    43,
545    39,
546    37,
547    35,
548    34,
549    34,
550    33
551  };
552
553  /**
554   * Returns the arithmetic mean of {@code x} and {@code y}, rounded towards
555   * negative infinity. This method is overflow resilient.
556   *
557   * @since 14.0
558   */
559  public static int mean(int x, int y) {
560    // Efficient method for computing the arithmetic mean.
561    // The alternative (x + y) / 2 fails for large values.
562    // The alternative (x + y) >>> 1 fails for negative values.
563    return (x & y) + ((x ^ y) >> 1);
564  }
565
566  private IntMath() {}
567}