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.checkNonNegative; 020import static com.google.common.math.MathPreconditions.checkPositive; 021import static com.google.common.math.MathPreconditions.checkRoundingUnnecessary; 022import static java.math.RoundingMode.CEILING; 023import static java.math.RoundingMode.FLOOR; 024import static java.math.RoundingMode.HALF_EVEN; 025 026import com.google.common.annotations.GwtCompatible; 027import com.google.common.annotations.GwtIncompatible; 028import com.google.common.annotations.VisibleForTesting; 029import java.math.BigDecimal; 030import java.math.BigInteger; 031import java.math.RoundingMode; 032import java.util.ArrayList; 033import java.util.List; 034 035/** 036 * A class for arithmetic on values of type {@code BigInteger}. 037 * 038 * <p>The implementations of many methods in this class are based on material from Henry S. Warren, 039 * Jr.'s <i>Hacker's Delight</i>, (Addison Wesley, 2002). 040 * 041 * <p>Similar functionality for {@code int} and for {@code long} can be found in {@link IntMath} and 042 * {@link LongMath} respectively. 043 * 044 * @author Louis Wasserman 045 * @since 11.0 046 */ 047@GwtCompatible(emulated = true) 048public final class BigIntegerMath { 049 /** 050 * Returns the smallest power of two greater than or equal to {@code x}. This is equivalent to 051 * {@code BigInteger.valueOf(2).pow(log2(x, CEILING))}. 052 * 053 * @throws IllegalArgumentException if {@code x <= 0} 054 * @since 20.0 055 */ 056 public static BigInteger ceilingPowerOfTwo(BigInteger x) { 057 return BigInteger.ZERO.setBit(log2(x, CEILING)); 058 } 059 060 /** 061 * Returns the largest power of two less than or equal to {@code x}. This is equivalent to {@code 062 * BigInteger.valueOf(2).pow(log2(x, FLOOR))}. 063 * 064 * @throws IllegalArgumentException if {@code x <= 0} 065 * @since 20.0 066 */ 067 public static BigInteger floorPowerOfTwo(BigInteger x) { 068 return BigInteger.ZERO.setBit(log2(x, FLOOR)); 069 } 070 071 /** Returns {@code true} if {@code x} represents a power of two. */ 072 public static boolean isPowerOfTwo(BigInteger x) { 073 checkNotNull(x); 074 return x.signum() > 0 && x.getLowestSetBit() == x.bitLength() - 1; 075 } 076 077 /** 078 * Returns the base-2 logarithm of {@code x}, rounded according to the specified rounding mode. 079 * 080 * @throws IllegalArgumentException if {@code x <= 0} 081 * @throws ArithmeticException if {@code mode} is {@link RoundingMode#UNNECESSARY} and {@code x} 082 * is not a power of two 083 */ 084 @SuppressWarnings("fallthrough") 085 // TODO(kevinb): remove after this warning is disabled globally 086 public static int log2(BigInteger x, RoundingMode mode) { 087 checkPositive("x", checkNotNull(x)); 088 int logFloor = x.bitLength() - 1; 089 switch (mode) { 090 case UNNECESSARY: 091 checkRoundingUnnecessary(isPowerOfTwo(x)); // fall through 092 case DOWN: 093 case FLOOR: 094 return logFloor; 095 096 case UP: 097 case CEILING: 098 return isPowerOfTwo(x) ? logFloor : logFloor + 1; 099 100 case HALF_DOWN: 101 case HALF_UP: 102 case HALF_EVEN: 103 if (logFloor < SQRT2_PRECOMPUTE_THRESHOLD) { 104 BigInteger halfPower = 105 SQRT2_PRECOMPUTED_BITS.shiftRight(SQRT2_PRECOMPUTE_THRESHOLD - logFloor); 106 if (x.compareTo(halfPower) <= 0) { 107 return logFloor; 108 } else { 109 return logFloor + 1; 110 } 111 } 112 // Since sqrt(2) is irrational, log2(x) - logFloor cannot be exactly 0.5 113 // 114 // To determine which side of logFloor.5 the logarithm is, 115 // we compare x^2 to 2^(2 * logFloor + 1). 116 BigInteger x2 = x.pow(2); 117 int logX2Floor = x2.bitLength() - 1; 118 return (logX2Floor < 2 * logFloor + 1) ? logFloor : logFloor + 1; 119 } 120 throw new AssertionError(); 121 } 122 123 /* 124 * The maximum number of bits in a square root for which we'll precompute an explicit half power 125 * of two. This can be any value, but higher values incur more class load time and linearly 126 * increasing memory consumption. 127 */ 128 @VisibleForTesting static final int SQRT2_PRECOMPUTE_THRESHOLD = 256; 129 130 @VisibleForTesting 131 static final BigInteger SQRT2_PRECOMPUTED_BITS = 132 new BigInteger("16a09e667f3bcc908b2fb1366ea957d3e3adec17512775099da2f590b0667322a", 16); 133 134 /** 135 * Returns the base-10 logarithm of {@code x}, rounded according to the specified rounding mode. 136 * 137 * @throws IllegalArgumentException if {@code x <= 0} 138 * @throws ArithmeticException if {@code mode} is {@link RoundingMode#UNNECESSARY} and {@code x} 139 * is not a power of ten 140 */ 141 @GwtIncompatible // TODO 142 @SuppressWarnings("fallthrough") 143 public static int log10(BigInteger x, RoundingMode mode) { 144 checkPositive("x", x); 145 if (fitsInLong(x)) { 146 return LongMath.log10(x.longValue(), mode); 147 } 148 149 int approxLog10 = (int) (log2(x, FLOOR) * LN_2 / LN_10); 150 BigInteger approxPow = BigInteger.TEN.pow(approxLog10); 151 int approxCmp = approxPow.compareTo(x); 152 153 /* 154 * We adjust approxLog10 and approxPow until they're equal to floor(log10(x)) and 155 * 10^floor(log10(x)). 156 */ 157 158 if (approxCmp > 0) { 159 /* 160 * The code is written so that even completely incorrect approximations will still yield the 161 * correct answer eventually, but in practice this branch should almost never be entered, and 162 * even then the loop should not run more than once. 163 */ 164 do { 165 approxLog10--; 166 approxPow = approxPow.divide(BigInteger.TEN); 167 approxCmp = approxPow.compareTo(x); 168 } while (approxCmp > 0); 169 } else { 170 BigInteger nextPow = BigInteger.TEN.multiply(approxPow); 171 int nextCmp = nextPow.compareTo(x); 172 while (nextCmp <= 0) { 173 approxLog10++; 174 approxPow = nextPow; 175 approxCmp = nextCmp; 176 nextPow = BigInteger.TEN.multiply(approxPow); 177 nextCmp = nextPow.compareTo(x); 178 } 179 } 180 181 int floorLog = approxLog10; 182 BigInteger floorPow = approxPow; 183 int floorCmp = approxCmp; 184 185 switch (mode) { 186 case UNNECESSARY: 187 checkRoundingUnnecessary(floorCmp == 0); 188 // fall through 189 case FLOOR: 190 case DOWN: 191 return floorLog; 192 193 case CEILING: 194 case UP: 195 return floorPow.equals(x) ? floorLog : floorLog + 1; 196 197 case HALF_DOWN: 198 case HALF_UP: 199 case HALF_EVEN: 200 // Since sqrt(10) is irrational, log10(x) - floorLog can never be exactly 0.5 201 BigInteger x2 = x.pow(2); 202 BigInteger halfPowerSquared = floorPow.pow(2).multiply(BigInteger.TEN); 203 return (x2.compareTo(halfPowerSquared) <= 0) ? floorLog : floorLog + 1; 204 } 205 throw new AssertionError(); 206 } 207 208 private static final double LN_10 = Math.log(10); 209 private static final double LN_2 = Math.log(2); 210 211 /** 212 * Returns the square root of {@code x}, rounded with the specified rounding mode. 213 * 214 * @throws IllegalArgumentException if {@code x < 0} 215 * @throws ArithmeticException if {@code mode} is {@link RoundingMode#UNNECESSARY} and {@code 216 * sqrt(x)} is not an integer 217 */ 218 @GwtIncompatible // TODO 219 @SuppressWarnings("fallthrough") 220 public static BigInteger sqrt(BigInteger x, RoundingMode mode) { 221 checkNonNegative("x", x); 222 if (fitsInLong(x)) { 223 return BigInteger.valueOf(LongMath.sqrt(x.longValue(), mode)); 224 } 225 BigInteger sqrtFloor = sqrtFloor(x); 226 switch (mode) { 227 case UNNECESSARY: 228 checkRoundingUnnecessary(sqrtFloor.pow(2).equals(x)); // fall through 229 case FLOOR: 230 case DOWN: 231 return sqrtFloor; 232 case CEILING: 233 case UP: 234 int sqrtFloorInt = sqrtFloor.intValue(); 235 boolean sqrtFloorIsExact = 236 (sqrtFloorInt * sqrtFloorInt == x.intValue()) // fast check mod 2^32 237 && sqrtFloor.pow(2).equals(x); // slow exact check 238 return sqrtFloorIsExact ? sqrtFloor : sqrtFloor.add(BigInteger.ONE); 239 case HALF_DOWN: 240 case HALF_UP: 241 case HALF_EVEN: 242 BigInteger halfSquare = sqrtFloor.pow(2).add(sqrtFloor); 243 /* 244 * We wish to test whether or not x <= (sqrtFloor + 0.5)^2 = halfSquare + 0.25. Since both x 245 * and halfSquare are integers, this is equivalent to testing whether or not x <= 246 * halfSquare. 247 */ 248 return (halfSquare.compareTo(x) >= 0) ? sqrtFloor : sqrtFloor.add(BigInteger.ONE); 249 } 250 throw new AssertionError(); 251 } 252 253 @GwtIncompatible // TODO 254 private static BigInteger sqrtFloor(BigInteger x) { 255 /* 256 * Adapted from Hacker's Delight, Figure 11-1. 257 * 258 * Using DoubleUtils.bigToDouble, getting a double approximation of x is extremely fast, and 259 * then we can get a double approximation of the square root. Then, we iteratively improve this 260 * guess with an application of Newton's method, which sets guess := (guess + (x / guess)) / 2. 261 * This iteration has the following two properties: 262 * 263 * a) every iteration (except potentially the first) has guess >= floor(sqrt(x)). This is 264 * because guess' is the arithmetic mean of guess and x / guess, sqrt(x) is the geometric mean, 265 * and the arithmetic mean is always higher than the geometric mean. 266 * 267 * b) this iteration converges to floor(sqrt(x)). In fact, the number of correct digits doubles 268 * with each iteration, so this algorithm takes O(log(digits)) iterations. 269 * 270 * We start out with a double-precision approximation, which may be higher or lower than the 271 * true value. Therefore, we perform at least one Newton iteration to get a guess that's 272 * definitely >= floor(sqrt(x)), and then continue the iteration until we reach a fixed point. 273 */ 274 BigInteger sqrt0; 275 int log2 = log2(x, FLOOR); 276 if (log2 < Double.MAX_EXPONENT) { 277 sqrt0 = sqrtApproxWithDoubles(x); 278 } else { 279 int shift = (log2 - DoubleUtils.SIGNIFICAND_BITS) & ~1; // even! 280 /* 281 * We have that x / 2^shift < 2^54. Our initial approximation to sqrtFloor(x) will be 282 * 2^(shift/2) * sqrtApproxWithDoubles(x / 2^shift). 283 */ 284 sqrt0 = sqrtApproxWithDoubles(x.shiftRight(shift)).shiftLeft(shift >> 1); 285 } 286 BigInteger sqrt1 = sqrt0.add(x.divide(sqrt0)).shiftRight(1); 287 if (sqrt0.equals(sqrt1)) { 288 return sqrt0; 289 } 290 do { 291 sqrt0 = sqrt1; 292 sqrt1 = sqrt0.add(x.divide(sqrt0)).shiftRight(1); 293 } while (sqrt1.compareTo(sqrt0) < 0); 294 return sqrt0; 295 } 296 297 @GwtIncompatible // TODO 298 private static BigInteger sqrtApproxWithDoubles(BigInteger x) { 299 return DoubleMath.roundToBigInteger(Math.sqrt(DoubleUtils.bigToDouble(x)), HALF_EVEN); 300 } 301 302 /** 303 * Returns {@code x}, rounded to a {@code double} with the specified rounding mode. If {@code x} 304 * is precisely representable as a {@code double}, its {@code double} value will be returned; 305 * otherwise, the rounding will choose between the two nearest representable values with {@code 306 * mode}. 307 * 308 * <p>For the case of {@link RoundingMode#HALF_DOWN}, {@code HALF_UP}, and {@code HALF_EVEN}, 309 * infinite {@code double} values are considered infinitely far away. For example, 2^2000 is not 310 * representable as a double, but {@code roundToDouble(BigInteger.valueOf(2).pow(2000), HALF_UP)} 311 * will return {@code Double.MAX_VALUE}, not {@code Double.POSITIVE_INFINITY}. 312 * 313 * <p>For the case of {@link RoundingMode#HALF_EVEN}, this implementation uses the IEEE 754 314 * default rounding mode: if the two nearest representable values are equally near, the one with 315 * the least significant bit zero is chosen. (In such cases, both of the nearest representable 316 * values are even integers; this method returns the one that is a multiple of a greater power of 317 * two.) 318 * 319 * @throws ArithmeticException if {@code mode} is {@link RoundingMode#UNNECESSARY} and {@code x} 320 * is not precisely representable as a {@code double} 321 * @since 30.0 322 */ 323 @GwtIncompatible 324 public static double roundToDouble(BigInteger x, RoundingMode mode) { 325 return BigIntegerToDoubleRounder.INSTANCE.roundToDouble(x, mode); 326 } 327 328 @GwtIncompatible 329 private static class BigIntegerToDoubleRounder extends ToDoubleRounder<BigInteger> { 330 static final BigIntegerToDoubleRounder INSTANCE = new BigIntegerToDoubleRounder(); 331 332 private BigIntegerToDoubleRounder() {} 333 334 @Override 335 double roundToDoubleArbitrarily(BigInteger bigInteger) { 336 return DoubleUtils.bigToDouble(bigInteger); 337 } 338 339 @Override 340 int sign(BigInteger bigInteger) { 341 return bigInteger.signum(); 342 } 343 344 @Override 345 BigInteger toX(double d, RoundingMode mode) { 346 return DoubleMath.roundToBigInteger(d, mode); 347 } 348 349 @Override 350 BigInteger minus(BigInteger a, BigInteger b) { 351 return a.subtract(b); 352 } 353 } 354 355 /** 356 * Returns the result of dividing {@code p} by {@code q}, rounding using the specified {@code 357 * RoundingMode}. 358 * 359 * @throws ArithmeticException if {@code q == 0}, or if {@code mode == UNNECESSARY} and {@code a} 360 * is not an integer multiple of {@code b} 361 */ 362 @GwtIncompatible // TODO 363 public static BigInteger divide(BigInteger p, BigInteger q, RoundingMode mode) { 364 BigDecimal pDec = new BigDecimal(p); 365 BigDecimal qDec = new BigDecimal(q); 366 return pDec.divide(qDec, 0, mode).toBigIntegerExact(); 367 } 368 369 /** 370 * Returns {@code n!}, that is, the product of the first {@code n} positive integers, or {@code 1} 371 * if {@code n == 0}. 372 * 373 * <p><b>Warning:</b> the result takes <i>O(n log n)</i> space, so use cautiously. 374 * 375 * <p>This uses an efficient binary recursive algorithm to compute the factorial with balanced 376 * multiplies. It also removes all the 2s from the intermediate products (shifting them back in at 377 * the end). 378 * 379 * @throws IllegalArgumentException if {@code n < 0} 380 */ 381 public static BigInteger factorial(int n) { 382 checkNonNegative("n", n); 383 384 // If the factorial is small enough, just use LongMath to do it. 385 if (n < LongMath.factorials.length) { 386 return BigInteger.valueOf(LongMath.factorials[n]); 387 } 388 389 // Pre-allocate space for our list of intermediate BigIntegers. 390 int approxSize = IntMath.divide(n * IntMath.log2(n, CEILING), Long.SIZE, CEILING); 391 ArrayList<BigInteger> bignums = new ArrayList<>(approxSize); 392 393 // Start from the pre-computed maximum long factorial. 394 int startingNumber = LongMath.factorials.length; 395 long product = LongMath.factorials[startingNumber - 1]; 396 // Strip off 2s from this value. 397 int shift = Long.numberOfTrailingZeros(product); 398 product >>= shift; 399 400 // Use floor(log2(num)) + 1 to prevent overflow of multiplication. 401 int productBits = LongMath.log2(product, FLOOR) + 1; 402 int bits = LongMath.log2(startingNumber, FLOOR) + 1; 403 // Check for the next power of two boundary, to save us a CLZ operation. 404 int nextPowerOfTwo = 1 << (bits - 1); 405 406 // Iteratively multiply the longs as big as they can go. 407 for (long num = startingNumber; num <= n; num++) { 408 // Check to see if the floor(log2(num)) + 1 has changed. 409 if ((num & nextPowerOfTwo) != 0) { 410 nextPowerOfTwo <<= 1; 411 bits++; 412 } 413 // Get rid of the 2s in num. 414 int tz = Long.numberOfTrailingZeros(num); 415 long normalizedNum = num >> tz; 416 shift += tz; 417 // Adjust floor(log2(num)) + 1. 418 int normalizedBits = bits - tz; 419 // If it won't fit in a long, then we store off the intermediate product. 420 if (normalizedBits + productBits >= Long.SIZE) { 421 bignums.add(BigInteger.valueOf(product)); 422 product = 1; 423 productBits = 0; 424 } 425 product *= normalizedNum; 426 productBits = LongMath.log2(product, FLOOR) + 1; 427 } 428 // Check for leftovers. 429 if (product > 1) { 430 bignums.add(BigInteger.valueOf(product)); 431 } 432 // Efficiently multiply all the intermediate products together. 433 return listProduct(bignums).shiftLeft(shift); 434 } 435 436 static BigInteger listProduct(List<BigInteger> nums) { 437 return listProduct(nums, 0, nums.size()); 438 } 439 440 static BigInteger listProduct(List<BigInteger> nums, int start, int end) { 441 switch (end - start) { 442 case 0: 443 return BigInteger.ONE; 444 case 1: 445 return nums.get(start); 446 case 2: 447 return nums.get(start).multiply(nums.get(start + 1)); 448 case 3: 449 return nums.get(start).multiply(nums.get(start + 1)).multiply(nums.get(start + 2)); 450 default: 451 // Otherwise, split the list in half and recursively do this. 452 int m = (end + start) >>> 1; 453 return listProduct(nums, start, m).multiply(listProduct(nums, m, end)); 454 } 455 } 456 457 /** 458 * Returns {@code n} choose {@code k}, also known as the binomial coefficient of {@code n} and 459 * {@code k}, that is, {@code n! / (k! (n - k)!)}. 460 * 461 * <p><b>Warning:</b> the result can take as much as <i>O(k log n)</i> space. 462 * 463 * @throws IllegalArgumentException if {@code n < 0}, {@code k < 0}, or {@code k > n} 464 */ 465 public static BigInteger binomial(int n, int k) { 466 checkNonNegative("n", n); 467 checkNonNegative("k", k); 468 checkArgument(k <= n, "k (%s) > n (%s)", k, n); 469 if (k > (n >> 1)) { 470 k = n - k; 471 } 472 if (k < LongMath.biggestBinomials.length && n <= LongMath.biggestBinomials[k]) { 473 return BigInteger.valueOf(LongMath.binomial(n, k)); 474 } 475 476 BigInteger accum = BigInteger.ONE; 477 478 long numeratorAccum = n; 479 long denominatorAccum = 1; 480 481 int bits = LongMath.log2(n, CEILING); 482 483 int numeratorBits = bits; 484 485 for (int i = 1; i < k; i++) { 486 int p = n - i; 487 int q = i + 1; 488 489 // log2(p) >= bits - 1, because p >= n/2 490 491 if (numeratorBits + bits >= Long.SIZE - 1) { 492 // The numerator is as big as it can get without risking overflow. 493 // Multiply numeratorAccum / denominatorAccum into accum. 494 accum = 495 accum 496 .multiply(BigInteger.valueOf(numeratorAccum)) 497 .divide(BigInteger.valueOf(denominatorAccum)); 498 numeratorAccum = p; 499 denominatorAccum = q; 500 numeratorBits = bits; 501 } else { 502 // We can definitely multiply into the long accumulators without overflowing them. 503 numeratorAccum *= p; 504 denominatorAccum *= q; 505 numeratorBits += bits; 506 } 507 } 508 return accum 509 .multiply(BigInteger.valueOf(numeratorAccum)) 510 .divide(BigInteger.valueOf(denominatorAccum)); 511 } 512 513 // Returns true if BigInteger.valueOf(x.longValue()).equals(x). 514 @GwtIncompatible // TODO 515 static boolean fitsInLong(BigInteger x) { 516 return x.bitLength() <= Long.SIZE - 1; 517 } 518 519 private BigIntegerMath() {} 520}