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