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 long}. 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 int} and for {@link BigInteger} can be found in 045 * {@link IntMath} and {@link BigIntegerMath} respectively. For other common operations on 046 * {@code long} values, see {@link com.google.common.primitives.Longs}. 047 * 048 * @author Louis Wasserman 049 * @since 11.0 050 */ 051@GwtCompatible(emulated = true) 052public final class LongMath { 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 Long.bitCount(x) == 1}, because 059 * {@code Long.bitCount(Long.MIN_VALUE) == 1}, but {@link Long#MIN_VALUE} is not a power of two. 060 */ 061 public static boolean isPowerOfTwo(long x) { 062 return x > 0 & (x & (x - 1)) == 0; 063 } 064 065 /** 066 * Returns the base-2 logarithm of {@code x}, rounded according to the specified rounding mode. 067 * 068 * @throws IllegalArgumentException if {@code x <= 0} 069 * @throws ArithmeticException if {@code mode} is {@link RoundingMode#UNNECESSARY} and {@code x} 070 * is not a power of two 071 */ 072 @SuppressWarnings("fallthrough") 073 public static int log2(long x, RoundingMode mode) { 074 checkPositive("x", x); 075 switch (mode) { 076 case UNNECESSARY: 077 checkRoundingUnnecessary(isPowerOfTwo(x)); 078 // fall through 079 case DOWN: 080 case FLOOR: 081 return (Long.SIZE - 1) - Long.numberOfLeadingZeros(x); 082 083 case UP: 084 case CEILING: 085 return Long.SIZE - Long.numberOfLeadingZeros(x - 1); 086 087 case HALF_DOWN: 088 case HALF_UP: 089 case HALF_EVEN: 090 // Since sqrt(2) is irrational, log2(x) - logFloor cannot be exactly 0.5 091 int leadingZeros = Long.numberOfLeadingZeros(x); 092 long cmp = MAX_POWER_OF_SQRT2_UNSIGNED >>> leadingZeros; 093 // floor(2^(logFloor + 0.5)) 094 int logFloor = (Long.SIZE - 1) - leadingZeros; 095 return (x <= cmp) ? logFloor : logFloor + 1; 096 097 default: 098 throw new AssertionError("impossible"); 099 } 100 } 101 102 /** The biggest half power of two that fits into an unsigned long */ 103 @VisibleForTesting static final long MAX_POWER_OF_SQRT2_UNSIGNED = 0xB504F333F9DE6484L; 104 105 /** 106 * Returns the base-10 logarithm of {@code x}, rounded according to the specified rounding mode. 107 * 108 * @throws IllegalArgumentException if {@code x <= 0} 109 * @throws ArithmeticException if {@code mode} is {@link RoundingMode#UNNECESSARY} and {@code x} 110 * is not a power of ten 111 */ 112 @GwtIncompatible("TODO") 113 @SuppressWarnings("fallthrough") 114 public static int log10(long x, RoundingMode mode) { 115 checkPositive("x", x); 116 if (fitsInInt(x)) { 117 return IntMath.log10((int) x, mode); 118 } 119 int logFloor = log10Floor(x); 120 long floorPow = powersOf10[logFloor]; 121 switch (mode) { 122 case UNNECESSARY: 123 checkRoundingUnnecessary(x == floorPow); 124 // fall through 125 case FLOOR: 126 case DOWN: 127 return logFloor; 128 case CEILING: 129 case UP: 130 return (x == floorPow) ? logFloor : logFloor + 1; 131 case HALF_DOWN: 132 case HALF_UP: 133 case HALF_EVEN: 134 // sqrt(10) is irrational, so log10(x)-logFloor is never exactly 0.5 135 return (x <= halfPowersOf10[logFloor]) ? logFloor : logFloor + 1; 136 default: 137 throw new AssertionError(); 138 } 139 } 140 141 @GwtIncompatible("TODO") 142 static int log10Floor(long x) { 143 /* 144 * Based on Hacker's Delight Fig. 11-5, the two-table-lookup, branch-free implementation. 145 * 146 * The key idea is that based on the number of leading zeros (equivalently, floor(log2(x))), 147 * we can narrow the possible floor(log10(x)) values to two. For example, if floor(log2(x)) 148 * is 6, then 64 <= x < 128, so floor(log10(x)) is either 1 or 2. 149 */ 150 int y = maxLog10ForLeadingZeros[Long.numberOfLeadingZeros(x)]; 151 // y is the higher of the two possible values of floor(log10(x)) 152 153 long sgn = (x - powersOf10[y]) >>> (Long.SIZE - 1); 154 /* 155 * 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 156 * want the lower of the two possible values, or y - 1, otherwise, we want y. 157 */ 158 return y - (int) sgn; 159 } 160 161 // maxLog10ForLeadingZeros[i] == floor(log10(2^(Long.SIZE - i))) 162 @VisibleForTesting static final byte[] maxLog10ForLeadingZeros = { 163 19, 18, 18, 18, 18, 17, 17, 17, 16, 16, 16, 15, 15, 15, 15, 14, 14, 14, 13, 13, 13, 12, 12, 164 12, 12, 11, 11, 11, 10, 10, 10, 9, 9, 9, 9, 8, 8, 8, 7, 7, 7, 6, 6, 6, 6, 5, 5, 5, 4, 4, 4, 165 3, 3, 3, 3, 2, 2, 2, 1, 1, 1, 0, 0, 0 }; 166 167 @GwtIncompatible("TODO") 168 @VisibleForTesting 169 static final long[] powersOf10 = { 170 1L, 171 10L, 172 100L, 173 1000L, 174 10000L, 175 100000L, 176 1000000L, 177 10000000L, 178 100000000L, 179 1000000000L, 180 10000000000L, 181 100000000000L, 182 1000000000000L, 183 10000000000000L, 184 100000000000000L, 185 1000000000000000L, 186 10000000000000000L, 187 100000000000000000L, 188 1000000000000000000L 189 }; 190 191 // halfPowersOf10[i] = largest long less than 10^(i + 0.5) 192 @GwtIncompatible("TODO") 193 @VisibleForTesting 194 static final long[] halfPowersOf10 = { 195 3L, 196 31L, 197 316L, 198 3162L, 199 31622L, 200 316227L, 201 3162277L, 202 31622776L, 203 316227766L, 204 3162277660L, 205 31622776601L, 206 316227766016L, 207 3162277660168L, 208 31622776601683L, 209 316227766016837L, 210 3162277660168379L, 211 31622776601683793L, 212 316227766016837933L, 213 3162277660168379331L 214 }; 215 216 /** 217 * Returns {@code b} to the {@code k}th power. Even if the result overflows, it will be equal to 218 * {@code BigInteger.valueOf(b).pow(k).longValue()}. This implementation runs in {@code O(log k)} 219 * time. 220 * 221 * @throws IllegalArgumentException if {@code k < 0} 222 */ 223 @GwtIncompatible("TODO") 224 public static long pow(long b, int k) { 225 checkNonNegative("exponent", k); 226 if (-2 <= b && b <= 2) { 227 switch ((int) 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 < Long.SIZE) ? 1L << k : 0; 236 case (-2): 237 if (k < Long.SIZE) { 238 return ((k & 1) == 0) ? 1L << k : -(1L << k); 239 } else { 240 return 0; 241 } 242 } 243 } 244 for (long accum = 1;; k >>= 1) { 245 switch (k) { 246 case 0: 247 return accum; 248 case 1: 249 return accum * b; 250 default: 251 accum *= ((k & 1) == 0) ? 1 : b; 252 b *= b; 253 } 254 } 255 } 256 257 /** 258 * Returns the square root of {@code x}, rounded with the specified rounding mode. 259 * 260 * @throws IllegalArgumentException if {@code x < 0} 261 * @throws ArithmeticException if {@code mode} is {@link RoundingMode#UNNECESSARY} and 262 * {@code sqrt(x)} is not an integer 263 */ 264 @GwtIncompatible("TODO") 265 @SuppressWarnings("fallthrough") 266 public static long sqrt(long x, RoundingMode mode) { 267 checkNonNegative("x", x); 268 if (fitsInInt(x)) { 269 return IntMath.sqrt((int) x, mode); 270 } 271 long sqrtFloor = sqrtFloor(x); 272 switch (mode) { 273 case UNNECESSARY: 274 checkRoundingUnnecessary(sqrtFloor * sqrtFloor == x); // fall through 275 case FLOOR: 276 case DOWN: 277 return sqrtFloor; 278 case CEILING: 279 case UP: 280 return (sqrtFloor * sqrtFloor == x) ? sqrtFloor : sqrtFloor + 1; 281 case HALF_DOWN: 282 case HALF_UP: 283 case HALF_EVEN: 284 long halfSquare = sqrtFloor * sqrtFloor + sqrtFloor; 285 /* 286 * We wish to test whether or not x <= (sqrtFloor + 0.5)^2 = halfSquare + 0.25. Since both 287 * x and halfSquare are integers, this is equivalent to testing whether or not x <= 288 * halfSquare. (We have to deal with overflow, though.) 289 */ 290 return (halfSquare >= x | halfSquare < 0) ? sqrtFloor : sqrtFloor + 1; 291 default: 292 throw new AssertionError(); 293 } 294 } 295 296 @GwtIncompatible("TODO") 297 private static long sqrtFloor(long x) { 298 long guess = (long) Math.sqrt(x); 299 /* 300 * Lemma: For all a, b, if |a - b| <= 1, then |floor(a) - floor(b)| <= 1. 301 * 302 * Proof: 303 * -1 <= a - b <= 1 304 * b - 1 <= a <= b + 1 305 * floor(b - 1) <= floor(a) <= floor(b + 1) 306 * floor(b) - 1 <= floor(a) <= floor(b) + 1 307 * -1 <= floor(a) - floor(b) <= 1 308 * 309 * Theorem: |floor(sqrt(x)) - guess| <= 1. 310 * 311 * Proof: By the lemma, it suffices to show that |sqrt(x) - Math.sqrt(x)| <= 1. 312 * We consider two cases: x <= 2^53 and x > 2^53. 313 * 314 * If x <= 2^53, then x is exactly representable as a double, so the only error is in rounding 315 * sqrt(x) to a double, which introduces at most 2^-52 relative error. Since sqrt(x) < 2^27, 316 * the absolute error is at most 2^(27-52) = 2^-25 < 1. 317 * 318 * Otherwise, x > 2^53. The rounding error introduced by casting x to a double is at most 319 * 2^63 * 2^-52 = 2^11. Noting that sqrt(x) > 2^26, 320 * 321 * sqrt(x) - 0.5 = sqrt((sqrt(x) - 0.5)^2) 322 * = sqrt(x - sqrt(x) + 0.25) 323 * < sqrt(x - 2^26 + 0.25) 324 * < sqrt(x - 2^11) 325 * <= sqrt((double) x) 326 * sqrt(x) + 0.5 = sqrt((sqrt(x) + 0.5)^2) 327 * = sqrt(x + sqrt(x) + 0.25) 328 * > sqrt(x + 2^26 + 0.25) 329 * > sqrt(x + 2^11) 330 * >= sqrt((double) x) 331 * sqrt(x) - 0.5 < sqrt((double) x) < sqrt(x) + 0.5 332 * 333 * Math.sqrt((double) x) is obtained by rounding sqrt((double) x) to a double, increasing the 334 * error by at most 2^-52 * sqrt(x) <= 2^(32 - 52) <= 2^-20, so clearly 335 * 336 * sqrt(x) - 0.5 - 2^-20 <= Math.sqrt((double) x) <= sqrt(x) + 0.5 + 2^-20 337 * 338 * Therefore, |sqrt(x) - Math.sqrt((double) x)| <= 1, so 339 * |floor(sqrt(x)) - (long) Math.sqrt((double) x)| <= 1 340 * as desired. 341 */ 342 long guessSquared = guess * guess; 343 if (x - guessSquared >= guess + guess + 1) { 344 // The condition is equivalent to x >= (guess + 1) * (guess + 1), but doesn't overflow. 345 guess++; 346 } else if (x < guessSquared) { 347 guess--; 348 } 349 return guess; 350 } 351 352 /** 353 * Returns the result of dividing {@code p} by {@code q}, rounding using the specified 354 * {@code RoundingMode}. 355 * 356 * @throws ArithmeticException if {@code q == 0}, or if {@code mode == UNNECESSARY} and {@code a} 357 * is not an integer multiple of {@code b} 358 */ 359 @GwtIncompatible("TODO") 360 @SuppressWarnings("fallthrough") 361 public static long divide(long p, long q, RoundingMode mode) { 362 checkNotNull(mode); 363 long div = p / q; // throws if q == 0 364 long rem = p - q * div; // equals p % q 365 366 if (rem == 0) { 367 return div; 368 } 369 370 /* 371 * Normal Java division rounds towards 0, consistently with RoundingMode.DOWN. We just have to 372 * deal with the cases where rounding towards 0 is wrong, which typically depends on the sign of 373 * p / q. 374 * 375 * signum is 1 if p and q are both nonnegative or both negative, and -1 otherwise. 376 */ 377 int signum = 1 | (int) ((p ^ q) >> (Long.SIZE - 1)); 378 boolean increment; 379 switch (mode) { 380 case UNNECESSARY: 381 checkRoundingUnnecessary(rem == 0); 382 // fall through 383 case DOWN: 384 increment = false; 385 break; 386 case UP: 387 increment = true; 388 break; 389 case CEILING: 390 increment = signum > 0; 391 break; 392 case FLOOR: 393 increment = signum < 0; 394 break; 395 case HALF_EVEN: 396 case HALF_DOWN: 397 case HALF_UP: 398 long absRem = abs(rem); 399 long cmpRemToHalfDivisor = absRem - (abs(q) - absRem); 400 // subtracting two nonnegative longs can't overflow 401 // cmpRemToHalfDivisor has the same sign as compare(abs(rem), abs(q) / 2). 402 if (cmpRemToHalfDivisor == 0) { // exactly on the half mark 403 increment = (mode == HALF_UP | (mode == HALF_EVEN & (div & 1) != 0)); 404 } else { 405 increment = cmpRemToHalfDivisor > 0; // closer to the UP value 406 } 407 break; 408 default: 409 throw new AssertionError(); 410 } 411 return increment ? div + signum : div; 412 } 413 414 /** 415 * Returns {@code x mod m}. This differs from {@code x % m} in that it always returns a 416 * non-negative result. 417 * 418 * <p>For example: 419 * 420 * <pre> {@code 421 * 422 * mod(7, 4) == 3 423 * mod(-7, 4) == 1 424 * mod(-1, 4) == 3 425 * mod(-8, 4) == 0 426 * mod(8, 4) == 0}</pre> 427 * 428 * @throws ArithmeticException if {@code m <= 0} 429 */ 430 @GwtIncompatible("TODO") 431 public static int mod(long x, int m) { 432 // Cast is safe because the result is guaranteed in the range [0, m) 433 return (int) mod(x, (long) m); 434 } 435 436 /** 437 * Returns {@code x mod m}. This differs from {@code x % m} in that it always returns a 438 * non-negative result. 439 * 440 * <p>For example: 441 * 442 * <pre> {@code 443 * 444 * mod(7, 4) == 3 445 * mod(-7, 4) == 1 446 * mod(-1, 4) == 3 447 * mod(-8, 4) == 0 448 * mod(8, 4) == 0}</pre> 449 * 450 * @throws ArithmeticException if {@code m <= 0} 451 */ 452 @GwtIncompatible("TODO") 453 public static long mod(long x, long m) { 454 if (m <= 0) { 455 throw new ArithmeticException("Modulus " + m + " must be > 0"); 456 } 457 long result = x % m; 458 return (result >= 0) ? result : result + m; 459 } 460 461 /** 462 * Returns the greatest common divisor of {@code a, b}. Returns {@code 0} if 463 * {@code a == 0 && b == 0}. 464 * 465 * @throws IllegalArgumentException if {@code a < 0} or {@code b < 0} 466 */ 467 public static long gcd(long a, long b) { 468 /* 469 * The reason we require both arguments to be >= 0 is because otherwise, what do you return on 470 * gcd(0, Long.MIN_VALUE)? BigInteger.gcd would return positive 2^63, but positive 2^63 isn't 471 * an int. 472 */ 473 checkNonNegative("a", a); 474 checkNonNegative("b", b); 475 if (a == 0) { 476 // 0 % b == 0, so b divides a, but the converse doesn't hold. 477 // BigInteger.gcd is consistent with this decision. 478 return b; 479 } else if (b == 0) { 480 return a; // similar logic 481 } 482 /* 483 * Uses the binary GCD algorithm; see http://en.wikipedia.org/wiki/Binary_GCD_algorithm. 484 * This is >60% faster than the Euclidean algorithm in benchmarks. 485 */ 486 int aTwos = Long.numberOfTrailingZeros(a); 487 a >>= aTwos; // divide out all 2s 488 int bTwos = Long.numberOfTrailingZeros(b); 489 b >>= bTwos; // divide out all 2s 490 while (a != b) { // both a, b are odd 491 // The key to the binary GCD algorithm is as follows: 492 // Both a and b are odd. Assume a > b; then gcd(a - b, b) = gcd(a, b). 493 // But in gcd(a - b, b), a - b is even and b is odd, so we can divide out powers of two. 494 495 // We bend over backwards to avoid branching, adapting a technique from 496 // http://graphics.stanford.edu/~seander/bithacks.html#IntegerMinOrMax 497 498 long delta = a - b; // can't overflow, since a and b are nonnegative 499 500 long minDeltaOrZero = delta & (delta >> (Long.SIZE - 1)); 501 // equivalent to Math.min(delta, 0) 502 503 a = delta - minDeltaOrZero - minDeltaOrZero; // sets a to Math.abs(a - b) 504 // a is now nonnegative and even 505 506 b += minDeltaOrZero; // sets b to min(old a, b) 507 a >>= Long.numberOfTrailingZeros(a); // divide out all 2s, since 2 doesn't divide b 508 } 509 return a << min(aTwos, bTwos); 510 } 511 512 /** 513 * Returns the sum of {@code a} and {@code b}, provided it does not overflow. 514 * 515 * @throws ArithmeticException if {@code a + b} overflows in signed {@code long} arithmetic 516 */ 517 @GwtIncompatible("TODO") 518 public static long checkedAdd(long a, long b) { 519 long result = a + b; 520 checkNoOverflow((a ^ b) < 0 | (a ^ result) >= 0); 521 return result; 522 } 523 524 /** 525 * Returns the difference of {@code a} and {@code b}, provided it does not overflow. 526 * 527 * @throws ArithmeticException if {@code a - b} overflows in signed {@code long} arithmetic 528 */ 529 @GwtIncompatible("TODO") 530 public static long checkedSubtract(long a, long b) { 531 long result = a - b; 532 checkNoOverflow((a ^ b) >= 0 | (a ^ result) >= 0); 533 return result; 534 } 535 536 /** 537 * Returns the product of {@code a} and {@code b}, provided it does not overflow. 538 * 539 * @throws ArithmeticException if {@code a * b} overflows in signed {@code long} arithmetic 540 */ 541 @GwtIncompatible("TODO") 542 public static long checkedMultiply(long a, long b) { 543 // Hacker's Delight, Section 2-12 544 int leadingZeros = Long.numberOfLeadingZeros(a) + Long.numberOfLeadingZeros(~a) 545 + Long.numberOfLeadingZeros(b) + Long.numberOfLeadingZeros(~b); 546 /* 547 * If leadingZeros > Long.SIZE + 1 it's definitely fine, if it's < Long.SIZE it's definitely 548 * bad. We do the leadingZeros check to avoid the division below if at all possible. 549 * 550 * Otherwise, if b == Long.MIN_VALUE, then the only allowed values of a are 0 and 1. We take 551 * care of all a < 0 with their own check, because in particular, the case a == -1 will 552 * incorrectly pass the division check below. 553 * 554 * In all other cases, we check that either a is 0 or the result is consistent with division. 555 */ 556 if (leadingZeros > Long.SIZE + 1) { 557 return a * b; 558 } 559 checkNoOverflow(leadingZeros >= Long.SIZE); 560 checkNoOverflow(a >= 0 | b != Long.MIN_VALUE); 561 long result = a * b; 562 checkNoOverflow(a == 0 || result / a == b); 563 return result; 564 } 565 566 /** 567 * Returns the {@code b} to the {@code k}th power, provided it does not overflow. 568 * 569 * @throws ArithmeticException if {@code b} to the {@code k}th power overflows in signed 570 * {@code long} arithmetic 571 */ 572 @GwtIncompatible("TODO") 573 public static long checkedPow(long b, int k) { 574 checkNonNegative("exponent", k); 575 if (b >= -2 & b <= 2) { 576 switch ((int) 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 checkNoOverflow(k < Long.SIZE - 1); 585 return 1L << k; 586 case (-2): 587 checkNoOverflow(k < Long.SIZE); 588 return ((k & 1) == 0) ? (1L << k) : (-1L << k); 589 } 590 } 591 long accum = 1; 592 while (true) { 593 switch (k) { 594 case 0: 595 return accum; 596 case 1: 597 return checkedMultiply(accum, b); 598 default: 599 if ((k & 1) != 0) { 600 accum = checkedMultiply(accum, b); 601 } 602 k >>= 1; 603 if (k > 0) { 604 checkNoOverflow(b <= FLOOR_SQRT_MAX_LONG); 605 b *= b; 606 } 607 } 608 } 609 } 610 611 @GwtIncompatible("TODO") 612 @VisibleForTesting static final long FLOOR_SQRT_MAX_LONG = 3037000499L; 613 614 /** 615 * Returns {@code n!}, that is, the product of the first {@code n} positive 616 * integers, {@code 1} if {@code n == 0}, or {@link Long#MAX_VALUE} if the 617 * result does not fit in a {@code long}. 618 * 619 * @throws IllegalArgumentException if {@code n < 0} 620 */ 621 @GwtIncompatible("TODO") 622 public static long factorial(int n) { 623 checkNonNegative("n", n); 624 return (n < factorials.length) ? factorials[n] : Long.MAX_VALUE; 625 } 626 627 static final long[] factorials = { 628 1L, 629 1L, 630 1L * 2, 631 1L * 2 * 3, 632 1L * 2 * 3 * 4, 633 1L * 2 * 3 * 4 * 5, 634 1L * 2 * 3 * 4 * 5 * 6, 635 1L * 2 * 3 * 4 * 5 * 6 * 7, 636 1L * 2 * 3 * 4 * 5 * 6 * 7 * 8, 637 1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9, 638 1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10, 639 1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11, 640 1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12, 641 1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 * 13, 642 1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 * 13 * 14, 643 1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 * 13 * 14 * 15, 644 1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 * 13 * 14 * 15 * 16, 645 1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 * 13 * 14 * 15 * 16 * 17, 646 1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 * 13 * 14 * 15 * 16 * 17 * 18, 647 1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 * 13 * 14 * 15 * 16 * 17 * 18 * 19, 648 1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 * 13 * 14 * 15 * 16 * 17 * 18 * 19 * 20 649 }; 650 651 /** 652 * Returns {@code n} choose {@code k}, also known as the binomial coefficient of {@code n} and 653 * {@code k}, or {@link Long#MAX_VALUE} if the result does not fit in a {@code long}. 654 * 655 * @throws IllegalArgumentException if {@code n < 0}, {@code k < 0}, or {@code k > n} 656 */ 657 public static long binomial(int n, int k) { 658 checkNonNegative("n", n); 659 checkNonNegative("k", k); 660 checkArgument(k <= n, "k (%s) > n (%s)", k, n); 661 if (k > (n >> 1)) { 662 k = n - k; 663 } 664 switch (k) { 665 case 0: 666 return 1; 667 case 1: 668 return n; 669 default: 670 if (n < factorials.length) { 671 return factorials[n] / (factorials[k] * factorials[n - k]); 672 } else if (k >= biggestBinomials.length || n > biggestBinomials[k]) { 673 return Long.MAX_VALUE; 674 } else if (k < biggestSimpleBinomials.length && n <= biggestSimpleBinomials[k]) { 675 // guaranteed not to overflow 676 long result = n--; 677 for (int i = 2; i <= k; n--, i++) { 678 result *= n; 679 result /= i; 680 } 681 return result; 682 } else { 683 int nBits = LongMath.log2(n, RoundingMode.CEILING); 684 685 long result = 1; 686 long numerator = n--; 687 long denominator = 1; 688 689 int numeratorBits = nBits; 690 // This is an upper bound on log2(numerator, ceiling). 691 692 /* 693 * We want to do this in long math for speed, but want to avoid overflow. We adapt the 694 * technique previously used by BigIntegerMath: maintain separate numerator and 695 * denominator accumulators, multiplying the fraction into result when near overflow. 696 */ 697 for (int i = 2; i <= k; i++, n--) { 698 if (numeratorBits + nBits < Long.SIZE - 1) { 699 // It's definitely safe to multiply into numerator and denominator. 700 numerator *= n; 701 denominator *= i; 702 numeratorBits += nBits; 703 } else { 704 // It might not be safe to multiply into numerator and denominator, 705 // so multiply (numerator / denominator) into result. 706 result = multiplyFraction(result, numerator, denominator); 707 numerator = n; 708 denominator = i; 709 numeratorBits = nBits; 710 } 711 } 712 return multiplyFraction(result, numerator, denominator); 713 } 714 } 715 } 716 717 /** 718 * Returns (x * numerator / denominator), which is assumed to come out to an integral value. 719 */ 720 static long multiplyFraction(long x, long numerator, long denominator) { 721 if (x == 1) { 722 return numerator / denominator; 723 } 724 long commonDivisor = gcd(x, denominator); 725 x /= commonDivisor; 726 denominator /= commonDivisor; 727 // We know gcd(x, denominator) = 1, and x * numerator / denominator is exact, 728 // so denominator must be a divisor of numerator. 729 return x * (numerator / denominator); 730 } 731 732 /* 733 * binomial(biggestBinomials[k], k) fits in a long, but not 734 * binomial(biggestBinomials[k] + 1, k). 735 */ 736 static final int[] biggestBinomials = 737 {Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE, 3810779, 121977, 16175, 4337, 1733, 738 887, 534, 361, 265, 206, 169, 143, 125, 111, 101, 94, 88, 83, 79, 76, 74, 72, 70, 69, 68, 739 67, 67, 66, 66, 66, 66}; 740 741 /* 742 * binomial(biggestSimpleBinomials[k], k) doesn't need to use the slower GCD-based impl, 743 * but binomial(biggestSimpleBinomials[k] + 1, k) does. 744 */ 745 @VisibleForTesting static final int[] biggestSimpleBinomials = 746 {Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE, 2642246, 86251, 11724, 3218, 1313, 747 684, 419, 287, 214, 169, 139, 119, 105, 95, 87, 81, 76, 73, 70, 68, 66, 64, 63, 62, 62, 748 61, 61, 61}; 749 // These values were generated by using checkedMultiply to see when the simple multiply/divide 750 // algorithm would lead to an overflow. 751 752 @GwtIncompatible("TODO") 753 static boolean fitsInInt(long x) { 754 return (int) x == x; 755 } 756 757 /** 758 * Returns the arithmetic mean of {@code x} and {@code y}, rounded toward 759 * negative infinity. This method is resilient to overflow. 760 * 761 * @since 14.0 762 */ 763 public static long mean(long x, long y) { 764 // Efficient method for computing the arithmetic mean. 765 // The alternative (x + y) / 2 fails for large values. 766 // The alternative (x + y) >>> 1 fails for negative values. 767 return (x & y) + ((x ^ y) >> 1); 768 } 769 770 private LongMath() {} 771}