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