Showing the changes to java/pkg/java/math (19 of 18352 files). Show all
Unified · Split
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
| @@ -0,0 +1,3855 @@ | ||
| 1 | +/* | |
| 2 | + * Copyright (c) 1996, 2011, Oracle and/or its affiliates. All rights reserved. | |
| 3 | + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. | |
| 4 | + * | |
| 5 | + * This code is free software; you can redistribute it and/or modify it | |
| 6 | + * under the terms of the GNU General Public License version 2 only, as | |
| 7 | + * published by the Free Software Foundation. Oracle designates this | |
| 8 | + * particular file as subject to the "Classpath" exception as provided | |
| 9 | + * by Oracle in the LICENSE file that accompanied this code. | |
| 10 | + * | |
| 11 | + * This code is distributed in the hope that it will be useful, but WITHOUT | |
| 12 | + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or | |
| 13 | + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License | |
| 14 | + * version 2 for more details (a copy is included in the LICENSE file that | |
| 15 | + * accompanied this code). | |
| 16 | + * | |
| 17 | + * You should have received a copy of the GNU General Public License version | |
| 18 | + * 2 along with this work; if not, write to the Free Software Foundation, | |
| 19 | + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. | |
| 20 | + * | |
| 21 | + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA | |
| 22 | + * or visit www.oracle.com if you need additional information or have any | |
| 23 | + * questions. | |
| 24 | + */ | |
| 25 | + | |
| 26 | +/* | |
| 27 | + * Portions Copyright IBM Corporation, 2001. All Rights Reserved. | |
| 28 | + */ | |
| 29 | + | |
| 30 | +package java.math; | |
| 31 | + | |
| 32 | +import java.util.Arrays; | |
| 33 | +import static java.math.BigInteger.LONG_MASK; | |
| 34 | + | |
| 35 | +/** | |
| 36 | + * Immutable, arbitrary-precision signed decimal numbers. A | |
| 37 | + * {@code BigDecimal} consists of an arbitrary precision integer | |
| 38 | + * <i>unscaled value</i> and a 32-bit integer <i>scale</i>. If zero | |
| 39 | + * or positive, the scale is the number of digits to the right of the | |
| 40 | + * decimal point. If negative, the unscaled value of the number is | |
| 41 | + * multiplied by ten to the power of the negation of the scale. The | |
| 42 | + * value of the number represented by the {@code BigDecimal} is | |
| 43 | + * therefore <tt>(unscaledValue × 10<sup>-scale</sup>)</tt>. | |
| 44 | + * | |
| 45 | + * <p>The {@code BigDecimal} class provides operations for | |
| 46 | + * arithmetic, scale manipulation, rounding, comparison, hashing, and | |
| 47 | + * format conversion. The {@link #toString} method provides a | |
| 48 | + * canonical representation of a {@code BigDecimal}. | |
| 49 | + * | |
| 50 | + * <p>The {@code BigDecimal} class gives its user complete control | |
| 51 | + * over rounding behavior. If no rounding mode is specified and the | |
| 52 | + * exact result cannot be represented, an exception is thrown; | |
| 53 | + * otherwise, calculations can be carried out to a chosen precision | |
| 54 | + * and rounding mode by supplying an appropriate {@link MathContext} | |
| 55 | + * object to the operation. In either case, eight <em>rounding | |
| 56 | + * modes</em> are provided for the control of rounding. Using the | |
| 57 | + * integer fields in this class (such as {@link #ROUND_HALF_UP}) to | |
| 58 | + * represent rounding mode is largely obsolete; the enumeration values | |
| 59 | + * of the {@code RoundingMode} {@code enum}, (such as {@link | |
| 60 | + * RoundingMode#HALF_UP}) should be used instead. | |
| 61 | + * | |
| 62 | + * <p>When a {@code MathContext} object is supplied with a precision | |
| 63 | + * setting of 0 (for example, {@link MathContext#UNLIMITED}), | |
| 64 | + * arithmetic operations are exact, as are the arithmetic methods | |
| 65 | + * which take no {@code MathContext} object. (This is the only | |
| 66 | + * behavior that was supported in releases prior to 5.) As a | |
| 67 | + * corollary of computing the exact result, the rounding mode setting | |
| 68 | + * of a {@code MathContext} object with a precision setting of 0 is | |
| 69 | + * not used and thus irrelevant. In the case of divide, the exact | |
| 70 | + * quotient could have an infinitely long decimal expansion; for | |
| 71 | + * example, 1 divided by 3. If the quotient has a nonterminating | |
| 72 | + * decimal expansion and the operation is specified to return an exact | |
| 73 | + * result, an {@code ArithmeticException} is thrown. Otherwise, the | |
| 74 | + * exact result of the division is returned, as done for other | |
| 75 | + * operations. | |
| 76 | + * | |
| 77 | + * <p>When the precision setting is not 0, the rules of | |
| 78 | + * {@code BigDecimal} arithmetic are broadly compatible with selected | |
| 79 | + * modes of operation of the arithmetic defined in ANSI X3.274-1996 | |
| 80 | + * and ANSI X3.274-1996/AM 1-2000 (section 7.4). Unlike those | |
| 81 | + * standards, {@code BigDecimal} includes many rounding modes, which | |
| 82 | + * were mandatory for division in {@code BigDecimal} releases prior | |
| 83 | + * to 5. Any conflicts between these ANSI standards and the | |
| 84 | + * {@code BigDecimal} specification are resolved in favor of | |
| 85 | + * {@code BigDecimal}. | |
| 86 | + * | |
| 87 | + * <p>Since the same numerical value can have different | |
| 88 | + * representations (with different scales), the rules of arithmetic | |
| 89 | + * and rounding must specify both the numerical result and the scale | |
| 90 | + * used in the result's representation. | |
| 91 | + * | |
| 92 | + * | |
| 93 | + * <p>In general the rounding modes and precision setting determine | |
| 94 | + * how operations return results with a limited number of digits when | |
| 95 | + * the exact result has more digits (perhaps infinitely many in the | |
| 96 | + * case of division) than the number of digits returned. | |
| 97 | + * | |
| 98 | + * First, the | |
| 99 | + * total number of digits to return is specified by the | |
| 100 | + * {@code MathContext}'s {@code precision} setting; this determines | |
| 101 | + * the result's <i>precision</i>. The digit count starts from the | |
| 102 | + * leftmost nonzero digit of the exact result. The rounding mode | |
| 103 | + * determines how any discarded trailing digits affect the returned | |
| 104 | + * result. | |
| 105 | + * | |
| 106 | + * <p>For all arithmetic operators , the operation is carried out as | |
| 107 | + * though an exact intermediate result were first calculated and then | |
| 108 | + * rounded to the number of digits specified by the precision setting | |
| 109 | + * (if necessary), using the selected rounding mode. If the exact | |
| 110 | + * result is not returned, some digit positions of the exact result | |
| 111 | + * are discarded. When rounding increases the magnitude of the | |
| 112 | + * returned result, it is possible for a new digit position to be | |
| 113 | + * created by a carry propagating to a leading {@literal "9"} digit. | |
| 114 | + * For example, rounding the value 999.9 to three digits rounding up | |
| 115 | + * would be numerically equal to one thousand, represented as | |
| 116 | + * 100×10<sup>1</sup>. In such cases, the new {@literal "1"} is | |
| 117 | + * the leading digit position of the returned result. | |
| 118 | + * | |
| 119 | + * <p>Besides a logical exact result, each arithmetic operation has a | |
| 120 | + * preferred scale for representing a result. The preferred | |
| 121 | + * scale for each operation is listed in the table below. | |
| 122 | + * | |
| 123 | + * <table border> | |
| 124 | + * <caption><b>Preferred Scales for Results of Arithmetic Operations | |
| 125 | + * </b></caption> | |
| 126 | + * <tr><th>Operation</th><th>Preferred Scale of Result</th></tr> | |
| 127 | + * <tr><td>Add</td><td>max(addend.scale(), augend.scale())</td> | |
| 128 | + * <tr><td>Subtract</td><td>max(minuend.scale(), subtrahend.scale())</td> | |
| 129 | + * <tr><td>Multiply</td><td>multiplier.scale() + multiplicand.scale()</td> | |
| 130 | + * <tr><td>Divide</td><td>dividend.scale() - divisor.scale()</td> | |
| 131 | + * </table> | |
| 132 | + * | |
| 133 | + * These scales are the ones used by the methods which return exact | |
| 134 | + * arithmetic results; except that an exact divide may have to use a | |
| 135 | + * larger scale since the exact result may have more digits. For | |
| 136 | + * example, {@code 1/32} is {@code 0.03125}. | |
| 137 | + * | |
| 138 | + * <p>Before rounding, the scale of the logical exact intermediate | |
| 139 | + * result is the preferred scale for that operation. If the exact | |
| 140 | + * numerical result cannot be represented in {@code precision} | |
| 141 | + * digits, rounding selects the set of digits to return and the scale | |
| 142 | + * of the result is reduced from the scale of the intermediate result | |
| 143 | + * to the least scale which can represent the {@code precision} | |
| 144 | + * digits actually returned. If the exact result can be represented | |
| 145 | + * with at most {@code precision} digits, the representation | |
| 146 | + * of the result with the scale closest to the preferred scale is | |
| 147 | + * returned. In particular, an exactly representable quotient may be | |
| 148 | + * represented in fewer than {@code precision} digits by removing | |
| 149 | + * trailing zeros and decreasing the scale. For example, rounding to | |
| 150 | + * three digits using the {@linkplain RoundingMode#FLOOR floor} | |
| 151 | + * rounding mode, <br> | |
| 152 | + * | |
| 153 | + * {@code 19/100 = 0.19 // integer=19, scale=2} <br> | |
| 154 | + * | |
| 155 | + * but<br> | |
| 156 | + * | |
| 157 | + * {@code 21/110 = 0.190 // integer=190, scale=3} <br> | |
| 158 | + * | |
| 159 | + * <p>Note that for add, subtract, and multiply, the reduction in | |
| 160 | + * scale will equal the number of digit positions of the exact result | |
| 161 | + * which are discarded. If the rounding causes a carry propagation to | |
| 162 | + * create a new high-order digit position, an additional digit of the | |
| 163 | + * result is discarded than when no new digit position is created. | |
| 164 | + * | |
| 165 | + * <p>Other methods may have slightly different rounding semantics. | |
| 166 | + * For example, the result of the {@code pow} method using the | |
| 167 | + * {@linkplain #pow(int, MathContext) specified algorithm} can | |
| 168 | + * occasionally differ from the rounded mathematical result by more | |
| 169 | + * than one unit in the last place, one <i>{@linkplain #ulp() ulp}</i>. | |
| 170 | + * | |
| 171 | + * <p>Two types of operations are provided for manipulating the scale | |
| 172 | + * of a {@code BigDecimal}: scaling/rounding operations and decimal | |
| 173 | + * point motion operations. Scaling/rounding operations ({@link | |
| 174 | + * #setScale setScale} and {@link #round round}) return a | |
| 175 | + * {@code BigDecimal} whose value is approximately (or exactly) equal | |
| 176 | + * to that of the operand, but whose scale or precision is the | |
| 177 | + * specified value; that is, they increase or decrease the precision | |
| 178 | + * of the stored number with minimal effect on its value. Decimal | |
| 179 | + * point motion operations ({@link #movePointLeft movePointLeft} and | |
| 180 | + * {@link #movePointRight movePointRight}) return a | |
| 181 | + * {@code BigDecimal} created from the operand by moving the decimal | |
| 182 | + * point a specified distance in the specified direction. | |
| 183 | + * | |
| 184 | + * <p>For the sake of brevity and clarity, pseudo-code is used | |
| 185 | + * throughout the descriptions of {@code BigDecimal} methods. The | |
| 186 | + * pseudo-code expression {@code (i + j)} is shorthand for "a | |
| 187 | + * {@code BigDecimal} whose value is that of the {@code BigDecimal} | |
| 188 | + * {@code i} added to that of the {@code BigDecimal} | |
| 189 | + * {@code j}." The pseudo-code expression {@code (i == j)} is | |
| 190 | + * shorthand for "{@code true} if and only if the | |
| 191 | + * {@code BigDecimal} {@code i} represents the same value as the | |
| 192 | + * {@code BigDecimal} {@code j}." Other pseudo-code expressions | |
| 193 | + * are interpreted similarly. Square brackets are used to represent | |
| 194 | + * the particular {@code BigInteger} and scale pair defining a | |
| 195 | + * {@code BigDecimal} value; for example [19, 2] is the | |
| 196 | + * {@code BigDecimal} numerically equal to 0.19 having a scale of 2. | |
| 197 | + * | |
| 198 | + * <p>Note: care should be exercised if {@code BigDecimal} objects | |
| 199 | + * are used as keys in a {@link java.util.SortedMap SortedMap} or | |
| 200 | + * elements in a {@link java.util.SortedSet SortedSet} since | |
| 201 | + * {@code BigDecimal}'s <i>natural ordering</i> is <i>inconsistent | |
| 202 | + * with equals</i>. See {@link Comparable}, {@link | |
| 203 | + * java.util.SortedMap} or {@link java.util.SortedSet} for more | |
| 204 | + * information. | |
| 205 | + * | |
| 206 | + * <p>All methods and constructors for this class throw | |
| 207 | + * {@code NullPointerException} when passed a {@code null} object | |
| 208 | + * reference for any input parameter. | |
| 209 | + * | |
| 210 | + * @see BigInteger | |
| 211 | + * @see MathContext | |
| 212 | + * @see RoundingMode | |
| 213 | + * @see java.util.SortedMap | |
| 214 | + * @see java.util.SortedSet | |
| 215 | + * @author Josh Bloch | |
| 216 | + * @author Mike Cowlishaw | |
| 217 | + * @author Joseph D. Darcy | |
| 218 | + */ | |
| 219 | +public class BigDecimal extends Number implements Comparable<BigDecimal> { | |
| 220 | + /** | |
| 221 | + * The unscaled value of this BigDecimal, as returned by {@link | |
| 222 | + * #unscaledValue}. | |
| 223 | + * | |
| 224 | + * @serial | |
| 225 | + * @see #unscaledValue | |
| 226 | + */ | |
| 227 | + private volatile BigInteger intVal; | |
| 228 | + | |
| 229 | + /** | |
| 230 | + * The scale of this BigDecimal, as returned by {@link #scale}. | |
| 231 | + * | |
| 232 | + * @serial | |
| 233 | + * @see #scale | |
| 234 | + */ | |
| 235 | + private int scale; // Note: this may have any value, so | |
| 236 | + // calculations must be done in longs | |
| 237 | + /** | |
| 238 | + * The number of decimal digits in this BigDecimal, or 0 if the | |
| 239 | + * number of digits are not known (lookaside information). If | |
| 240 | + * nonzero, the value is guaranteed correct. Use the precision() | |
| 241 | + * method to obtain and set the value if it might be 0. This | |
| 242 | + * field is mutable until set nonzero. | |
| 243 | + * | |
| 244 | + * @since 1.5 | |
| 245 | + */ | |
| 246 | + private transient int precision; | |
| 247 | + | |
| 248 | + /** | |
| 249 | + * Used to store the canonical string representation, if computed. | |
| 250 | + */ | |
| 251 | + private transient String stringCache; | |
| 252 | + | |
| 253 | + /** | |
| 254 | + * Sentinel value for {@link #intCompact} indicating the | |
| 255 | + * significand information is only available from {@code intVal}. | |
| 256 | + */ | |
| 257 | + static final long INFLATED = Long.MIN_VALUE; | |
| 258 | + | |
| 259 | + /** | |
| 260 | + * If the absolute value of the significand of this BigDecimal is | |
| 261 | + * less than or equal to {@code Long.MAX_VALUE}, the value can be | |
| 262 | + * compactly stored in this field and used in computations. | |
| 263 | + */ | |
| 264 | + private transient long intCompact; | |
| 265 | + | |
| 266 | + // All 18-digit base ten strings fit into a long; not all 19-digit | |
| 267 | + // strings will | |
| 268 | + private static final int MAX_COMPACT_DIGITS = 18; | |
| 269 | + | |
| 270 | + private static final int MAX_BIGINT_BITS = 62; | |
| 271 | + | |
| 272 | + /* Appease the serialization gods */ | |
| 273 | + private static final long serialVersionUID = 6108874887143696463L; | |
| 274 | + | |
| 275 | + private static final ThreadLocal<StringBuilderHelper> | |
| 276 | + threadLocalStringBuilderHelper = new ThreadLocal<StringBuilderHelper>() { | |
| 277 | + @Override | |
| 278 | + protected StringBuilderHelper initialValue() { | |
| 279 | + return new StringBuilderHelper(); | |
| 280 | + } | |
| 281 | + }; | |
| 282 | + | |
| 283 | + // Cache of common small BigDecimal values. | |
| 284 | + private static final BigDecimal zeroThroughTen[] = { | |
| 285 | + new BigDecimal(BigInteger.ZERO, 0, 0, 1), | |
| 286 | + new BigDecimal(BigInteger.ONE, 1, 0, 1), | |
| 287 | + new BigDecimal(BigInteger.valueOf(2), 2, 0, 1), | |
| 288 | + new BigDecimal(BigInteger.valueOf(3), 3, 0, 1), | |
| 289 | + new BigDecimal(BigInteger.valueOf(4), 4, 0, 1), | |
| 290 | + new BigDecimal(BigInteger.valueOf(5), 5, 0, 1), | |
| 291 | + new BigDecimal(BigInteger.valueOf(6), 6, 0, 1), | |
| 292 | + new BigDecimal(BigInteger.valueOf(7), 7, 0, 1), | |
| 293 | + new BigDecimal(BigInteger.valueOf(8), 8, 0, 1), | |
| 294 | + new BigDecimal(BigInteger.valueOf(9), 9, 0, 1), | |
| 295 | + new BigDecimal(BigInteger.TEN, 10, 0, 2), | |
| 296 | + }; | |
| 297 | + | |
| 298 | + // Cache of zero scaled by 0 - 15 | |
| 299 | + private static final BigDecimal[] ZERO_SCALED_BY = { | |
| 300 | + zeroThroughTen[0], | |
| 301 | + new BigDecimal(BigInteger.ZERO, 0, 1, 1), | |
| 302 | + new BigDecimal(BigInteger.ZERO, 0, 2, 1), | |
| 303 | + new BigDecimal(BigInteger.ZERO, 0, 3, 1), | |
| 304 | + new BigDecimal(BigInteger.ZERO, 0, 4, 1), | |
| 305 | + new BigDecimal(BigInteger.ZERO, 0, 5, 1), | |
| 306 | + new BigDecimal(BigInteger.ZERO, 0, 6, 1), | |
| 307 | + new BigDecimal(BigInteger.ZERO, 0, 7, 1), | |
| 308 | + new BigDecimal(BigInteger.ZERO, 0, 8, 1), | |
| 309 | + new BigDecimal(BigInteger.ZERO, 0, 9, 1), | |
| 310 | + new BigDecimal(BigInteger.ZERO, 0, 10, 1), | |
| 311 | + new BigDecimal(BigInteger.ZERO, 0, 11, 1), | |
| 312 | + new BigDecimal(BigInteger.ZERO, 0, 12, 1), | |
| 313 | + new BigDecimal(BigInteger.ZERO, 0, 13, 1), | |
| 314 | + new BigDecimal(BigInteger.ZERO, 0, 14, 1), | |
| 315 | + new BigDecimal(BigInteger.ZERO, 0, 15, 1), | |
| 316 | + }; | |
| 317 | + | |
| 318 | + // Half of Long.MIN_VALUE & Long.MAX_VALUE. | |
| 319 | + private static final long HALF_LONG_MAX_VALUE = Long.MAX_VALUE / 2; | |
| 320 | + private static final long HALF_LONG_MIN_VALUE = Long.MIN_VALUE / 2; | |
| 321 | + | |
| 322 | + // Constants | |
| 323 | + /** | |
| 324 | + * The value 0, with a scale of 0. | |
| 325 | + * | |
| 326 | + * @since 1.5 | |
| 327 | + */ | |
| 328 | + public static final BigDecimal ZERO = | |
| 329 | + zeroThroughTen[0]; | |
| 330 | + | |
| 331 | + /** | |
| 332 | + * The value 1, with a scale of 0. | |
| 333 | + * | |
| 334 | + * @since 1.5 | |
| 335 | + */ | |
| 336 | + public static final BigDecimal ONE = | |
| 337 | + zeroThroughTen[1]; | |
| 338 | + | |
| 339 | + /** | |
| 340 | + * The value 10, with a scale of 0. | |
| 341 | + * | |
| 342 | + * @since 1.5 | |
| 343 | + */ | |
| 344 | + public static final BigDecimal TEN = | |
| 345 | + zeroThroughTen[10]; | |
| 346 | + | |
| 347 | + // Constructors | |
| 348 | + | |
| 349 | + /** | |
| 350 | + * Trusted package private constructor. | |
| 351 | + * Trusted simply means if val is INFLATED, intVal could not be null and | |
| 352 | + * if intVal is null, val could not be INFLATED. | |
| 353 | + */ | |
| 354 | + BigDecimal(BigInteger intVal, long val, int scale, int prec) { | |
| 355 | + this.scale = scale; | |
| 356 | + this.precision = prec; | |
| 357 | + this.intCompact = val; | |
| 358 | + this.intVal = intVal; | |
| 359 | + } | |
| 360 | + | |
| 361 | + /** | |
| 362 | + * Translates a character array representation of a | |
| 363 | + * {@code BigDecimal} into a {@code BigDecimal}, accepting the | |
| 364 | + * same sequence of characters as the {@link #BigDecimal(String)} | |
| 365 | + * constructor, while allowing a sub-array to be specified. | |
| 366 | + * | |
| 367 | + * <p>Note that if the sequence of characters is already available | |
| 368 | + * within a character array, using this constructor is faster than | |
| 369 | + * converting the {@code char} array to string and using the | |
| 370 | + * {@code BigDecimal(String)} constructor . | |
| 371 | + * | |
| 372 | + * @param in {@code char} array that is the source of characters. | |
| 373 | + * @param offset first character in the array to inspect. | |
| 374 | + * @param len number of characters to consider. | |
| 375 | + * @throws NumberFormatException if {@code in} is not a valid | |
| 376 | + * representation of a {@code BigDecimal} or the defined subarray | |
| 377 | + * is not wholly within {@code in}. | |
| 378 | + * @since 1.5 | |
| 379 | + */ | |
| 380 | + public BigDecimal(char[] in, int offset, int len) { | |
| 381 | + // protect against huge length. | |
| 382 | + if (offset+len > in.length || offset < 0) | |
| 383 | + throw new NumberFormatException(); | |
| 384 | + // This is the primary string to BigDecimal constructor; all | |
| 385 | + // incoming strings end up here; it uses explicit (inline) | |
| 386 | + // parsing for speed and generates at most one intermediate | |
| 387 | + // (temporary) object (a char[] array) for non-compact case. | |
| 388 | + | |
| 389 | + // Use locals for all fields values until completion | |
| 390 | + int prec = 0; // record precision value | |
| 391 | + int scl = 0; // record scale value | |
| 392 | + long rs = 0; // the compact value in long | |
| 393 | + BigInteger rb = null; // the inflated value in BigInteger | |
| 394 | + | |
| 395 | + // use array bounds checking to handle too-long, len == 0, | |
| 396 | + // bad offset, etc. | |
| 397 | + try { | |
| 398 | + // handle the sign | |
| 399 | + boolean isneg = false; // assume positive | |
| 400 | + if (in[offset] == '-') { | |
| 401 | + isneg = true; // leading minus means negative | |
| 402 | + offset++; | |
| 403 | + len--; | |
| 404 | + } else if (in[offset] == '+') { // leading + allowed | |
| 405 | + offset++; | |
| 406 | + len--; | |
| 407 | + } | |
| 408 | + | |
| 409 | + // should now be at numeric part of the significand | |
| 410 | + boolean dot = false; // true when there is a '.' | |
| 411 | + int cfirst = offset; // record start of integer | |
| 412 | + long exp = 0; // exponent | |
| 413 | + char c; // current character | |
| 414 | + | |
| 415 | + boolean isCompact = (len <= MAX_COMPACT_DIGITS); | |
| 416 | + // integer significand array & idx is the index to it. The array | |
| 417 | + // is ONLY used when we can't use a compact representation. | |
| 418 | + char coeff[] = isCompact ? null : new char[len]; | |
| 419 | + int idx = 0; | |
| 420 | + | |
| 421 | + for (; len > 0; offset++, len--) { | |
| 422 | + c = in[offset]; | |
| 423 | + // have digit | |
| 424 | + if ((c >= '0' && c <= '9') || Character.isDigit(c)) { | |
| 425 | + // First compact case, we need not to preserve the character | |
| 426 | + // and we can just compute the value in place. | |
| 427 | + if (isCompact) { | |
| 428 | + int digit = Character.digit(c, 10); | |
| 429 | + if (digit == 0) { | |
| 430 | + if (prec == 0) | |
| 431 | + prec = 1; | |
| 432 | + else if (rs != 0) { | |
| 433 | + rs *= 10; | |
| 434 | + ++prec; | |
| 435 | + } // else digit is a redundant leading zero | |
| 436 | + } else { | |
| 437 | + if (prec != 1 || rs != 0) | |
| 438 | + ++prec; // prec unchanged if preceded by 0s | |
| 439 | + rs = rs * 10 + digit; | |
| 440 | + } | |
| 441 | + } else { // the unscaled value is likely a BigInteger object. | |
| 442 | + if (c == '0' || Character.digit(c, 10) == 0) { | |
| 443 | + if (prec == 0) { | |
| 444 | + coeff[idx] = c; | |
| 445 | + prec = 1; | |
| 446 | + } else if (idx != 0) { | |
| 447 | + coeff[idx++] = c; | |
| 448 | + ++prec; | |
| 449 | + } // else c must be a redundant leading zero | |
| 450 | + } else { | |
| 451 | + if (prec != 1 || idx != 0) | |
| 452 | + ++prec; // prec unchanged if preceded by 0s | |
| 453 | + coeff[idx++] = c; | |
| 454 | + } | |
| 455 | + } | |
| 456 | + if (dot) | |
| 457 | + ++scl; | |
| 458 | + continue; | |
| 459 | + } | |
| 460 | + // have dot | |
| 461 | + if (c == '.') { | |
| 462 | + // have dot | |
| 463 | + if (dot) // two dots | |
| 464 | + throw new NumberFormatException(); | |
| 465 | + dot = true; | |
| 466 | + continue; | |
| 467 | + } | |
| 468 | + // exponent expected | |
| 469 | + if ((c != 'e') && (c != 'E')) | |
| 470 | + throw new NumberFormatException(); | |
| 471 | + offset++; | |
| 472 | + c = in[offset]; | |
| 473 | + len--; | |
| 474 | + boolean negexp = (c == '-'); | |
| 475 | + // optional sign | |
| 476 | + if (negexp || c == '+') { | |
| 477 | + offset++; | |
| 478 | + c = in[offset]; | |
| 479 | + len--; | |
| 480 | + } | |
| 481 | + if (len <= 0) // no exponent digits | |
| 482 | + throw new NumberFormatException(); | |
| 483 | + // skip leading zeros in the exponent | |
| 484 | + while (len > 10 && Character.digit(c, 10) == 0) { | |
| 485 | + offset++; | |
| 486 | + c = in[offset]; | |
| 487 | + len--; | |
| 488 | + } | |
| 489 | + if (len > 10) // too many nonzero exponent digits | |
| 490 | + throw new NumberFormatException(); | |
| 491 | + // c now holds first digit of exponent | |
| 492 | + for (;; len--) { | |
| 493 | + int v; | |
| 494 | + if (c >= '0' && c <= '9') { | |
| 495 | + v = c - '0'; | |
| 496 | + } else { | |
| 497 | + v = Character.digit(c, 10); | |
| 498 | + if (v < 0) // not a digit | |
| 499 | + throw new NumberFormatException(); | |
| 500 | + } | |
| 501 | + exp = exp * 10 + v; | |
| 502 | + if (len == 1) | |
| 503 | + break; // that was final character | |
| 504 | + offset++; | |
| 505 | + c = in[offset]; | |
| 506 | + } | |
| 507 | + if (negexp) // apply sign | |
| 508 | + exp = -exp; | |
| 509 | + // Next test is required for backwards compatibility | |
| 510 | + if ((int)exp != exp) // overflow | |
| 511 | + throw new NumberFormatException(); | |
| 512 | + break; // [saves a test] | |
| 513 | + } | |
| 514 | + // here when no characters left | |
| 515 | + if (prec == 0) // no digits found | |
| 516 | + throw new NumberFormatException(); | |
| 517 | + | |
| 518 | + // Adjust scale if exp is not zero. | |
| 519 | + if (exp != 0) { // had significant exponent | |
| 520 | + // Can't call checkScale which relies on proper fields value | |
| 521 | + long adjustedScale = scl - exp; | |
| 522 | + if (adjustedScale > Integer.MAX_VALUE || | |
| 523 | + adjustedScale < Integer.MIN_VALUE) | |
| 524 | + throw new NumberFormatException("Scale out of range."); | |
| 525 | + scl = (int)adjustedScale; | |
| 526 | + } | |
| 527 | + | |
| 528 | + // Remove leading zeros from precision (digits count) | |
| 529 | + if (isCompact) { | |
| 530 | + rs = isneg ? -rs : rs; | |
| 531 | + } else { | |
| 532 | + char quick[]; | |
| 533 | + if (!isneg) { | |
| 534 | + quick = (coeff.length != prec) ? | |
| 535 | + Arrays.copyOf(coeff, prec) : coeff; | |
| 536 | + } else { | |
| 537 | + quick = new char[prec + 1]; | |
| 538 | + quick[0] = '-'; | |
| 539 | + System.arraycopy(coeff, 0, quick, 1, prec); | |
| 540 | + } | |
| 541 | + rb = new BigInteger(quick); | |
| 542 | + rs = compactValFor(rb); | |
| 543 | + } | |
| 544 | + } catch (ArrayIndexOutOfBoundsException e) { | |
| 545 | + throw new NumberFormatException(); | |
| 546 | + } catch (NegativeArraySizeException e) { | |
| 547 | + throw new NumberFormatException(); | |
| 548 | + } | |
| 549 | + this.scale = scl; | |
| 550 | + this.precision = prec; | |
| 551 | + this.intCompact = rs; | |
| 552 | + this.intVal = (rs != INFLATED) ? null : rb; | |
| 553 | + } | |
| 554 | + | |
| 555 | + /** | |
| 556 | + * Translates a character array representation of a | |
| 557 | + * {@code BigDecimal} into a {@code BigDecimal}, accepting the | |
| 558 | + * same sequence of characters as the {@link #BigDecimal(String)} | |
| 559 | + * constructor, while allowing a sub-array to be specified and | |
| 560 | + * with rounding according to the context settings. | |
| 561 | + * | |
| 562 | + * <p>Note that if the sequence of characters is already available | |
| 563 | + * within a character array, using this constructor is faster than | |
| 564 | + * converting the {@code char} array to string and using the | |
| 565 | + * {@code BigDecimal(String)} constructor . | |
| 566 | + * | |
| 567 | + * @param in {@code char} array that is the source of characters. | |
| 568 | + * @param offset first character in the array to inspect. | |
| 569 | + * @param len number of characters to consider.. | |
| 570 | + * @param mc the context to use. | |
| 571 | + * @throws ArithmeticException if the result is inexact but the | |
| 572 | + * rounding mode is {@code UNNECESSARY}. | |
| 573 | + * @throws NumberFormatException if {@code in} is not a valid | |
| 574 | + * representation of a {@code BigDecimal} or the defined subarray | |
| 575 | + * is not wholly within {@code in}. | |
| 576 | + * @since 1.5 | |
| 577 | + */ | |
| 578 | + public BigDecimal(char[] in, int offset, int len, MathContext mc) { | |
| 579 | + this(in, offset, len); | |
| 580 | + if (mc.precision > 0) | |
| 581 | + roundThis(mc); | |
| 582 | + } | |
| 583 | + | |
| 584 | + /** | |
| 585 | + * Translates a character array representation of a | |
| 586 | + * {@code BigDecimal} into a {@code BigDecimal}, accepting the | |
| 587 | + * same sequence of characters as the {@link #BigDecimal(String)} | |
| 588 | + * constructor. | |
| 589 | + * | |
| 590 | + * <p>Note that if the sequence of characters is already available | |
| 591 | + * as a character array, using this constructor is faster than | |
| 592 | + * converting the {@code char} array to string and using the | |
| 593 | + * {@code BigDecimal(String)} constructor . | |
| 594 | + * | |
| 595 | + * @param in {@code char} array that is the source of characters. | |
| 596 | + * @throws NumberFormatException if {@code in} is not a valid | |
| 597 | + * representation of a {@code BigDecimal}. | |
| 598 | + * @since 1.5 | |
| 599 | + */ | |
| 600 | + public BigDecimal(char[] in) { | |
| 601 | + this(in, 0, in.length); | |
| 602 | + } | |
| 603 | + | |
| 604 | + /** | |
| 605 | + * Translates a character array representation of a | |
| 606 | + * {@code BigDecimal} into a {@code BigDecimal}, accepting the | |
| 607 | + * same sequence of characters as the {@link #BigDecimal(String)} | |
| 608 | + * constructor and with rounding according to the context | |
| 609 | + * settings. | |
| 610 | + * | |
| 611 | + * <p>Note that if the sequence of characters is already available | |
| 612 | + * as a character array, using this constructor is faster than | |
| 613 | + * converting the {@code char} array to string and using the | |
| 614 | + * {@code BigDecimal(String)} constructor . | |
| 615 | + * | |
| 616 | + * @param in {@code char} array that is the source of characters. | |
| 617 | + * @param mc the context to use. | |
| 618 | + * @throws ArithmeticException if the result is inexact but the | |
| 619 | + * rounding mode is {@code UNNECESSARY}. | |
| 620 | + * @throws NumberFormatException if {@code in} is not a valid | |
| 621 | + * representation of a {@code BigDecimal}. | |
| 622 | + * @since 1.5 | |
| 623 | + */ | |
| 624 | + public BigDecimal(char[] in, MathContext mc) { | |
| 625 | + this(in, 0, in.length, mc); | |
| 626 | + } | |
| 627 | + | |
| 628 | + /** | |
| 629 | + * Translates the string representation of a {@code BigDecimal} | |
| 630 | + * into a {@code BigDecimal}. The string representation consists | |
| 631 | + * of an optional sign, {@code '+'} (<tt> '\u002B'</tt>) or | |
| 632 | + * {@code '-'} (<tt>'\u002D'</tt>), followed by a sequence of | |
| 633 | + * zero or more decimal digits ("the integer"), optionally | |
| 634 | + * followed by a fraction, optionally followed by an exponent. | |
| 635 | + * | |
| 636 | + * <p>The fraction consists of a decimal point followed by zero | |
| 637 | + * or more decimal digits. The string must contain at least one | |
| 638 | + * digit in either the integer or the fraction. The number formed | |
| 639 | + * by the sign, the integer and the fraction is referred to as the | |
| 640 | + * <i>significand</i>. | |
| 641 | + * | |
| 642 | + * <p>The exponent consists of the character {@code 'e'} | |
| 643 | + * (<tt>'\u0065'</tt>) or {@code 'E'} (<tt>'\u0045'</tt>) | |
| 644 | + * followed by one or more decimal digits. The value of the | |
| 645 | + * exponent must lie between -{@link Integer#MAX_VALUE} ({@link | |
| 646 | + * Integer#MIN_VALUE}+1) and {@link Integer#MAX_VALUE}, inclusive. | |
| 647 | + * | |
| 648 | + * <p>More formally, the strings this constructor accepts are | |
| 649 | + * described by the following grammar: | |
| 650 | + * <blockquote> | |
| 651 | + * <dl> | |
| 652 | + * <dt><i>BigDecimalString:</i> | |
| 653 | + * <dd><i>Sign<sub>opt</sub> Significand Exponent<sub>opt</sub></i> | |
| 654 | + * <p> | |
| 655 | + * <dt><i>Sign:</i> | |
| 656 | + * <dd>{@code +} | |
| 657 | + * <dd>{@code -} | |
| 658 | + * <p> | |
| 659 | + * <dt><i>Significand:</i> | |
| 660 | + * <dd><i>IntegerPart</i> {@code .} <i>FractionPart<sub>opt</sub></i> | |
| 661 | + * <dd>{@code .} <i>FractionPart</i> | |
| 662 | + * <dd><i>IntegerPart</i> | |
| 663 | + * <p> | |
| 664 | + * <dt><i>IntegerPart:</i> | |
| 665 | + * <dd><i>Digits</i> | |
| 666 | + * <p> | |
| 667 | + * <dt><i>FractionPart:</i> | |
| 668 | + * <dd><i>Digits</i> | |
| 669 | + * <p> | |
| 670 | + * <dt><i>Exponent:</i> | |
| 671 | + * <dd><i>ExponentIndicator SignedInteger</i> | |
| 672 | + * <p> | |
| 673 | + * <dt><i>ExponentIndicator:</i> | |
| 674 | + * <dd>{@code e} | |
| 675 | + * <dd>{@code E} | |
| 676 | + * <p> | |
| 677 | + * <dt><i>SignedInteger:</i> | |
| 678 | + * <dd><i>Sign<sub>opt</sub> Digits</i> | |
| 679 | + * <p> | |
| 680 | + * <dt><i>Digits:</i> | |
| 681 | + * <dd><i>Digit</i> | |
| 682 | + * <dd><i>Digits Digit</i> | |
| 683 | + * <p> | |
| 684 | + * <dt><i>Digit:</i> | |
| 685 | + * <dd>any character for which {@link Character#isDigit} | |
| 686 | + * returns {@code true}, including 0, 1, 2 ... | |
| 687 | + * </dl> | |
| 688 | + * </blockquote> | |
| 689 | + * | |
| 690 | + * <p>The scale of the returned {@code BigDecimal} will be the | |
| 691 | + * number of digits in the fraction, or zero if the string | |
| 692 | + * contains no decimal point, subject to adjustment for any | |
| 693 | + * exponent; if the string contains an exponent, the exponent is | |
| 694 | + * subtracted from the scale. The value of the resulting scale | |
| 695 | + * must lie between {@code Integer.MIN_VALUE} and | |
| 696 | + * {@code Integer.MAX_VALUE}, inclusive. | |
| 697 | + * | |
| 698 | + * <p>The character-to-digit mapping is provided by {@link | |
| 699 | + * java.lang.Character#digit} set to convert to radix 10. The | |
| 700 | + * String may not contain any extraneous characters (whitespace, | |
| 701 | + * for example). | |
| 702 | + * | |
| 703 | + * <p><b>Examples:</b><br> | |
| 704 | + * The value of the returned {@code BigDecimal} is equal to | |
| 705 | + * <i>significand</i> × 10<sup> <i>exponent</i></sup>. | |
| 706 | + * For each string on the left, the resulting representation | |
| 707 | + * [{@code BigInteger}, {@code scale}] is shown on the right. | |
| 708 | + * <pre> | |
| 709 | + * "0" [0,0] | |
| 710 | + * "0.00" [0,2] | |
| 711 | + * "123" [123,0] | |
| 712 | + * "-123" [-123,0] | |
| 713 | + * "1.23E3" [123,-1] | |
| 714 | + * "1.23E+3" [123,-1] | |
| 715 | + * "12.3E+7" [123,-6] | |
| 716 | + * "12.0" [120,1] | |
| 717 | + * "12.3" [123,1] | |
| 718 | + * "0.00123" [123,5] | |
| 719 | + * "-1.23E-12" [-123,14] | |
| 720 | + * "1234.5E-4" [12345,5] | |
| 721 | + * "0E+7" [0,-7] | |
| 722 | + * "-0" [0,0] | |
| 723 | + * </pre> | |
| 724 | + * | |
| 725 | + * <p>Note: For values other than {@code float} and | |
| 726 | + * {@code double} NaN and ±Infinity, this constructor is | |
| 727 | + * compatible with the values returned by {@link Float#toString} | |
| 728 | + * and {@link Double#toString}. This is generally the preferred | |
| 729 | + * way to convert a {@code float} or {@code double} into a | |
| 730 | + * BigDecimal, as it doesn't suffer from the unpredictability of | |
| 731 | + * the {@link #BigDecimal(double)} constructor. | |
| 732 | + * | |
| 733 | + * @param val String representation of {@code BigDecimal}. | |
| 734 | + * | |
| 735 | + * @throws NumberFormatException if {@code val} is not a valid | |
| 736 | + * representation of a {@code BigDecimal}. | |
| 737 | + */ | |
| 738 | + public BigDecimal(String val) { | |
| 739 | + this(val.toCharArray(), 0, val.length()); | |
| 740 | + } | |
| 741 | + | |
| 742 | + /** | |
| 743 | + * Translates the string representation of a {@code BigDecimal} | |
| 744 | + * into a {@code BigDecimal}, accepting the same strings as the | |
| 745 | + * {@link #BigDecimal(String)} constructor, with rounding | |
| 746 | + * according to the context settings. | |
| 747 | + * | |
| 748 | + * @param val string representation of a {@code BigDecimal}. | |
| 749 | + * @param mc the context to use. | |
| 750 | + * @throws ArithmeticException if the result is inexact but the | |
| 751 | + * rounding mode is {@code UNNECESSARY}. | |
| 752 | + * @throws NumberFormatException if {@code val} is not a valid | |
| 753 | + * representation of a BigDecimal. | |
| 754 | + * @since 1.5 | |
| 755 | + */ | |
| 756 | + public BigDecimal(String val, MathContext mc) { | |
| 757 | + this(val.toCharArray(), 0, val.length()); | |
| 758 | + if (mc.precision > 0) | |
| 759 | + roundThis(mc); | |
| 760 | + } | |
| 761 | + | |
| 762 | + /** | |
| 763 | + * Translates a {@code double} into a {@code BigDecimal} which | |
| 764 | + * is the exact decimal representation of the {@code double}'s | |
| 765 | + * binary floating-point value. The scale of the returned | |
| 766 | + * {@code BigDecimal} is the smallest value such that | |
| 767 | + * <tt>(10<sup>scale</sup> × val)</tt> is an integer. | |
| 768 | + * <p> | |
| 769 | + * <b>Notes:</b> | |
| 770 | + * <ol> | |
| 771 | + * <li> | |
| 772 | + * The results of this constructor can be somewhat unpredictable. | |
| 773 | + * One might assume that writing {@code new BigDecimal(0.1)} in | |
| 774 | + * Java creates a {@code BigDecimal} which is exactly equal to | |
| 775 | + * 0.1 (an unscaled value of 1, with a scale of 1), but it is | |
| 776 | + * actually equal to | |
| 777 | + * 0.1000000000000000055511151231257827021181583404541015625. | |
| 778 | + * This is because 0.1 cannot be represented exactly as a | |
| 779 | + * {@code double} (or, for that matter, as a binary fraction of | |
| 780 | + * any finite length). Thus, the value that is being passed | |
| 781 | + * <i>in</i> to the constructor is not exactly equal to 0.1, | |
| 782 | + * appearances notwithstanding. | |
| 783 | + * | |
| 784 | + * <li> | |
| 785 | + * The {@code String} constructor, on the other hand, is | |
| 786 | + * perfectly predictable: writing {@code new BigDecimal("0.1")} | |
| 787 | + * creates a {@code BigDecimal} which is <i>exactly</i> equal to | |
| 788 | + * 0.1, as one would expect. Therefore, it is generally | |
| 789 | + * recommended that the {@linkplain #BigDecimal(String) | |
| 790 | + * <tt>String</tt> constructor} be used in preference to this one. | |
| 791 | + * | |
| 792 | + * <li> | |
| 793 | + * When a {@code double} must be used as a source for a | |
| 794 | + * {@code BigDecimal}, note that this constructor provides an | |
| 795 | + * exact conversion; it does not give the same result as | |
| 796 | + * converting the {@code double} to a {@code String} using the | |
| 797 | + * {@link Double#toString(double)} method and then using the | |
| 798 | + * {@link #BigDecimal(String)} constructor. To get that result, | |
| 799 | + * use the {@code static} {@link #valueOf(double)} method. | |
| 800 | + * </ol> | |
| 801 | + * | |
| 802 | + * @param val {@code double} value to be converted to | |
| 803 | + * {@code BigDecimal}. | |
| 804 | + * @throws NumberFormatException if {@code val} is infinite or NaN. | |
| 805 | + */ | |
| 806 | + public BigDecimal(double val) { | |
| 807 | + if (Double.isInfinite(val) || Double.isNaN(val)) | |
| 808 | + throw new NumberFormatException("Infinite or NaN"); | |
| 809 | + | |
| 810 | + // Translate the double into sign, exponent and significand, according | |
| 811 | + // to the formulae in JLS, Section 20.10.22. | |
| 812 | + long valBits = Double.doubleToLongBits(val); | |
| 813 | + int sign = ((valBits >> 63)==0 ? 1 : -1); | |
| 814 | + int exponent = (int) ((valBits >> 52) & 0x7ffL); | |
| 815 | + long significand = (exponent==0 ? (valBits & ((1L<<52) - 1)) << 1 | |
| 816 | + : (valBits & ((1L<<52) - 1)) | (1L<<52)); | |
| 817 | + exponent -= 1075; | |
| 818 | + // At this point, val == sign * significand * 2**exponent. | |
| 819 | + | |
| 820 | + /* | |
| 821 | + * Special case zero to supress nonterminating normalization | |
| 822 | + * and bogus scale calculation. | |
| 823 | + */ | |
| 824 | + if (significand == 0) { | |
| 825 | + intVal = BigInteger.ZERO; | |
| 826 | + intCompact = 0; | |
| 827 | + precision = 1; | |
| 828 | + return; | |
| 829 | + } | |
| 830 | + | |
| 831 | + // Normalize | |
| 832 | + while((significand & 1) == 0) { // i.e., significand is even | |
| 833 | + significand >>= 1; | |
| 834 | + exponent++; | |
| 835 | + } | |
| 836 | + | |
| 837 | + // Calculate intVal and scale | |
| 838 | + long s = sign * significand; | |
| 839 | + BigInteger b; | |
| 840 | + if (exponent < 0) { | |
| 841 | + b = BigInteger.valueOf(5).pow(-exponent).multiply(s); | |
| 842 | + scale = -exponent; | |
| 843 | + } else if (exponent > 0) { | |
| 844 | + b = BigInteger.valueOf(2).pow(exponent).multiply(s); | |
| 845 | + } else { | |
| 846 | + b = BigInteger.valueOf(s); | |
| 847 | + } | |
| 848 | + intCompact = compactValFor(b); | |
| 849 | + intVal = (intCompact != INFLATED) ? null : b; | |
| 850 | + } | |
| 851 | + | |
| 852 | + /** | |
| 853 | + * Translates a {@code double} into a {@code BigDecimal}, with | |
| 854 | + * rounding according to the context settings. The scale of the | |
| 855 | + * {@code BigDecimal} is the smallest value such that | |
| 856 | + * <tt>(10<sup>scale</sup> × val)</tt> is an integer. | |
| 857 | + * | |
| 858 | + * <p>The results of this constructor can be somewhat unpredictable | |
| 859 | + * and its use is generally not recommended; see the notes under | |
| 860 | + * the {@link #BigDecimal(double)} constructor. | |
| 861 | + * | |
| 862 | + * @param val {@code double} value to be converted to | |
| 863 | + * {@code BigDecimal}. | |
| 864 | + * @param mc the context to use. | |
| 865 | + * @throws ArithmeticException if the result is inexact but the | |
| 866 | + * RoundingMode is UNNECESSARY. | |
| 867 | + * @throws NumberFormatException if {@code val} is infinite or NaN. | |
| 868 | + * @since 1.5 | |
| 869 | + */ | |
| 870 | + public BigDecimal(double val, MathContext mc) { | |
| 871 | + this(val); | |
| 872 | + if (mc.precision > 0) | |
| 873 | + roundThis(mc); | |
| 874 | + } | |
| 875 | + | |
| 876 | + /** | |
| 877 | + * Translates a {@code BigInteger} into a {@code BigDecimal}. | |
| 878 | + * The scale of the {@code BigDecimal} is zero. | |
| 879 | + * | |
| 880 | + * @param val {@code BigInteger} value to be converted to | |
| 881 | + * {@code BigDecimal}. | |
| 882 | + */ | |
| 883 | + public BigDecimal(BigInteger val) { | |
| 884 | + intCompact = compactValFor(val); | |
| 885 | + intVal = (intCompact != INFLATED) ? null : val; | |
| 886 | + } | |
| 887 | + | |
| 888 | + /** | |
| 889 | + * Translates a {@code BigInteger} into a {@code BigDecimal} | |
| 890 | + * rounding according to the context settings. The scale of the | |
| 891 | + * {@code BigDecimal} is zero. | |
| 892 | + * | |
| 893 | + * @param val {@code BigInteger} value to be converted to | |
| 894 | + * {@code BigDecimal}. | |
| 895 | + * @param mc the context to use. | |
| 896 | + * @throws ArithmeticException if the result is inexact but the | |
| 897 | + * rounding mode is {@code UNNECESSARY}. | |
| 898 | + * @since 1.5 | |
| 899 | + */ | |
| 900 | + public BigDecimal(BigInteger val, MathContext mc) { | |
| 901 | + this(val); | |
| 902 | + if (mc.precision > 0) | |
| 903 | + roundThis(mc); | |
| 904 | + } | |
| 905 | + | |
| 906 | + /** | |
| 907 | + * Translates a {@code BigInteger} unscaled value and an | |
| 908 | + * {@code int} scale into a {@code BigDecimal}. The value of | |
| 909 | + * the {@code BigDecimal} is | |
| 910 | + * <tt>(unscaledVal × 10<sup>-scale</sup>)</tt>. | |
| 911 | + * | |
| 912 | + * @param unscaledVal unscaled value of the {@code BigDecimal}. | |
| 913 | + * @param scale scale of the {@code BigDecimal}. | |
| 914 | + */ | |
| 915 | + public BigDecimal(BigInteger unscaledVal, int scale) { | |
| 916 | + // Negative scales are now allowed | |
| 917 | + this(unscaledVal); | |
| 918 | + this.scale = scale; | |
| 919 | + } | |
| 920 | + | |
| 921 | + /** | |
| 922 | + * Translates a {@code BigInteger} unscaled value and an | |
| 923 | + * {@code int} scale into a {@code BigDecimal}, with rounding | |
| 924 | + * according to the context settings. The value of the | |
| 925 | + * {@code BigDecimal} is <tt>(unscaledVal × | |
| 926 | + * 10<sup>-scale</sup>)</tt>, rounded according to the | |
| 927 | + * {@code precision} and rounding mode settings. | |
| 928 | + * | |
| 929 | + * @param unscaledVal unscaled value of the {@code BigDecimal}. | |
| 930 | + * @param scale scale of the {@code BigDecimal}. | |
| 931 | + * @param mc the context to use. | |
| 932 | + * @throws ArithmeticException if the result is inexact but the | |
| 933 | + * rounding mode is {@code UNNECESSARY}. | |
| 934 | + * @since 1.5 | |
| 935 | + */ | |
| 936 | + public BigDecimal(BigInteger unscaledVal, int scale, MathContext mc) { | |
| 937 | + this(unscaledVal); | |
| 938 | + this.scale = scale; | |
| 939 | + if (mc.precision > 0) | |
| 940 | + roundThis(mc); | |
| 941 | + } | |
| 942 | + | |
| 943 | + /** | |
| 944 | + * Translates an {@code int} into a {@code BigDecimal}. The | |
| 945 | + * scale of the {@code BigDecimal} is zero. | |
| 946 | + * | |
| 947 | + * @param val {@code int} value to be converted to | |
| 948 | + * {@code BigDecimal}. | |
| 949 | + * @since 1.5 | |
| 950 | + */ | |
| 951 | + public BigDecimal(int val) { | |
| 952 | + intCompact = val; | |
| 953 | + } | |
| 954 | + | |
| 955 | + /** | |
| 956 | + * Translates an {@code int} into a {@code BigDecimal}, with | |
| 957 | + * rounding according to the context settings. The scale of the | |
| 958 | + * {@code BigDecimal}, before any rounding, is zero. | |
| 959 | + * | |
| 960 | + * @param val {@code int} value to be converted to {@code BigDecimal}. | |
| 961 | + * @param mc the context to use. | |
| 962 | + * @throws ArithmeticException if the result is inexact but the | |
| 963 | + * rounding mode is {@code UNNECESSARY}. | |
| 964 | + * @since 1.5 | |
| 965 | + */ | |
| 966 | + public BigDecimal(int val, MathContext mc) { | |
| 967 | + intCompact = val; | |
| 968 | + if (mc.precision > 0) | |
| 969 | + roundThis(mc); | |
| 970 | + } | |
| 971 | + | |
| 972 | + /** | |
| 973 | + * Translates a {@code long} into a {@code BigDecimal}. The | |
| 974 | + * scale of the {@code BigDecimal} is zero. | |
| 975 | + * | |
| 976 | + * @param val {@code long} value to be converted to {@code BigDecimal}. | |
| 977 | + * @since 1.5 | |
| 978 | + */ | |
| 979 | + public BigDecimal(long val) { | |
| 980 | + this.intCompact = val; | |
| 981 | + this.intVal = (val == INFLATED) ? BigInteger.valueOf(val) : null; | |
| 982 | + } | |
| 983 | + | |
| 984 | + /** | |
| 985 | + * Translates a {@code long} into a {@code BigDecimal}, with | |
| 986 | + * rounding according to the context settings. The scale of the | |
| 987 | + * {@code BigDecimal}, before any rounding, is zero. | |
| 988 | + * | |
| 989 | + * @param val {@code long} value to be converted to {@code BigDecimal}. | |
| 990 | + * @param mc the context to use. | |
| 991 | + * @throws ArithmeticException if the result is inexact but the | |
| 992 | + * rounding mode is {@code UNNECESSARY}. | |
| 993 | + * @since 1.5 | |
| 994 | + */ | |
| 995 | + public BigDecimal(long val, MathContext mc) { | |
| 996 | + this(val); | |
| 997 | + if (mc.precision > 0) | |
| 998 | + roundThis(mc); | |
| 999 | + } | |
| 1000 | + | |
| 1001 | + // Static Factory Methods | |
| 1002 | + | |
| 1003 | + /** | |
| 1004 | + * Translates a {@code long} unscaled value and an | |
| 1005 | + * {@code int} scale into a {@code BigDecimal}. This | |
| 1006 | + * {@literal "static factory method"} is provided in preference to | |
| 1007 | + * a ({@code long}, {@code int}) constructor because it | |
| 1008 | + * allows for reuse of frequently used {@code BigDecimal} values.. | |
| 1009 | + * | |
| 1010 | + * @param unscaledVal unscaled value of the {@code BigDecimal}. | |
| 1011 | + * @param scale scale of the {@code BigDecimal}. | |
| 1012 | + * @return a {@code BigDecimal} whose value is | |
| 1013 | + * <tt>(unscaledVal × 10<sup>-scale</sup>)</tt>. | |
| 1014 | + */ | |
| 1015 | + public static BigDecimal valueOf(long unscaledVal, int scale) { | |
| 1016 | + if (scale == 0) | |
| 1017 | + return valueOf(unscaledVal); | |
| 1018 | + else if (unscaledVal == 0) { | |
| 1019 | + if (scale > 0 && scale < ZERO_SCALED_BY.length) | |
| 1020 | + return ZERO_SCALED_BY[scale]; | |
| 1021 | + else | |
| 1022 | + return new BigDecimal(BigInteger.ZERO, 0, scale, 1); | |
| 1023 | + } | |
| 1024 | + return new BigDecimal(unscaledVal == INFLATED ? | |
| 1025 | + BigInteger.valueOf(unscaledVal) : null, | |
| 1026 | + unscaledVal, scale, 0); | |
| 1027 | + } | |
| 1028 | + | |
| 1029 | + /** | |
| 1030 | + * Translates a {@code long} value into a {@code BigDecimal} | |
| 1031 | + * with a scale of zero. This {@literal "static factory method"} | |
| 1032 | + * is provided in preference to a ({@code long}) constructor | |
| 1033 | + * because it allows for reuse of frequently used | |
| 1034 | + * {@code BigDecimal} values. | |
| 1035 | + * | |
| 1036 | + * @param val value of the {@code BigDecimal}. | |
| 1037 | + * @return a {@code BigDecimal} whose value is {@code val}. | |
| 1038 | + */ | |
| 1039 | + public static BigDecimal valueOf(long val) { | |
| 1040 | + if (val >= 0 && val < zeroThroughTen.length) | |
| 1041 | + return zeroThroughTen[(int)val]; | |
| 1042 | + else if (val != INFLATED) | |
| 1043 | + return new BigDecimal(null, val, 0, 0); | |
| 1044 | + return new BigDecimal(BigInteger.valueOf(val), val, 0, 0); | |
| 1045 | + } | |
| 1046 | + | |
| 1047 | + /** | |
| 1048 | + * Translates a {@code double} into a {@code BigDecimal}, using | |
| 1049 | + * the {@code double}'s canonical string representation provided | |
| 1050 | + * by the {@link Double#toString(double)} method. | |
| 1051 | + * | |
| 1052 | + * <p><b>Note:</b> This is generally the preferred way to convert | |
| 1053 | + * a {@code double} (or {@code float}) into a | |
| 1054 | + * {@code BigDecimal}, as the value returned is equal to that | |
| 1055 | + * resulting from constructing a {@code BigDecimal} from the | |
| 1056 | + * result of using {@link Double#toString(double)}. | |
| 1057 | + * | |
| 1058 | + * @param val {@code double} to convert to a {@code BigDecimal}. | |
| 1059 | + * @return a {@code BigDecimal} whose value is equal to or approximately | |
| 1060 | + * equal to the value of {@code val}. | |
| 1061 | + * @throws NumberFormatException if {@code val} is infinite or NaN. | |
| 1062 | + * @since 1.5 | |
| 1063 | + */ | |
| 1064 | + public static BigDecimal valueOf(double val) { | |
| 1065 | + // Reminder: a zero double returns '0.0', so we cannot fastpath | |
| 1066 | + // to use the constant ZERO. This might be important enough to | |
| 1067 | + // justify a factory approach, a cache, or a few private | |
| 1068 | + // constants, later. | |
| 1069 | + return new BigDecimal(Double.toString(val)); | |
| 1070 | + } | |
| 1071 | + | |
| 1072 | + // Arithmetic Operations | |
| 1073 | + /** | |
| 1074 | + * Returns a {@code BigDecimal} whose value is {@code (this + | |
| 1075 | + * augend)}, and whose scale is {@code max(this.scale(), | |
| 1076 | + * augend.scale())}. | |
| 1077 | + * | |
| 1078 | + * @param augend value to be added to this {@code BigDecimal}. | |
| 1079 | + * @return {@code this + augend} | |
| 1080 | + */ | |
| 1081 | + public BigDecimal add(BigDecimal augend) { | |
| 1082 | + long xs = this.intCompact; | |
| 1083 | + long ys = augend.intCompact; | |
| 1084 | + BigInteger fst = (xs != INFLATED) ? null : this.intVal; | |
| 1085 | + BigInteger snd = (ys != INFLATED) ? null : augend.intVal; | |
| 1086 | + int rscale = this.scale; | |
| 1087 | + | |
| 1088 | + long sdiff = (long)rscale - augend.scale; | |
| 1089 | + if (sdiff != 0) { | |
| 1090 | + if (sdiff < 0) { | |
| 1091 | + int raise = checkScale(-sdiff); | |
| 1092 | + rscale = augend.scale; | |
| 1093 | + if (xs == INFLATED || | |
| 1094 | + (xs = longMultiplyPowerTen(xs, raise)) == INFLATED) | |
| 1095 | + fst = bigMultiplyPowerTen(raise); | |
| 1096 | + } else { | |
| 1097 | + int raise = augend.checkScale(sdiff); | |
| 1098 | + if (ys == INFLATED || | |
| 1099 | + (ys = longMultiplyPowerTen(ys, raise)) == INFLATED) | |
| 1100 | + snd = augend.bigMultiplyPowerTen(raise); | |
| 1101 | + } | |
| 1102 | + } | |
| 1103 | + if (xs != INFLATED && ys != INFLATED) { | |
| 1104 | + long sum = xs + ys; | |
| 1105 | + // See "Hacker's Delight" section 2-12 for explanation of | |
| 1106 | + // the overflow test. | |
| 1107 | + if ( (((sum ^ xs) & (sum ^ ys))) >= 0L) // not overflowed | |
| 1108 | + return BigDecimal.valueOf(sum, rscale); | |
| 1109 | + } | |
| 1110 | + if (fst == null) | |
| 1111 | + fst = BigInteger.valueOf(xs); | |
| 1112 | + if (snd == null) | |
| 1113 | + snd = BigInteger.valueOf(ys); | |
| 1114 | + BigInteger sum = fst.add(snd); | |
| 1115 | + return (fst.signum == snd.signum) ? | |
| 1116 | + new BigDecimal(sum, INFLATED, rscale, 0) : | |
| 1117 | + new BigDecimal(sum, rscale); | |
| 1118 | + } | |
| 1119 | + | |
| 1120 | + /** | |
| 1121 | + * Returns a {@code BigDecimal} whose value is {@code (this + augend)}, | |
| 1122 | + * with rounding according to the context settings. | |
| 1123 | + * | |
| 1124 | + * If either number is zero and the precision setting is nonzero then | |
| 1125 | + * the other number, rounded if necessary, is used as the result. | |
| 1126 | + * | |
| 1127 | + * @param augend value to be added to this {@code BigDecimal}. | |
| 1128 | + * @param mc the context to use. | |
| 1129 | + * @return {@code this + augend}, rounded as necessary. | |
| 1130 | + * @throws ArithmeticException if the result is inexact but the | |
| 1131 | + * rounding mode is {@code UNNECESSARY}. | |
| 1132 | + * @since 1.5 | |
| 1133 | + */ | |
| 1134 | + public BigDecimal add(BigDecimal augend, MathContext mc) { | |
| 1135 | + if (mc.precision == 0) | |
| 1136 | + return add(augend); | |
| 1137 | + BigDecimal lhs = this; | |
| 1138 | + | |
| 1139 | + // Could optimize if values are compact | |
| 1140 | + this.inflate(); | |
| 1141 | + augend.inflate(); | |
| 1142 | + | |
| 1143 | + // If either number is zero then the other number, rounded and | |
| 1144 | + // scaled if necessary, is used as the result. | |
| 1145 | + { | |
| 1146 | + boolean lhsIsZero = lhs.signum() == 0; | |
| 1147 | + boolean augendIsZero = augend.signum() == 0; | |
| 1148 | + | |
| 1149 | + if (lhsIsZero || augendIsZero) { | |
| 1150 | + int preferredScale = Math.max(lhs.scale(), augend.scale()); | |
| 1151 | + BigDecimal result; | |
| 1152 | + | |
| 1153 | + // Could use a factory for zero instead of a new object | |
| 1154 | + if (lhsIsZero && augendIsZero) | |
| 1155 | + return new BigDecimal(BigInteger.ZERO, 0, preferredScale, 0); | |
| 1156 | + | |
| 1157 | + result = lhsIsZero ? doRound(augend, mc) : doRound(lhs, mc); | |
| 1158 | + | |
| 1159 | + if (result.scale() == preferredScale) | |
| 1160 | + return result; | |
| 1161 | + else if (result.scale() > preferredScale) { | |
| 1162 | + BigDecimal scaledResult = | |
| 1163 | + new BigDecimal(result.intVal, result.intCompact, | |
| 1164 | + result.scale, 0); | |
| 1165 | + scaledResult.stripZerosToMatchScale(preferredScale); | |
| 1166 | + return scaledResult; | |
| 1167 | + } else { // result.scale < preferredScale | |
| 1168 | + int precisionDiff = mc.precision - result.precision(); | |
| 1169 | + int scaleDiff = preferredScale - result.scale(); | |
| 1170 | + | |
| 1171 | + if (precisionDiff >= scaleDiff) | |
| 1172 | + return result.setScale(preferredScale); // can achieve target scale | |
| 1173 | + else | |
| 1174 | + return result.setScale(result.scale() + precisionDiff); | |
| 1175 | + } | |
| 1176 | + } | |
| 1177 | + } | |
| 1178 | + | |
| 1179 | + long padding = (long)lhs.scale - augend.scale; | |
| 1180 | + if (padding != 0) { // scales differ; alignment needed | |
| 1181 | + BigDecimal arg[] = preAlign(lhs, augend, padding, mc); | |
| 1182 | + matchScale(arg); | |
| 1183 | + lhs = arg[0]; | |
| 1184 | + augend = arg[1]; | |
| 1185 | + } | |
| 1186 | + | |
| 1187 | + BigDecimal d = new BigDecimal(lhs.inflate().add(augend.inflate()), | |
| 1188 | + lhs.scale); | |
| 1189 | + return doRound(d, mc); | |
| 1190 | + } | |
| 1191 | + | |
| 1192 | + /** | |
| 1193 | + * Returns an array of length two, the sum of whose entries is | |
| 1194 | + * equal to the rounded sum of the {@code BigDecimal} arguments. | |
| 1195 | + * | |
| 1196 | + * <p>If the digit positions of the arguments have a sufficient | |
| 1197 | + * gap between them, the value smaller in magnitude can be | |
| 1198 | + * condensed into a {@literal "sticky bit"} and the end result will | |
| 1199 | + * round the same way <em>if</em> the precision of the final | |
| 1200 | + * result does not include the high order digit of the small | |
| 1201 | + * magnitude operand. | |
| 1202 | + * | |
| 1203 | + * <p>Note that while strictly speaking this is an optimization, | |
| 1204 | + * it makes a much wider range of additions practical. | |
| 1205 | + * | |
| 1206 | + * <p>This corresponds to a pre-shift operation in a fixed | |
| 1207 | + * precision floating-point adder; this method is complicated by | |
| 1208 | + * variable precision of the result as determined by the | |
| 1209 | + * MathContext. A more nuanced operation could implement a | |
| 1210 | + * {@literal "right shift"} on the smaller magnitude operand so | |
| 1211 | + * that the number of digits of the smaller operand could be | |
| 1212 | + * reduced even though the significands partially overlapped. | |
| 1213 | + */ | |
| 1214 | + private BigDecimal[] preAlign(BigDecimal lhs, BigDecimal augend, | |
| 1215 | + long padding, MathContext mc) { | |
| 1216 | + assert padding != 0; | |
| 1217 | + BigDecimal big; | |
| 1218 | + BigDecimal small; | |
| 1219 | + | |
| 1220 | + if (padding < 0) { // lhs is big; augend is small | |
| 1221 | + big = lhs; | |
| 1222 | + small = augend; | |
| 1223 | + } else { // lhs is small; augend is big | |
| 1224 | + big = augend; | |
| 1225 | + small = lhs; | |
| 1226 | + } | |
| 1227 | + | |
| 1228 | + /* | |
| 1229 | + * This is the estimated scale of an ulp of the result; it | |
| 1230 | + * assumes that the result doesn't have a carry-out on a true | |
| 1231 | + * add (e.g. 999 + 1 => 1000) or any subtractive cancellation | |
| 1232 | + * on borrowing (e.g. 100 - 1.2 => 98.8) | |
| 1233 | + */ | |
| 1234 | + long estResultUlpScale = (long)big.scale - big.precision() + mc.precision; | |
| 1235 | + | |
| 1236 | + /* | |
| 1237 | + * The low-order digit position of big is big.scale(). This | |
| 1238 | + * is true regardless of whether big has a positive or | |
| 1239 | + * negative scale. The high-order digit position of small is | |
| 1240 | + * small.scale - (small.precision() - 1). To do the full | |
| 1241 | + * condensation, the digit positions of big and small must be | |
| 1242 | + * disjoint *and* the digit positions of small should not be | |
| 1243 | + * directly visible in the result. | |
| 1244 | + */ | |
| 1245 | + long smallHighDigitPos = (long)small.scale - small.precision() + 1; | |
| 1246 | + if (smallHighDigitPos > big.scale + 2 && // big and small disjoint | |
| 1247 | + smallHighDigitPos > estResultUlpScale + 2) { // small digits not visible | |
| 1248 | + small = BigDecimal.valueOf(small.signum(), | |
| 1249 | + this.checkScale(Math.max(big.scale, estResultUlpScale) + 3)); | |
| 1250 | + } | |
| 1251 | + | |
| 1252 | + // Since addition is symmetric, preserving input order in | |
| 1253 | + // returned operands doesn't matter | |
| 1254 | + BigDecimal[] result = {big, small}; | |
| 1255 | + return result; | |
| 1256 | + } | |
| 1257 | + | |
| 1258 | + /** | |
| 1259 | + * Returns a {@code BigDecimal} whose value is {@code (this - | |
| 1260 | + * subtrahend)}, and whose scale is {@code max(this.scale(), | |
| 1261 | + * subtrahend.scale())}. | |
| 1262 | + * | |
| 1263 | + * @param subtrahend value to be subtracted from this {@code BigDecimal}. | |
| 1264 | + * @return {@code this - subtrahend} | |
| 1265 | + */ | |
| 1266 | + public BigDecimal subtract(BigDecimal subtrahend) { | |
| 1267 | + return add(subtrahend.negate()); | |
| 1268 | + } | |
| 1269 | + | |
| 1270 | + /** | |
| 1271 | + * Returns a {@code BigDecimal} whose value is {@code (this - subtrahend)}, | |
| 1272 | + * with rounding according to the context settings. | |
| 1273 | + * | |
| 1274 | + * If {@code subtrahend} is zero then this, rounded if necessary, is used as the | |
| 1275 | + * result. If this is zero then the result is {@code subtrahend.negate(mc)}. | |
| 1276 | + * | |
| 1277 | + * @param subtrahend value to be subtracted from this {@code BigDecimal}. | |
| 1278 | + * @param mc the context to use. | |
| 1279 | + * @return {@code this - subtrahend}, rounded as necessary. | |
| 1280 | + * @throws ArithmeticException if the result is inexact but the | |
| 1281 | + * rounding mode is {@code UNNECESSARY}. | |
| 1282 | + * @since 1.5 | |
| 1283 | + */ | |
| 1284 | + public BigDecimal subtract(BigDecimal subtrahend, MathContext mc) { | |
| 1285 | + BigDecimal nsubtrahend = subtrahend.negate(); | |
| 1286 | + if (mc.precision == 0) | |
| 1287 | + return add(nsubtrahend); | |
| 1288 | + // share the special rounding code in add() | |
| 1289 | + return add(nsubtrahend, mc); | |
| 1290 | + } | |
| 1291 | + | |
| 1292 | + /** | |
| 1293 | + * Returns a {@code BigDecimal} whose value is <tt>(this × | |
| 1294 | + * multiplicand)</tt>, and whose scale is {@code (this.scale() + | |
| 1295 | + * multiplicand.scale())}. | |
| 1296 | + * | |
| 1297 | + * @param multiplicand value to be multiplied by this {@code BigDecimal}. | |
| 1298 | + * @return {@code this * multiplicand} | |
| 1299 | + */ | |
| 1300 | + public BigDecimal multiply(BigDecimal multiplicand) { | |
| 1301 | + long x = this.intCompact; | |
| 1302 | + long y = multiplicand.intCompact; | |
| 1303 | + int productScale = checkScale((long)scale + multiplicand.scale); | |
| 1304 | + | |
| 1305 | + // Might be able to do a more clever check incorporating the | |
| 1306 | + // inflated check into the overflow computation. | |
| 1307 | + if (x != INFLATED && y != INFLATED) { | |
| 1308 | + /* | |
| 1309 | + * If the product is not an overflowed value, continue | |
| 1310 | + * to use the compact representation. if either of x or y | |
| 1311 | + * is INFLATED, the product should also be regarded as | |
| 1312 | + * an overflow. Before using the overflow test suggested in | |
| 1313 | + * "Hacker's Delight" section 2-12, we perform quick checks | |
| 1314 | + * using the precision information to see whether the overflow | |
| 1315 | + * would occur since division is expensive on most CPUs. | |
| 1316 | + */ | |
| 1317 | + long product = x * y; | |
| 1318 | + long prec = this.precision() + multiplicand.precision(); | |
| 1319 | + if (prec < 19 || (prec < 21 && (y == 0 || product / y == x))) | |
| 1320 | + return BigDecimal.valueOf(product, productScale); | |
| 1321 | + return new BigDecimal(BigInteger.valueOf(x).multiply(y), INFLATED, | |
| 1322 | + productScale, 0); | |
| 1323 | + } | |
| 1324 | + BigInteger rb; | |
| 1325 | + if (x == INFLATED && y == INFLATED) | |
| 1326 | + rb = this.intVal.multiply(multiplicand.intVal); | |
| 1327 | + else if (x != INFLATED) | |
| 1328 | + rb = multiplicand.intVal.multiply(x); | |
| 1329 | + else | |
| 1330 | + rb = this.intVal.multiply(y); | |
| 1331 | + return new BigDecimal(rb, INFLATED, productScale, 0); | |
| 1332 | + } | |
| 1333 | + | |
| 1334 | + /** | |
| 1335 | + * Returns a {@code BigDecimal} whose value is <tt>(this × | |
| 1336 | + * multiplicand)</tt>, with rounding according to the context settings. | |
| 1337 | + * | |
| 1338 | + * @param multiplicand value to be multiplied by this {@code BigDecimal}. | |
| 1339 | + * @param mc the context to use. | |
| 1340 | + * @return {@code this * multiplicand}, rounded as necessary. | |
| 1341 | + * @throws ArithmeticException if the result is inexact but the | |
| 1342 | + * rounding mode is {@code UNNECESSARY}. | |
| 1343 | + * @since 1.5 | |
| 1344 | + */ | |
| 1345 | + public BigDecimal multiply(BigDecimal multiplicand, MathContext mc) { | |
| 1346 | + if (mc.precision == 0) | |
| 1347 | + return multiply(multiplicand); | |
| 1348 | + return doRound(this.multiply(multiplicand), mc); | |
| 1349 | + } | |
| 1350 | + | |
| 1351 | + /** | |
| 1352 | + * Returns a {@code BigDecimal} whose value is {@code (this / | |
| 1353 | + * divisor)}, and whose scale is as specified. If rounding must | |
| 1354 | + * be performed to generate a result with the specified scale, the | |
| 1355 | + * specified rounding mode is applied. | |
| 1356 | + * | |
| 1357 | + * <p>The new {@link #divide(BigDecimal, int, RoundingMode)} method | |
| 1358 | + * should be used in preference to this legacy method. | |
| 1359 | + * | |
| 1360 | + * @param divisor value by which this {@code BigDecimal} is to be divided. | |
| 1361 | + * @param scale scale of the {@code BigDecimal} quotient to be returned. | |
| 1362 | + * @param roundingMode rounding mode to apply. | |
| 1363 | + * @return {@code this / divisor} | |
| 1364 | + * @throws ArithmeticException if {@code divisor} is zero, | |
| 1365 | + * {@code roundingMode==ROUND_UNNECESSARY} and | |
| 1366 | + * the specified scale is insufficient to represent the result | |
| 1367 | + * of the division exactly. | |
| 1368 | + * @throws IllegalArgumentException if {@code roundingMode} does not | |
| 1369 | + * represent a valid rounding mode. | |
| 1370 | + * @see #ROUND_UP | |
| 1371 | + * @see #ROUND_DOWN | |
| 1372 | + * @see #ROUND_CEILING | |
| 1373 | + * @see #ROUND_FLOOR | |
| 1374 | + * @see #ROUND_HALF_UP | |
| 1375 | + * @see #ROUND_HALF_DOWN | |
| 1376 | + * @see #ROUND_HALF_EVEN | |
| 1377 | + * @see #ROUND_UNNECESSARY | |
| 1378 | + */ | |
| 1379 | + public BigDecimal divide(BigDecimal divisor, int scale, int roundingMode) { | |
| 1380 | + /* | |
| 1381 | + * IMPLEMENTATION NOTE: This method *must* return a new object | |
| 1382 | + * since divideAndRound uses divide to generate a value whose | |
| 1383 | + * scale is then modified. | |
| 1384 | + */ | |
| 1385 | + if (roundingMode < ROUND_UP || roundingMode > ROUND_UNNECESSARY) | |
| 1386 | + throw new IllegalArgumentException("Invalid rounding mode"); | |
| 1387 | + /* | |
| 1388 | + * Rescale dividend or divisor (whichever can be "upscaled" to | |
| 1389 | + * produce correctly scaled quotient). | |
| 1390 | + * Take care to detect out-of-range scales | |
| 1391 | + */ | |
| 1392 | + BigDecimal dividend = this; | |
| 1393 | + if (checkScale((long)scale + divisor.scale) > this.scale) | |
| 1394 | + dividend = this.setScale(scale + divisor.scale, ROUND_UNNECESSARY); | |
| 1395 | + else | |
| 1396 | + divisor = divisor.setScale(checkScale((long)this.scale - scale), | |
| 1397 | + ROUND_UNNECESSARY); | |
| 1398 | + return divideAndRound(dividend.intCompact, dividend.intVal, | |
| 1399 | + divisor.intCompact, divisor.intVal, | |
| 1400 | + scale, roundingMode, scale); | |
| 1401 | + } | |
| 1402 | + | |
| 1403 | + /** | |
| 1404 | + * Internally used for division operation. The dividend and divisor are | |
| 1405 | + * passed both in {@code long} format and {@code BigInteger} format. The | |
| 1406 | + * returned {@code BigDecimal} object is the quotient whose scale is set to | |
| 1407 | + * the passed in scale. If the remainder is not zero, it will be rounded | |
| 1408 | + * based on the passed in roundingMode. Also, if the remainder is zero and | |
| 1409 | + * the last parameter, i.e. preferredScale is NOT equal to scale, the | |
| 1410 | + * trailing zeros of the result is stripped to match the preferredScale. | |
| 1411 | + */ | |
| 1412 | + private static BigDecimal divideAndRound(long ldividend, BigInteger bdividend, | |
| 1413 | + long ldivisor, BigInteger bdivisor, | |
| 1414 | + int scale, int roundingMode, | |
| 1415 | + int preferredScale) { | |
| 1416 | + boolean isRemainderZero; // record remainder is zero or not | |
| 1417 | + int qsign; // quotient sign | |
| 1418 | + long q = 0, r = 0; // store quotient & remainder in long | |
| 1419 | + MutableBigInteger mq = null; // store quotient | |
| 1420 | + MutableBigInteger mr = null; // store remainder | |
| 1421 | + MutableBigInteger mdivisor = null; | |
| 1422 | + boolean isLongDivision = (ldividend != INFLATED && ldivisor != INFLATED); | |
| 1423 | + if (isLongDivision) { | |
| 1424 | + q = ldividend / ldivisor; | |
| 1425 | + if (roundingMode == ROUND_DOWN && scale == preferredScale) | |
| 1426 | + return new BigDecimal(null, q, scale, 0); | |
| 1427 | + r = ldividend % ldivisor; | |
| 1428 | + isRemainderZero = (r == 0); | |
| 1429 | + qsign = ((ldividend < 0) == (ldivisor < 0)) ? 1 : -1; | |
| 1430 | + } else { | |
| 1431 | + if (bdividend == null) | |
| 1432 | + bdividend = BigInteger.valueOf(ldividend); | |
| 1433 | + // Descend into mutables for faster remainder checks | |
| 1434 | + MutableBigInteger mdividend = new MutableBigInteger(bdividend.mag); | |
| 1435 | + mq = new MutableBigInteger(); | |
| 1436 | + if (ldivisor != INFLATED) { | |
| 1437 | + r = mdividend.divide(ldivisor, mq); | |
| 1438 | + isRemainderZero = (r == 0); | |
| 1439 | + qsign = (ldivisor < 0) ? -bdividend.signum : bdividend.signum; | |
| 1440 | + } else { | |
| 1441 | + mdivisor = new MutableBigInteger(bdivisor.mag); | |
| 1442 | + mr = mdividend.divide(mdivisor, mq); | |
| 1443 | + isRemainderZero = mr.isZero(); | |
| 1444 | + qsign = (bdividend.signum != bdivisor.signum) ? -1 : 1; | |
| 1445 | + } | |
| 1446 | + } | |
| 1447 | + boolean increment = false; | |
| 1448 | + if (!isRemainderZero) { | |
| 1449 | + int cmpFracHalf; | |
| 1450 | + /* Round as appropriate */ | |
| 1451 | + if (roundingMode == ROUND_UNNECESSARY) { // Rounding prohibited | |
| 1452 | + throw new ArithmeticException("Rounding necessary"); | |
| 1453 | + } else if (roundingMode == ROUND_UP) { // Away from zero | |
| 1454 | + increment = true; | |
| 1455 | + } else if (roundingMode == ROUND_DOWN) { // Towards zero | |
| 1456 | + increment = false; | |
| 1457 | + } else if (roundingMode == ROUND_CEILING) { // Towards +infinity | |
| 1458 | + increment = (qsign > 0); | |
| 1459 | + } else if (roundingMode == ROUND_FLOOR) { // Towards -infinity | |
| 1460 | + increment = (qsign < 0); | |
| 1461 | + } else { | |
| 1462 | + if (isLongDivision || ldivisor != INFLATED) { | |
| 1463 | + if (r <= HALF_LONG_MIN_VALUE || r > HALF_LONG_MAX_VALUE) { | |
| 1464 | + cmpFracHalf = 1; // 2 * r can't fit into long | |
| 1465 | + } else { | |
| 1466 | + cmpFracHalf = longCompareMagnitude(2 * r, ldivisor); | |
| 1467 | + } | |
| 1468 | + } else { | |
| 1469 | + cmpFracHalf = mr.compareHalf(mdivisor); | |
| 1470 | + } | |
| 1471 | + if (cmpFracHalf < 0) | |
| 1472 | + increment = false; // We're closer to higher digit | |
| 1473 | + else if (cmpFracHalf > 0) // We're closer to lower digit | |
| 1474 | + increment = true; | |
| 1475 | + else if (roundingMode == ROUND_HALF_UP) | |
| 1476 | + increment = true; | |
| 1477 | + else if (roundingMode == ROUND_HALF_DOWN) | |
| 1478 | + increment = false; | |
| 1479 | + else // roundingMode == ROUND_HALF_EVEN, true iff quotient is odd | |
| 1480 | + increment = isLongDivision ? (q & 1L) != 0L : mq.isOdd(); | |
| 1481 | + } | |
| 1482 | + } | |
| 1483 | + BigDecimal res; | |
| 1484 | + if (isLongDivision) | |
| 1485 | + res = new BigDecimal(null, (increment ? q + qsign : q), scale, 0); | |
| 1486 | + else { | |
| 1487 | + if (increment) | |
| 1488 | + mq.add(MutableBigInteger.ONE); | |
| 1489 | + res = mq.toBigDecimal(qsign, scale); | |
| 1490 | + } | |
| 1491 | + if (isRemainderZero && preferredScale != scale) | |
| 1492 | + res.stripZerosToMatchScale(preferredScale); | |
| 1493 | + return res; | |
| 1494 | + } | |
| 1495 | + | |
| 1496 | + /** | |
| 1497 | + * Returns a {@code BigDecimal} whose value is {@code (this / | |
| 1498 | + * divisor)}, and whose scale is as specified. If rounding must | |
| 1499 | + * be performed to generate a result with the specified scale, the | |
| 1500 | + * specified rounding mode is applied. | |
| 1501 | + * | |
| 1502 | + * @param divisor value by which this {@code BigDecimal} is to be divided. | |
| 1503 | + * @param scale scale of the {@code BigDecimal} quotient to be returned. | |
| 1504 | + * @param roundingMode rounding mode to apply. | |
| 1505 | + * @return {@code this / divisor} | |
| 1506 | + * @throws ArithmeticException if {@code divisor} is zero, | |
| 1507 | + * {@code roundingMode==RoundingMode.UNNECESSARY} and | |
| 1508 | + * the specified scale is insufficient to represent the result | |
| 1509 | + * of the division exactly. | |
| 1510 | + * @since 1.5 | |
| 1511 | + */ | |
| 1512 | + public BigDecimal divide(BigDecimal divisor, int scale, RoundingMode roundingMode) { | |
| 1513 | + return divide(divisor, scale, roundingMode.oldMode); | |
| 1514 | + } | |
| 1515 | + | |
| 1516 | + /** | |
| 1517 | + * Returns a {@code BigDecimal} whose value is {@code (this / | |
| 1518 | + * divisor)}, and whose scale is {@code this.scale()}. If | |
| 1519 | + * rounding must be performed to generate a result with the given | |
| 1520 | + * scale, the specified rounding mode is applied. | |
| 1521 | + * | |
| 1522 | + * <p>The new {@link #divide(BigDecimal, RoundingMode)} method | |
| 1523 | + * should be used in preference to this legacy method. | |
| 1524 | + * | |
| 1525 | + * @param divisor value by which this {@code BigDecimal} is to be divided. | |
| 1526 | + * @param roundingMode rounding mode to apply. | |
| 1527 | + * @return {@code this / divisor} | |
| 1528 | + * @throws ArithmeticException if {@code divisor==0}, or | |
| 1529 | + * {@code roundingMode==ROUND_UNNECESSARY} and | |
| 1530 | + * {@code this.scale()} is insufficient to represent the result | |
| 1531 | + * of the division exactly. | |
| 1532 | + * @throws IllegalArgumentException if {@code roundingMode} does not | |
| 1533 | + * represent a valid rounding mode. | |
| 1534 | + * @see #ROUND_UP | |
| 1535 | + * @see #ROUND_DOWN | |
| 1536 | + * @see #ROUND_CEILING | |
| 1537 | + * @see #ROUND_FLOOR | |
| 1538 | + * @see #ROUND_HALF_UP | |
| 1539 | + * @see #ROUND_HALF_DOWN | |
| 1540 | + * @see #ROUND_HALF_EVEN | |
| 1541 | + * @see #ROUND_UNNECESSARY | |
| 1542 | + */ | |
| 1543 | + public BigDecimal divide(BigDecimal divisor, int roundingMode) { | |
| 1544 | + return this.divide(divisor, scale, roundingMode); | |
| 1545 | + } | |
| 1546 | + | |
| 1547 | + /** | |
| 1548 | + * Returns a {@code BigDecimal} whose value is {@code (this / | |
| 1549 | + * divisor)}, and whose scale is {@code this.scale()}. If | |
| 1550 | + * rounding must be performed to generate a result with the given | |
| 1551 | + * scale, the specified rounding mode is applied. | |
| 1552 | + * | |
| 1553 | + * @param divisor value by which this {@code BigDecimal} is to be divided. | |
| 1554 | + * @param roundingMode rounding mode to apply. | |
| 1555 | + * @return {@code this / divisor} | |
| 1556 | + * @throws ArithmeticException if {@code divisor==0}, or | |
| 1557 | + * {@code roundingMode==RoundingMode.UNNECESSARY} and | |
| 1558 | + * {@code this.scale()} is insufficient to represent the result | |
| 1559 | + * of the division exactly. | |
| 1560 | + * @since 1.5 | |
| 1561 | + */ | |
| 1562 | + public BigDecimal divide(BigDecimal divisor, RoundingMode roundingMode) { | |
| 1563 | + return this.divide(divisor, scale, roundingMode.oldMode); | |
| 1564 | + } | |
| 1565 | + | |
| 1566 | + /** | |
| 1567 | + * Returns a {@code BigDecimal} whose value is {@code (this / | |
| 1568 | + * divisor)}, and whose preferred scale is {@code (this.scale() - | |
| 1569 | + * divisor.scale())}; if the exact quotient cannot be | |
| 1570 | + * represented (because it has a non-terminating decimal | |
| 1571 | + * expansion) an {@code ArithmeticException} is thrown. | |
| 1572 | + * | |
| 1573 | + * @param divisor value by which this {@code BigDecimal} is to be divided. | |
| 1574 | + * @throws ArithmeticException if the exact quotient does not have a | |
| 1575 | + * terminating decimal expansion | |
| 1576 | + * @return {@code this / divisor} | |
| 1577 | + * @since 1.5 | |
| 1578 | + * @author Joseph D. Darcy | |
| 1579 | + */ | |
| 1580 | + public BigDecimal divide(BigDecimal divisor) { | |
| 1581 | + /* | |
| 1582 | + * Handle zero cases first. | |
| 1583 | + */ | |
| 1584 | + if (divisor.signum() == 0) { // x/0 | |
| 1585 | + if (this.signum() == 0) // 0/0 | |
| 1586 | + throw new ArithmeticException("Division undefined"); // NaN | |
| 1587 | + throw new ArithmeticException("Division by zero"); | |
| 1588 | + } | |
| 1589 | + | |
| 1590 | + // Calculate preferred scale | |
| 1591 | + int preferredScale = saturateLong((long)this.scale - divisor.scale); | |
| 1592 | + if (this.signum() == 0) // 0/y | |
| 1593 | + return (preferredScale >= 0 && | |
| 1594 | + preferredScale < ZERO_SCALED_BY.length) ? | |
| 1595 | + ZERO_SCALED_BY[preferredScale] : | |
| 1596 | + BigDecimal.valueOf(0, preferredScale); | |
| 1597 | + else { | |
| 1598 | + this.inflate(); | |
| 1599 | + divisor.inflate(); | |
| 1600 | + /* | |
| 1601 | + * If the quotient this/divisor has a terminating decimal | |
| 1602 | + * expansion, the expansion can have no more than | |
| 1603 | + * (a.precision() + ceil(10*b.precision)/3) digits. | |
| 1604 | + * Therefore, create a MathContext object with this | |
| 1605 | + * precision and do a divide with the UNNECESSARY rounding | |
| 1606 | + * mode. | |
| 1607 | + */ | |
| 1608 | + MathContext mc = new MathContext( (int)Math.min(this.precision() + | |
| 1609 | + (long)Math.ceil(10.0*divisor.precision()/3.0), | |
| 1610 | + Integer.MAX_VALUE), | |
| 1611 | + RoundingMode.UNNECESSARY); | |
| 1612 | + BigDecimal quotient; | |
| 1613 | + try { | |
| 1614 | + quotient = this.divide(divisor, mc); | |
| 1615 | + } catch (ArithmeticException e) { | |
| 1616 | + throw new ArithmeticException("Non-terminating decimal expansion; " + | |
| 1617 | + "no exact representable decimal result."); | |
| 1618 | + } | |
| 1619 | + | |
| 1620 | + int quotientScale = quotient.scale(); | |
| 1621 | + | |
| 1622 | + // divide(BigDecimal, mc) tries to adjust the quotient to | |
| 1623 | + // the desired one by removing trailing zeros; since the | |
| 1624 | + // exact divide method does not have an explicit digit | |
| 1625 | + // limit, we can add zeros too. | |
| 1626 | + | |
| 1627 | + if (preferredScale > quotientScale) | |
| 1628 | + return quotient.setScale(preferredScale, ROUND_UNNECESSARY); | |
| 1629 | + | |
| 1630 | + return quotient; | |
| 1631 | + } | |
| 1632 | + } | |
| 1633 | + | |
| 1634 | + /** | |
| 1635 | + * Returns a {@code BigDecimal} whose value is {@code (this / | |
| 1636 | + * divisor)}, with rounding according to the context settings. | |
| 1637 | + * | |
| 1638 | + * @param divisor value by which this {@code BigDecimal} is to be divided. | |
| 1639 | + * @param mc the context to use. | |
| 1640 | + * @return {@code this / divisor}, rounded as necessary. | |
| 1641 | + * @throws ArithmeticException if the result is inexact but the | |
| 1642 | + * rounding mode is {@code UNNECESSARY} or | |
| 1643 | + * {@code mc.precision == 0} and the quotient has a | |
| 1644 | + * non-terminating decimal expansion. | |
| 1645 | + * @since 1.5 | |
| 1646 | + */ | |
| 1647 | + public BigDecimal divide(BigDecimal divisor, MathContext mc) { | |
| 1648 | + int mcp = mc.precision; | |
| 1649 | + if (mcp == 0) | |
| 1650 | + return divide(divisor); | |
| 1651 | + | |
| 1652 | + BigDecimal dividend = this; | |
| 1653 | + long preferredScale = (long)dividend.scale - divisor.scale; | |
| 1654 | + // Now calculate the answer. We use the existing | |
| 1655 | + // divide-and-round method, but as this rounds to scale we have | |
| 1656 | + // to normalize the values here to achieve the desired result. | |
| 1657 | + // For x/y we first handle y=0 and x=0, and then normalize x and | |
| 1658 | + // y to give x' and y' with the following constraints: | |
| 1659 | + // (a) 0.1 <= x' < 1 | |
| 1660 | + // (b) x' <= y' < 10*x' | |
| 1661 | + // Dividing x'/y' with the required scale set to mc.precision then | |
| 1662 | + // will give a result in the range 0.1 to 1 rounded to exactly | |
| 1663 | + // the right number of digits (except in the case of a result of | |
| 1664 | + // 1.000... which can arise when x=y, or when rounding overflows | |
| 1665 | + // The 1.000... case will reduce properly to 1. | |
| 1666 | + if (divisor.signum() == 0) { // x/0 | |
| 1667 | + if (dividend.signum() == 0) // 0/0 | |
| 1668 | + throw new ArithmeticException("Division undefined"); // NaN | |
| 1669 | + throw new ArithmeticException("Division by zero"); | |
| 1670 | + } | |
| 1671 | + if (dividend.signum() == 0) // 0/y | |
| 1672 | + return new BigDecimal(BigInteger.ZERO, 0, | |
| 1673 | + saturateLong(preferredScale), 1); | |
| 1674 | + | |
| 1675 | + // Normalize dividend & divisor so that both fall into [0.1, 0.999...] | |
| 1676 | + int xscale = dividend.precision(); | |
| 1677 | + int yscale = divisor.precision(); | |
| 1678 | + dividend = new BigDecimal(dividend.intVal, dividend.intCompact, | |
| 1679 | + xscale, xscale); | |
| 1680 | + divisor = new BigDecimal(divisor.intVal, divisor.intCompact, | |
| 1681 | + yscale, yscale); | |
| 1682 | + if (dividend.compareMagnitude(divisor) > 0) // satisfy constraint (b) | |
| 1683 | + yscale = divisor.scale -= 1; // [that is, divisor *= 10] | |
| 1684 | + | |
| 1685 | + // In order to find out whether the divide generates the exact result, | |
| 1686 | + // we avoid calling the above divide method. 'quotient' holds the | |
| 1687 | + // return BigDecimal object whose scale will be set to 'scl'. | |
| 1688 | + BigDecimal quotient; | |
| 1689 | + int scl = checkScale(preferredScale + yscale - xscale + mcp); | |
| 1690 | + if (checkScale((long)mcp + yscale) > xscale) | |
| 1691 | + dividend = dividend.setScale(mcp + yscale, ROUND_UNNECESSARY); | |
| 1692 | + else | |
| 1693 | + divisor = divisor.setScale(checkScale((long)xscale - mcp), | |
| 1694 | + ROUND_UNNECESSARY); | |
| 1695 | + quotient = divideAndRound(dividend.intCompact, dividend.intVal, | |
| 1696 | + divisor.intCompact, divisor.intVal, | |
| 1697 | + scl, mc.roundingMode.oldMode, | |
| 1698 | + checkScale(preferredScale)); | |
| 1699 | + // doRound, here, only affects 1000000000 case. | |
| 1700 | + quotient = doRound(quotient, mc); | |
| 1701 | + | |
| 1702 | + return quotient; | |
| 1703 | + } | |
| 1704 | + | |
| 1705 | + /** | |
| 1706 | + * Returns a {@code BigDecimal} whose value is the integer part | |
| 1707 | + * of the quotient {@code (this / divisor)} rounded down. The | |
| 1708 | + * preferred scale of the result is {@code (this.scale() - | |
| 1709 | + * divisor.scale())}. | |
| 1710 | + * | |
| 1711 | + * @param divisor value by which this {@code BigDecimal} is to be divided. | |
| 1712 | + * @return The integer part of {@code this / divisor}. | |
| 1713 | + * @throws ArithmeticException if {@code divisor==0} | |
| 1714 | + * @since 1.5 | |
| 1715 | + */ | |
| 1716 | + public BigDecimal divideToIntegralValue(BigDecimal divisor) { | |
| 1717 | + // Calculate preferred scale | |
| 1718 | + int preferredScale = saturateLong((long)this.scale - divisor.scale); | |
| 1719 | + if (this.compareMagnitude(divisor) < 0) { | |
| 1720 | + // much faster when this << divisor | |
| 1721 | + return BigDecimal.valueOf(0, preferredScale); | |
| 1722 | + } | |
| 1723 | + | |
| 1724 | + if(this.signum() == 0 && divisor.signum() != 0) | |
| 1725 | + return this.setScale(preferredScale, ROUND_UNNECESSARY); | |
| 1726 | + | |
| 1727 | + // Perform a divide with enough digits to round to a correct | |
| 1728 | + // integer value; then remove any fractional digits | |
| 1729 | + | |
| 1730 | + int maxDigits = (int)Math.min(this.precision() + | |
| 1731 | + (long)Math.ceil(10.0*divisor.precision()/3.0) + | |
| 1732 | + Math.abs((long)this.scale() - divisor.scale()) + 2, | |
| 1733 | + Integer.MAX_VALUE); | |
| 1734 | + BigDecimal quotient = this.divide(divisor, new MathContext(maxDigits, | |
| 1735 | + RoundingMode.DOWN)); | |
| 1736 | + if (quotient.scale > 0) { | |
| 1737 | + quotient = quotient.setScale(0, RoundingMode.DOWN); | |
| 1738 | + quotient.stripZerosToMatchScale(preferredScale); | |
| 1739 | + } | |
| 1740 | + | |
| 1741 | + if (quotient.scale < preferredScale) { | |
| 1742 | + // pad with zeros if necessary | |
| 1743 | + quotient = quotient.setScale(preferredScale, ROUND_UNNECESSARY); | |
| 1744 | + } | |
| 1745 | + return quotient; | |
| 1746 | + } | |
| 1747 | + | |
| 1748 | + /** | |
| 1749 | + * Returns a {@code BigDecimal} whose value is the integer part | |
| 1750 | + * of {@code (this / divisor)}. Since the integer part of the | |
| 1751 | + * exact quotient does not depend on the rounding mode, the | |
| 1752 | + * rounding mode does not affect the values returned by this | |
| 1753 | + * method. The preferred scale of the result is | |
| 1754 | + * {@code (this.scale() - divisor.scale())}. An | |
| 1755 | + * {@code ArithmeticException} is thrown if the integer part of | |
| 1756 | + * the exact quotient needs more than {@code mc.precision} | |
| 1757 | + * digits. | |
| 1758 | + * | |
| 1759 | + * @param divisor value by which this {@code BigDecimal} is to be divided. | |
| 1760 | + * @param mc the context to use. | |
| 1761 | + * @return The integer part of {@code this / divisor}. | |
| 1762 | + * @throws ArithmeticException if {@code divisor==0} | |
| 1763 | + * @throws ArithmeticException if {@code mc.precision} {@literal >} 0 and the result | |
| 1764 | + * requires a precision of more than {@code mc.precision} digits. | |
| 1765 | + * @since 1.5 | |
| 1766 | + * @author Joseph D. Darcy | |
| 1767 | + */ | |
| 1768 | + public BigDecimal divideToIntegralValue(BigDecimal divisor, MathContext mc) { | |
| 1769 | + if (mc.precision == 0 || // exact result | |
| 1770 | + (this.compareMagnitude(divisor) < 0) ) // zero result | |
| 1771 | + return divideToIntegralValue(divisor); | |
| 1772 | + | |
| 1773 | + // Calculate preferred scale | |
| 1774 | + int preferredScale = saturateLong((long)this.scale - divisor.scale); | |
| 1775 | + | |
| 1776 | + /* | |
| 1777 | + * Perform a normal divide to mc.precision digits. If the | |
| 1778 | + * remainder has absolute value less than the divisor, the | |
| 1779 | + * integer portion of the quotient fits into mc.precision | |
| 1780 | + * digits. Next, remove any fractional digits from the | |
| 1781 | + * quotient and adjust the scale to the preferred value. | |
| 1782 | + */ | |
| 1783 | + BigDecimal result = this. | |
| 1784 | + divide(divisor, new MathContext(mc.precision, RoundingMode.DOWN)); | |
| 1785 | + | |
| 1786 | + if (result.scale() < 0) { | |
| 1787 | + /* | |
| 1788 | + * Result is an integer. See if quotient represents the | |
| 1789 | + * full integer portion of the exact quotient; if it does, | |
| 1790 | + * the computed remainder will be less than the divisor. | |
| 1791 | + */ | |
| 1792 | + BigDecimal product = result.multiply(divisor); | |
| 1793 | + // If the quotient is the full integer value, | |
| 1794 | + // |dividend-product| < |divisor|. | |
| 1795 | + if (this.subtract(product).compareMagnitude(divisor) >= 0) { | |
| 1796 | + throw new ArithmeticException("Division impossible"); | |
| 1797 | + } | |
| 1798 | + } else if (result.scale() > 0) { | |
| 1799 | + /* | |
| 1800 | + * Integer portion of quotient will fit into precision | |
| 1801 | + * digits; recompute quotient to scale 0 to avoid double | |
| 1802 | + * rounding and then try to adjust, if necessary. | |
| 1803 | + */ | |
| 1804 | + result = result.setScale(0, RoundingMode.DOWN); | |
| 1805 | + } | |
| 1806 | + // else result.scale() == 0; | |
| 1807 | + | |
| 1808 | + int precisionDiff; | |
| 1809 | + if ((preferredScale > result.scale()) && | |
| 1810 | + (precisionDiff = mc.precision - result.precision()) > 0) { | |
| 1811 | + return result.setScale(result.scale() + | |
| 1812 | + Math.min(precisionDiff, preferredScale - result.scale) ); | |
| 1813 | + } else { | |
| 1814 | + result.stripZerosToMatchScale(preferredScale); | |
| 1815 | + return result; | |
| 1816 | + } | |
| 1817 | + } | |
| 1818 | + | |
| 1819 | + /** | |
| 1820 | + * Returns a {@code BigDecimal} whose value is {@code (this % divisor)}. | |
| 1821 | + * | |
| 1822 | + * <p>The remainder is given by | |
| 1823 | + * {@code this.subtract(this.divideToIntegralValue(divisor).multiply(divisor))}. | |
| 1824 | + * Note that this is not the modulo operation (the result can be | |
| 1825 | + * negative). | |
| 1826 | + * | |
| 1827 | + * @param divisor value by which this {@code BigDecimal} is to be divided. | |
| 1828 | + * @return {@code this % divisor}. | |
| 1829 | + * @throws ArithmeticException if {@code divisor==0} | |
| 1830 | + * @since 1.5 | |
| 1831 | + */ | |
| 1832 | + public BigDecimal remainder(BigDecimal divisor) { | |
| 1833 | + BigDecimal divrem[] = this.divideAndRemainder(divisor); | |
| 1834 | + return divrem[1]; | |
| 1835 | + } | |
| 1836 | + | |
| 1837 | + | |
| 1838 | + /** | |
| 1839 | + * Returns a {@code BigDecimal} whose value is {@code (this % | |
| 1840 | + * divisor)}, with rounding according to the context settings. | |
| 1841 | + * The {@code MathContext} settings affect the implicit divide | |
| 1842 | + * used to compute the remainder. The remainder computation | |
| 1843 | + * itself is by definition exact. Therefore, the remainder may | |
| 1844 | + * contain more than {@code mc.getPrecision()} digits. | |
| 1845 | + * | |
| 1846 | + * <p>The remainder is given by | |
| 1847 | + * {@code this.subtract(this.divideToIntegralValue(divisor, | |
| 1848 | + * mc).multiply(divisor))}. Note that this is not the modulo | |
| 1849 | + * operation (the result can be negative). | |
| 1850 | + * | |
| 1851 | + * @param divisor value by which this {@code BigDecimal} is to be divided. | |
| 1852 | + * @param mc the context to use. | |
| 1853 | + * @return {@code this % divisor}, rounded as necessary. | |
| 1854 | + * @throws ArithmeticException if {@code divisor==0} | |
| 1855 | + * @throws ArithmeticException if the result is inexact but the | |
| 1856 | + * rounding mode is {@code UNNECESSARY}, or {@code mc.precision} | |
| 1857 | + * {@literal >} 0 and the result of {@code this.divideToIntgralValue(divisor)} would | |
| 1858 | + * require a precision of more than {@code mc.precision} digits. | |
| 1859 | + * @see #divideToIntegralValue(java.math.BigDecimal, java.math.MathContext) | |
| 1860 | + * @since 1.5 | |
| 1861 | + */ | |
| 1862 | + public BigDecimal remainder(BigDecimal divisor, MathContext mc) { | |
| 1863 | + BigDecimal divrem[] = this.divideAndRemainder(divisor, mc); | |
| 1864 | + return divrem[1]; | |
| 1865 | + } | |
| 1866 | + | |
| 1867 | + /** | |
| 1868 | + * Returns a two-element {@code BigDecimal} array containing the | |
| 1869 | + * result of {@code divideToIntegralValue} followed by the result of | |
| 1870 | + * {@code remainder} on the two operands. | |
| 1871 | + * | |
| 1872 | + * <p>Note that if both the integer quotient and remainder are | |
| 1873 | + * needed, this method is faster than using the | |
| 1874 | + * {@code divideToIntegralValue} and {@code remainder} methods | |
| 1875 | + * separately because the division need only be carried out once. | |
| 1876 | + * | |
| 1877 | + * @param divisor value by which this {@code BigDecimal} is to be divided, | |
| 1878 | + * and the remainder computed. | |
| 1879 | + * @return a two element {@code BigDecimal} array: the quotient | |
| 1880 | + * (the result of {@code divideToIntegralValue}) is the initial element | |
| 1881 | + * and the remainder is the final element. | |
| 1882 | + * @throws ArithmeticException if {@code divisor==0} | |
| 1883 | + * @see #divideToIntegralValue(java.math.BigDecimal, java.math.MathContext) | |
| 1884 | + * @see #remainder(java.math.BigDecimal, java.math.MathContext) | |
| 1885 | + * @since 1.5 | |
| 1886 | + */ | |
| 1887 | + public BigDecimal[] divideAndRemainder(BigDecimal divisor) { | |
| 1888 | + // we use the identity x = i * y + r to determine r | |
| 1889 | + BigDecimal[] result = new BigDecimal[2]; | |
| 1890 | + | |
| 1891 | + result[0] = this.divideToIntegralValue(divisor); | |
| 1892 | + result[1] = this.subtract(result[0].multiply(divisor)); | |
| 1893 | + return result; | |
| 1894 | + } | |
| 1895 | + | |
| 1896 | + /** | |
| 1897 | + * Returns a two-element {@code BigDecimal} array containing the | |
| 1898 | + * result of {@code divideToIntegralValue} followed by the result of | |
| 1899 | + * {@code remainder} on the two operands calculated with rounding | |
| 1900 | + * according to the context settings. | |
| 1901 | + * | |
| 1902 | + * <p>Note that if both the integer quotient and remainder are | |
| 1903 | + * needed, this method is faster than using the | |
| 1904 | + * {@code divideToIntegralValue} and {@code remainder} methods | |
| 1905 | + * separately because the division need only be carried out once. | |
| 1906 | + * | |
| 1907 | + * @param divisor value by which this {@code BigDecimal} is to be divided, | |
| 1908 | + * and the remainder computed. | |
| 1909 | + * @param mc the context to use. | |
| 1910 | + * @return a two element {@code BigDecimal} array: the quotient | |
| 1911 | + * (the result of {@code divideToIntegralValue}) is the | |
| 1912 | + * initial element and the remainder is the final element. | |
| 1913 | + * @throws ArithmeticException if {@code divisor==0} | |
| 1914 | + * @throws ArithmeticException if the result is inexact but the | |
| 1915 | + * rounding mode is {@code UNNECESSARY}, or {@code mc.precision} | |
| 1916 | + * {@literal >} 0 and the result of {@code this.divideToIntgralValue(divisor)} would | |
| 1917 | + * require a precision of more than {@code mc.precision} digits. | |
| 1918 | + * @see #divideToIntegralValue(java.math.BigDecimal, java.math.MathContext) | |
| 1919 | + * @see #remainder(java.math.BigDecimal, java.math.MathContext) | |
| 1920 | + * @since 1.5 | |
| 1921 | + */ | |
| 1922 | + public BigDecimal[] divideAndRemainder(BigDecimal divisor, MathContext mc) { | |
| 1923 | + if (mc.precision == 0) | |
| 1924 | + return divideAndRemainder(divisor); | |
| 1925 | + | |
| 1926 | + BigDecimal[] result = new BigDecimal[2]; | |
| 1927 | + BigDecimal lhs = this; | |
| 1928 | + | |
| 1929 | + result[0] = lhs.divideToIntegralValue(divisor, mc); | |
| 1930 | + result[1] = lhs.subtract(result[0].multiply(divisor)); | |
| 1931 | + return result; | |
| 1932 | + } | |
| 1933 | + | |
| 1934 | + /** | |
| 1935 | + * Returns a {@code BigDecimal} whose value is | |
| 1936 | + * <tt>(this<sup>n</sup>)</tt>, The power is computed exactly, to | |
| 1937 | + * unlimited precision. | |
| 1938 | + * | |
| 1939 | + * <p>The parameter {@code n} must be in the range 0 through | |
| 1940 | + * 999999999, inclusive. {@code ZERO.pow(0)} returns {@link | |
| 1941 | + * #ONE}. | |
| 1942 | + * | |
| 1943 | + * Note that future releases may expand the allowable exponent | |
| 1944 | + * range of this method. | |
| 1945 | + * | |
| 1946 | + * @param n power to raise this {@code BigDecimal} to. | |
| 1947 | + * @return <tt>this<sup>n</sup></tt> | |
| 1948 | + * @throws ArithmeticException if {@code n} is out of range. | |
| 1949 | + * @since 1.5 | |
| 1950 | + */ | |
| 1951 | + public BigDecimal pow(int n) { | |
| 1952 | + if (n < 0 || n > 999999999) | |
| 1953 | + throw new ArithmeticException("Invalid operation"); | |
| 1954 | + // No need to calculate pow(n) if result will over/underflow. | |
| 1955 | + // Don't attempt to support "supernormal" numbers. | |
| 1956 | + int newScale = checkScale((long)scale * n); | |
| 1957 | + this.inflate(); | |
| 1958 | + return new BigDecimal(intVal.pow(n), newScale); | |
| 1959 | + } | |
| 1960 | + | |
| 1961 | + | |
| 1962 | + /** | |
| 1963 | + * Returns a {@code BigDecimal} whose value is | |
| 1964 | + * <tt>(this<sup>n</sup>)</tt>. The current implementation uses | |
| 1965 | + * the core algorithm defined in ANSI standard X3.274-1996 with | |
| 1966 | + * rounding according to the context settings. In general, the | |
| 1967 | + * returned numerical value is within two ulps of the exact | |
| 1968 | + * numerical value for the chosen precision. Note that future | |
| 1969 | + * releases may use a different algorithm with a decreased | |
| 1970 | + * allowable error bound and increased allowable exponent range. | |
| 1971 | + * | |
| 1972 | + * <p>The X3.274-1996 algorithm is: | |
| 1973 | + * | |
| 1974 | + * <ul> | |
| 1975 | + * <li> An {@code ArithmeticException} exception is thrown if | |
| 1976 | + * <ul> | |
| 1977 | + * <li>{@code abs(n) > 999999999} | |
| 1978 | + * <li>{@code mc.precision == 0} and {@code n < 0} | |
| 1979 | + * <li>{@code mc.precision > 0} and {@code n} has more than | |
| 1980 | + * {@code mc.precision} decimal digits | |
| 1981 | + * </ul> | |
| 1982 | + * | |
| 1983 | + * <li> if {@code n} is zero, {@link #ONE} is returned even if | |
| 1984 | + * {@code this} is zero, otherwise | |
| 1985 | + * <ul> | |
| 1986 | + * <li> if {@code n} is positive, the result is calculated via | |
| 1987 | + * the repeated squaring technique into a single accumulator. | |
| 1988 | + * The individual multiplications with the accumulator use the | |
| 1989 | + * same math context settings as in {@code mc} except for a | |
| 1990 | + * precision increased to {@code mc.precision + elength + 1} | |
| 1991 | + * where {@code elength} is the number of decimal digits in | |
| 1992 | + * {@code n}. | |
| 1993 | + * | |
| 1994 | + * <li> if {@code n} is negative, the result is calculated as if | |
| 1995 | + * {@code n} were positive; this value is then divided into one | |
| 1996 | + * using the working precision specified above. | |
| 1997 | + * | |
| 1998 | + * <li> The final value from either the positive or negative case | |
| 1999 | + * is then rounded to the destination precision. | |
| 2000 | + * </ul> | |
| 2001 | + * </ul> | |
| 2002 | + * | |
| 2003 | + * @param n power to raise this {@code BigDecimal} to. | |
| 2004 | + * @param mc the context to use. | |
| 2005 | + * @return <tt>this<sup>n</sup></tt> using the ANSI standard X3.274-1996 | |
| 2006 | + * algorithm | |
| 2007 | + * @throws ArithmeticException if the result is inexact but the | |
| 2008 | + * rounding mode is {@code UNNECESSARY}, or {@code n} is out | |
| 2009 | + * of range. | |
| 2010 | + * @since 1.5 | |
| 2011 | + */ | |
| 2012 | + public BigDecimal pow(int n, MathContext mc) { | |
| 2013 | + if (mc.precision == 0) | |
| 2014 | + return pow(n); | |
| 2015 | + if (n < -999999999 || n > 999999999) | |
| 2016 | + throw new ArithmeticException("Invalid operation"); | |
| 2017 | + if (n == 0) | |
| 2018 | + return ONE; // x**0 == 1 in X3.274 | |
| 2019 | + this.inflate(); | |
| 2020 | + BigDecimal lhs = this; | |
| 2021 | + MathContext workmc = mc; // working settings | |
| 2022 | + int mag = Math.abs(n); // magnitude of n | |
| 2023 | + if (mc.precision > 0) { | |
| 2024 | + | |
| 2025 | + int elength = longDigitLength(mag); // length of n in digits | |
| 2026 | + if (elength > mc.precision) // X3.274 rule | |
| 2027 | + throw new ArithmeticException("Invalid operation"); | |
| 2028 | + workmc = new MathContext(mc.precision + elength + 1, | |
| 2029 | + mc.roundingMode); | |
| 2030 | + } | |
| 2031 | + // ready to carry out power calculation... | |
| 2032 | + BigDecimal acc = ONE; // accumulator | |
| 2033 | + boolean seenbit = false; // set once we've seen a 1-bit | |
| 2034 | + for (int i=1;;i++) { // for each bit [top bit ignored] | |
| 2035 | + mag += mag; // shift left 1 bit | |
| 2036 | + if (mag < 0) { // top bit is set | |
| 2037 | + seenbit = true; // OK, we're off | |
| 2038 | + acc = acc.multiply(lhs, workmc); // acc=acc*x | |
| 2039 | + } | |
| 2040 | + if (i == 31) | |
| 2041 | + break; // that was the last bit | |
| 2042 | + if (seenbit) | |
| 2043 | + acc=acc.multiply(acc, workmc); // acc=acc*acc [square] | |
| 2044 | + // else (!seenbit) no point in squaring ONE | |
| 2045 | + } | |
| 2046 | + // if negative n, calculate the reciprocal using working precision | |
| 2047 | + if (n<0) // [hence mc.precision>0] | |
| 2048 | + acc=ONE.divide(acc, workmc); | |
| 2049 | + // round to final precision and strip zeros | |
| 2050 | + return doRound(acc, mc); | |
| 2051 | + } | |
| 2052 | + | |
| 2053 | + /** | |
| 2054 | + * Returns a {@code BigDecimal} whose value is the absolute value | |
| 2055 | + * of this {@code BigDecimal}, and whose scale is | |
| 2056 | + * {@code this.scale()}. | |
| 2057 | + * | |
| 2058 | + * @return {@code abs(this)} | |
| 2059 | + */ | |
| 2060 | + public BigDecimal abs() { | |
| 2061 | + return (signum() < 0 ? negate() : this); | |
| 2062 | + } | |
| 2063 | + | |
| 2064 | + /** | |
| 2065 | + * Returns a {@code BigDecimal} whose value is the absolute value | |
| 2066 | + * of this {@code BigDecimal}, with rounding according to the | |
| 2067 | + * context settings. | |
| 2068 | + * | |
| 2069 | + * @param mc the context to use. | |
| 2070 | + * @return {@code abs(this)}, rounded as necessary. | |
| 2071 | + * @throws ArithmeticException if the result is inexact but the | |
| 2072 | + * rounding mode is {@code UNNECESSARY}. | |
| 2073 | + * @since 1.5 | |
| 2074 | + */ | |
| 2075 | + public BigDecimal abs(MathContext mc) { | |
| 2076 | + return (signum() < 0 ? negate(mc) : plus(mc)); | |
| 2077 | + } | |
| 2078 | + | |
| 2079 | + /** | |
| 2080 | + * Returns a {@code BigDecimal} whose value is {@code (-this)}, | |
| 2081 | + * and whose scale is {@code this.scale()}. | |
| 2082 | + * | |
| 2083 | + * @return {@code -this}. | |
| 2084 | + */ | |
| 2085 | + public BigDecimal negate() { | |
| 2086 | + BigDecimal result; | |
| 2087 | + if (intCompact != INFLATED) | |
| 2088 | + result = BigDecimal.valueOf(-intCompact, scale); | |
| 2089 | + else { | |
| 2090 | + result = new BigDecimal(intVal.negate(), scale); | |
| 2091 | + result.precision = precision; | |
| 2092 | + } | |
| 2093 | + return result; | |
| 2094 | + } | |
| 2095 | + | |
| 2096 | + /** | |
| 2097 | + * Returns a {@code BigDecimal} whose value is {@code (-this)}, | |
| 2098 | + * with rounding according to the context settings. | |
| 2099 | + * | |
| 2100 | + * @param mc the context to use. | |
| 2101 | + * @return {@code -this}, rounded as necessary. | |
| 2102 | + * @throws ArithmeticException if the result is inexact but the | |
| 2103 | + * rounding mode is {@code UNNECESSARY}. | |
| 2104 | + * @since 1.5 | |
| 2105 | + */ | |
| 2106 | + public BigDecimal negate(MathContext mc) { | |
| 2107 | + return negate().plus(mc); | |
| 2108 | + } | |
| 2109 | + | |
| 2110 | + /** | |
| 2111 | + * Returns a {@code BigDecimal} whose value is {@code (+this)}, and whose | |
| 2112 | + * scale is {@code this.scale()}. | |
| 2113 | + * | |
| 2114 | + * <p>This method, which simply returns this {@code BigDecimal} | |
| 2115 | + * is included for symmetry with the unary minus method {@link | |
| 2116 | + * #negate()}. | |
| 2117 | + * | |
| 2118 | + * @return {@code this}. | |
| 2119 | + * @see #negate() | |
| 2120 | + * @since 1.5 | |
| 2121 | + */ | |
| 2122 | + public BigDecimal plus() { | |
| 2123 | + return this; | |
| 2124 | + } | |
| 2125 | + | |
| 2126 | + /** | |
| 2127 | + * Returns a {@code BigDecimal} whose value is {@code (+this)}, | |
| 2128 | + * with rounding according to the context settings. | |
| 2129 | + * | |
| 2130 | + * <p>The effect of this method is identical to that of the {@link | |
| 2131 | + * #round(MathContext)} method. | |
| 2132 | + * | |
| 2133 | + * @param mc the context to use. | |
| 2134 | + * @return {@code this}, rounded as necessary. A zero result will | |
| 2135 | + * have a scale of 0. | |
| 2136 | + * @throws ArithmeticException if the result is inexact but the | |
| 2137 | + * rounding mode is {@code UNNECESSARY}. | |
| 2138 | + * @see #round(MathContext) | |
| 2139 | + * @since 1.5 | |
| 2140 | + */ | |
| 2141 | + public BigDecimal plus(MathContext mc) { | |
| 2142 | + if (mc.precision == 0) // no rounding please | |
| 2143 | + return this; | |
| 2144 | + return doRound(this, mc); | |
| 2145 | + } | |
| 2146 | + | |
| 2147 | + /** | |
| 2148 | + * Returns the signum function of this {@code BigDecimal}. | |
| 2149 | + * | |
| 2150 | + * @return -1, 0, or 1 as the value of this {@code BigDecimal} | |
| 2151 | + * is negative, zero, or positive. | |
| 2152 | + */ | |
| 2153 | + public int signum() { | |
| 2154 | + return (intCompact != INFLATED)? | |
| 2155 | + Long.signum(intCompact): | |
| 2156 | + intVal.signum(); | |
| 2157 | + } | |
| 2158 | + | |
| 2159 | + /** | |
| 2160 | + * Returns the <i>scale</i> of this {@code BigDecimal}. If zero | |
| 2161 | + * or positive, the scale is the number of digits to the right of | |
| 2162 | + * the decimal point. If negative, the unscaled value of the | |
| 2163 | + * number is multiplied by ten to the power of the negation of the | |
| 2164 | + * scale. For example, a scale of {@code -3} means the unscaled | |
| 2165 | + * value is multiplied by 1000. | |
| 2166 | + * | |
| 2167 | + * @return the scale of this {@code BigDecimal}. | |
| 2168 | + */ | |
| 2169 | + public int scale() { | |
| 2170 | + return scale; | |
| 2171 | + } | |
| 2172 | + | |
| 2173 | + /** | |
| 2174 | + * Returns the <i>precision</i> of this {@code BigDecimal}. (The | |
| 2175 | + * precision is the number of digits in the unscaled value.) | |
| 2176 | + * | |
| 2177 | + * <p>The precision of a zero value is 1. | |
| 2178 | + * | |
| 2179 | + * @return the precision of this {@code BigDecimal}. | |
| 2180 | + * @since 1.5 | |
| 2181 | + */ | |
| 2182 | + public int precision() { | |
| 2183 | + int result = precision; | |
| 2184 | + if (result == 0) { | |
| 2185 | + long s = intCompact; | |
| 2186 | + if (s != INFLATED) | |
| 2187 | + result = longDigitLength(s); | |
| 2188 | + else | |
| 2189 | + result = bigDigitLength(inflate()); | |
| 2190 | + precision = result; | |
| 2191 | + } | |
| 2192 | + return result; | |
| 2193 | + } | |
| 2194 | + | |
| 2195 | + | |
| 2196 | + /** | |
| 2197 | + * Returns a {@code BigInteger} whose value is the <i>unscaled | |
| 2198 | + * value</i> of this {@code BigDecimal}. (Computes <tt>(this * | |
| 2199 | + * 10<sup>this.scale()</sup>)</tt>.) | |
| 2200 | + * | |
| 2201 | + * @return the unscaled value of this {@code BigDecimal}. | |
| 2202 | + * @since 1.2 | |
| 2203 | + */ | |
| 2204 | + public BigInteger unscaledValue() { | |
| 2205 | + return this.inflate(); | |
| 2206 | + } | |
| 2207 | + | |
| 2208 | + // Rounding Modes | |
| 2209 | + | |
| 2210 | + /** | |
| 2211 | + * Rounding mode to round away from zero. Always increments the | |
| 2212 | + * digit prior to a nonzero discarded fraction. Note that this rounding | |
| 2213 | + * mode never decreases the magnitude of the calculated value. | |
| 2214 | + */ | |
| 2215 | + public final static int ROUND_UP = 0; | |
| 2216 | + | |
| 2217 | + /** | |
| 2218 | + * Rounding mode to round towards zero. Never increments the digit | |
| 2219 | + * prior to a discarded fraction (i.e., truncates). Note that this | |
| 2220 | + * rounding mode never increases the magnitude of the calculated value. | |
| 2221 | + */ | |
| 2222 | + public final static int ROUND_DOWN = 1; | |
| 2223 | + | |
| 2224 | + /** | |
| 2225 | + * Rounding mode to round towards positive infinity. If the | |
| 2226 | + * {@code BigDecimal} is positive, behaves as for | |
| 2227 | + * {@code ROUND_UP}; if negative, behaves as for | |
| 2228 | + * {@code ROUND_DOWN}. Note that this rounding mode never | |
| 2229 | + * decreases the calculated value. | |
| 2230 | + */ | |
| 2231 | + public final static int ROUND_CEILING = 2; | |
| 2232 | + | |
| 2233 | + /** | |
| 2234 | + * Rounding mode to round towards negative infinity. If the | |
| 2235 | + * {@code BigDecimal} is positive, behave as for | |
| 2236 | + * {@code ROUND_DOWN}; if negative, behave as for | |
| 2237 | + * {@code ROUND_UP}. Note that this rounding mode never | |
| 2238 | + * increases the calculated value. | |
| 2239 | + */ | |
| 2240 | + public final static int ROUND_FLOOR = 3; | |
| 2241 | + | |
| 2242 | + /** | |
| 2243 | + * Rounding mode to round towards {@literal "nearest neighbor"} | |
| 2244 | + * unless both neighbors are equidistant, in which case round up. | |
| 2245 | + * Behaves as for {@code ROUND_UP} if the discarded fraction is | |
| 2246 | + * ≥ 0.5; otherwise, behaves as for {@code ROUND_DOWN}. Note | |
| 2247 | + * that this is the rounding mode that most of us were taught in | |
| 2248 | + * grade school. | |
| 2249 | + */ | |
| 2250 | + public final static int ROUND_HALF_UP = 4; | |
| 2251 | + | |
| 2252 | + /** | |
| 2253 | + * Rounding mode to round towards {@literal "nearest neighbor"} | |
| 2254 | + * unless both neighbors are equidistant, in which case round | |
| 2255 | + * down. Behaves as for {@code ROUND_UP} if the discarded | |
| 2256 | + * fraction is {@literal >} 0.5; otherwise, behaves as for | |
| 2257 | + * {@code ROUND_DOWN}. | |
| 2258 | + */ | |
| 2259 | + public final static int ROUND_HALF_DOWN = 5; | |
| 2260 | + | |
| 2261 | + /** | |
| 2262 | + * Rounding mode to round towards the {@literal "nearest neighbor"} | |
| 2263 | + * unless both neighbors are equidistant, in which case, round | |
| 2264 | + * towards the even neighbor. Behaves as for | |
| 2265 | + * {@code ROUND_HALF_UP} if the digit to the left of the | |
| 2266 | + * discarded fraction is odd; behaves as for | |
| 2267 | + * {@code ROUND_HALF_DOWN} if it's even. Note that this is the | |
| 2268 | + * rounding mode that minimizes cumulative error when applied | |
| 2269 | + * repeatedly over a sequence of calculations. | |
| 2270 | + */ | |
| 2271 | + public final static int ROUND_HALF_EVEN = 6; | |
| 2272 | + | |
| 2273 | + /** | |
| 2274 | + * Rounding mode to assert that the requested operation has an exact | |
| 2275 | + * result, hence no rounding is necessary. If this rounding mode is | |
| 2276 | + * specified on an operation that yields an inexact result, an | |
| 2277 | + * {@code ArithmeticException} is thrown. | |
| 2278 | + */ | |
| 2279 | + public final static int ROUND_UNNECESSARY = 7; | |
| 2280 | + | |
| 2281 | + | |
| 2282 | + // Scaling/Rounding Operations | |
| 2283 | + | |
| 2284 | + /** | |
| 2285 | + * Returns a {@code BigDecimal} rounded according to the | |
| 2286 | + * {@code MathContext} settings. If the precision setting is 0 then | |
| 2287 | + * no rounding takes place. | |
| 2288 | + * | |
| 2289 | + * <p>The effect of this method is identical to that of the | |
| 2290 | + * {@link #plus(MathContext)} method. | |
| 2291 | + * | |
| 2292 | + * @param mc the context to use. | |
| 2293 | + * @return a {@code BigDecimal} rounded according to the | |
| 2294 | + * {@code MathContext} settings. | |
| 2295 | + * @throws ArithmeticException if the rounding mode is | |
| 2296 | + * {@code UNNECESSARY} and the | |
| 2297 | + * {@code BigDecimal} operation would require rounding. | |
| 2298 | + * @see #plus(MathContext) | |
| 2299 | + * @since 1.5 | |
| 2300 | + */ | |
| 2301 | + public BigDecimal round(MathContext mc) { | |
| 2302 | + return plus(mc); | |
| 2303 | + } | |
| 2304 | + | |
| 2305 | + /** | |
| 2306 | + * Returns a {@code BigDecimal} whose scale is the specified | |
| 2307 | + * value, and whose unscaled value is determined by multiplying or | |
| 2308 | + * dividing this {@code BigDecimal}'s unscaled value by the | |
| 2309 | + * appropriate power of ten to maintain its overall value. If the | |
| 2310 | + * scale is reduced by the operation, the unscaled value must be | |
| 2311 | + * divided (rather than multiplied), and the value may be changed; | |
| 2312 | + * in this case, the specified rounding mode is applied to the | |
| 2313 | + * division. | |
| 2314 | + * | |
| 2315 | + * <p>Note that since BigDecimal objects are immutable, calls of | |
| 2316 | + * this method do <i>not</i> result in the original object being | |
| 2317 | + * modified, contrary to the usual convention of having methods | |
| 2318 | + * named <tt>set<i>X</i></tt> mutate field <i>{@code X}</i>. | |
| 2319 | + * Instead, {@code setScale} returns an object with the proper | |
| 2320 | + * scale; the returned object may or may not be newly allocated. | |
| 2321 | + * | |
| 2322 | + * @param newScale scale of the {@code BigDecimal} value to be returned. | |
| 2323 | + * @param roundingMode The rounding mode to apply. | |
| 2324 | + * @return a {@code BigDecimal} whose scale is the specified value, | |
| 2325 | + * and whose unscaled value is determined by multiplying or | |
| 2326 | + * dividing this {@code BigDecimal}'s unscaled value by the | |
| 2327 | + * appropriate power of ten to maintain its overall value. | |
| 2328 | + * @throws ArithmeticException if {@code roundingMode==UNNECESSARY} | |
| 2329 | + * and the specified scaling operation would require | |
| 2330 | + * rounding. | |
| 2331 | + * @see RoundingMode | |
| 2332 | + * @since 1.5 | |
| 2333 | + */ | |
| 2334 | + public BigDecimal setScale(int newScale, RoundingMode roundingMode) { | |
| 2335 | + return setScale(newScale, roundingMode.oldMode); | |
| 2336 | + } | |
| 2337 | + | |
| 2338 | + /** | |
| 2339 | + * Returns a {@code BigDecimal} whose scale is the specified | |
| 2340 | + * value, and whose unscaled value is determined by multiplying or | |
| 2341 | + * dividing this {@code BigDecimal}'s unscaled value by the | |
| 2342 | + * appropriate power of ten to maintain its overall value. If the | |
| 2343 | + * scale is reduced by the operation, the unscaled value must be | |
| 2344 | + * divided (rather than multiplied), and the value may be changed; | |
| 2345 | + * in this case, the specified rounding mode is applied to the | |
| 2346 | + * division. | |
| 2347 | + * | |
| 2348 | + * <p>Note that since BigDecimal objects are immutable, calls of | |
| 2349 | + * this method do <i>not</i> result in the original object being | |
| 2350 | + * modified, contrary to the usual convention of having methods | |
| 2351 | + * named <tt>set<i>X</i></tt> mutate field <i>{@code X}</i>. | |
| 2352 | + * Instead, {@code setScale} returns an object with the proper | |
| 2353 | + * scale; the returned object may or may not be newly allocated. | |
| 2354 | + * | |
| 2355 | + * <p>The new {@link #setScale(int, RoundingMode)} method should | |
| 2356 | + * be used in preference to this legacy method. | |
| 2357 | + * | |
| 2358 | + * @param newScale scale of the {@code BigDecimal} value to be returned. | |
| 2359 | + * @param roundingMode The rounding mode to apply. | |
| 2360 | + * @return a {@code BigDecimal} whose scale is the specified value, | |
| 2361 | + * and whose unscaled value is determined by multiplying or | |
| 2362 | + * dividing this {@code BigDecimal}'s unscaled value by the | |
| 2363 | + * appropriate power of ten to maintain its overall value. | |
| 2364 | + * @throws ArithmeticException if {@code roundingMode==ROUND_UNNECESSARY} | |
| 2365 | + * and the specified scaling operation would require | |
| 2366 | + * rounding. | |
| 2367 | + * @throws IllegalArgumentException if {@code roundingMode} does not | |
| 2368 | + * represent a valid rounding mode. | |
| 2369 | + * @see #ROUND_UP | |
| 2370 | + * @see #ROUND_DOWN | |
| 2371 | + * @see #ROUND_CEILING | |
| 2372 | + * @see #ROUND_FLOOR | |
| 2373 | + * @see #ROUND_HALF_UP | |
| 2374 | + * @see #ROUND_HALF_DOWN | |
| 2375 | + * @see #ROUND_HALF_EVEN | |
| 2376 | + * @see #ROUND_UNNECESSARY | |
| 2377 | + */ | |
| 2378 | + public BigDecimal setScale(int newScale, int roundingMode) { | |
| 2379 | + if (roundingMode < ROUND_UP || roundingMode > ROUND_UNNECESSARY) | |
| 2380 | + throw new IllegalArgumentException("Invalid rounding mode"); | |
| 2381 | + | |
| 2382 | + int oldScale = this.scale; | |
| 2383 | + if (newScale == oldScale) // easy case | |
| 2384 | + return this; | |
| 2385 | + if (this.signum() == 0) // zero can have any scale | |
| 2386 | + return BigDecimal.valueOf(0, newScale); | |
| 2387 | + | |
| 2388 | + long rs = this.intCompact; | |
| 2389 | + if (newScale > oldScale) { | |
| 2390 | + int raise = checkScale((long)newScale - oldScale); | |
| 2391 | + BigInteger rb = null; | |
| 2392 | + if (rs == INFLATED || | |
| 2393 | + (rs = longMultiplyPowerTen(rs, raise)) == INFLATED) | |
| 2394 | + rb = bigMultiplyPowerTen(raise); | |
| 2395 | + return new BigDecimal(rb, rs, newScale, | |
| 2396 | + (precision > 0) ? precision + raise : 0); | |
| 2397 | + } else { | |
| 2398 | + // newScale < oldScale -- drop some digits | |
| 2399 | + // Can't predict the precision due to the effect of rounding. | |
| 2400 | + int drop = checkScale((long)oldScale - newScale); | |
| 2401 | + if (drop < LONG_TEN_POWERS_TABLE.length) | |
| 2402 | + return divideAndRound(rs, this.intVal, | |
| 2403 | + LONG_TEN_POWERS_TABLE[drop], null, | |
| 2404 | + newScale, roundingMode, newScale); | |
| 2405 | + else | |
| 2406 | + return divideAndRound(rs, this.intVal, | |
| 2407 | + INFLATED, bigTenToThe(drop), | |
| 2408 | + newScale, roundingMode, newScale); | |
| 2409 | + } | |
| 2410 | + } | |
| 2411 | + | |
| 2412 | + /** | |
| 2413 | + * Returns a {@code BigDecimal} whose scale is the specified | |
| 2414 | + * value, and whose value is numerically equal to this | |
| 2415 | + * {@code BigDecimal}'s. Throws an {@code ArithmeticException} | |
| 2416 | + * if this is not possible. | |
| 2417 | + * | |
| 2418 | + * <p>This call is typically used to increase the scale, in which | |
| 2419 | + * case it is guaranteed that there exists a {@code BigDecimal} | |
| 2420 | + * of the specified scale and the correct value. The call can | |
| 2421 | + * also be used to reduce the scale if the caller knows that the | |
| 2422 | + * {@code BigDecimal} has sufficiently many zeros at the end of | |
| 2423 | + * its fractional part (i.e., factors of ten in its integer value) | |
| 2424 | + * to allow for the rescaling without changing its value. | |
| 2425 | + * | |
| 2426 | + * <p>This method returns the same result as the two-argument | |
| 2427 | + * versions of {@code setScale}, but saves the caller the trouble | |
| 2428 | + * of specifying a rounding mode in cases where it is irrelevant. | |
| 2429 | + * | |
| 2430 | + * <p>Note that since {@code BigDecimal} objects are immutable, | |
| 2431 | + * calls of this method do <i>not</i> result in the original | |
| 2432 | + * object being modified, contrary to the usual convention of | |
| 2433 | + * having methods named <tt>set<i>X</i></tt> mutate field | |
| 2434 | + * <i>{@code X}</i>. Instead, {@code setScale} returns an | |
| 2435 | + * object with the proper scale; the returned object may or may | |
| 2436 | + * not be newly allocated. | |
| 2437 | + * | |
| 2438 | + * @param newScale scale of the {@code BigDecimal} value to be returned. | |
| 2439 | + * @return a {@code BigDecimal} whose scale is the specified value, and | |
| 2440 | + * whose unscaled value is determined by multiplying or dividing | |
| 2441 | + * this {@code BigDecimal}'s unscaled value by the appropriate | |
| 2442 | + * power of ten to maintain its overall value. | |
| 2443 | + * @throws ArithmeticException if the specified scaling operation would | |
| 2444 | + * require rounding. | |
| 2445 | + * @see #setScale(int, int) | |
| 2446 | + * @see #setScale(int, RoundingMode) | |
| 2447 | + */ | |
| 2448 | + public BigDecimal setScale(int newScale) { | |
| 2449 | + return setScale(newScale, ROUND_UNNECESSARY); | |
| 2450 | + } | |
| 2451 | + | |
| 2452 | + // Decimal Point Motion Operations | |
| 2453 | + | |
| 2454 | + /** | |
| 2455 | + * Returns a {@code BigDecimal} which is equivalent to this one | |
| 2456 | + * with the decimal point moved {@code n} places to the left. If | |
| 2457 | + * {@code n} is non-negative, the call merely adds {@code n} to | |
| 2458 | + * the scale. If {@code n} is negative, the call is equivalent | |
| 2459 | + * to {@code movePointRight(-n)}. The {@code BigDecimal} | |
| 2460 | + * returned by this call has value <tt>(this × | |
| 2461 | + * 10<sup>-n</sup>)</tt> and scale {@code max(this.scale()+n, | |
| 2462 | + * 0)}. | |
| 2463 | + * | |
| 2464 | + * @param n number of places to move the decimal point to the left. | |
| 2465 | + * @return a {@code BigDecimal} which is equivalent to this one with the | |
| 2466 | + * decimal point moved {@code n} places to the left. | |
| 2467 | + * @throws ArithmeticException if scale overflows. | |
| 2468 | + */ | |
| 2469 | + public BigDecimal movePointLeft(int n) { | |
| 2470 | + // Cannot use movePointRight(-n) in case of n==Integer.MIN_VALUE | |
| 2471 | + int newScale = checkScale((long)scale + n); | |
| 2472 | + BigDecimal num = new BigDecimal(intVal, intCompact, newScale, 0); | |
| 2473 | + return num.scale < 0 ? num.setScale(0, ROUND_UNNECESSARY) : num; | |
| 2474 | + } | |
| 2475 | + | |
| 2476 | + /** | |
| 2477 | + * Returns a {@code BigDecimal} which is equivalent to this one | |
| 2478 | + * with the decimal point moved {@code n} places to the right. | |
| 2479 | + * If {@code n} is non-negative, the call merely subtracts | |
| 2480 | + * {@code n} from the scale. If {@code n} is negative, the call | |
| 2481 | + * is equivalent to {@code movePointLeft(-n)}. The | |
| 2482 | + * {@code BigDecimal} returned by this call has value <tt>(this | |
| 2483 | + * × 10<sup>n</sup>)</tt> and scale {@code max(this.scale()-n, | |
| 2484 | + * 0)}. | |
| 2485 | + * | |
| 2486 | + * @param n number of places to move the decimal point to the right. | |
| 2487 | + * @return a {@code BigDecimal} which is equivalent to this one | |
| 2488 | + * with the decimal point moved {@code n} places to the right. | |
| 2489 | + * @throws ArithmeticException if scale overflows. | |
| 2490 | + */ | |
| 2491 | + public BigDecimal movePointRight(int n) { | |
| 2492 | + // Cannot use movePointLeft(-n) in case of n==Integer.MIN_VALUE | |
| 2493 | + int newScale = checkScale((long)scale - n); | |
| 2494 | + BigDecimal num = new BigDecimal(intVal, intCompact, newScale, 0); | |
| 2495 | + return num.scale < 0 ? num.setScale(0, ROUND_UNNECESSARY) : num; | |
| 2496 | + } | |
| 2497 | + | |
| 2498 | + /** | |
| 2499 | + * Returns a BigDecimal whose numerical value is equal to | |
| 2500 | + * ({@code this} * 10<sup>n</sup>). The scale of | |
| 2501 | + * the result is {@code (this.scale() - n)}. | |
| 2502 | + * | |
| 2503 | + * @throws ArithmeticException if the scale would be | |
| 2504 | + * outside the range of a 32-bit integer. | |
| 2505 | + * | |
| 2506 | + * @since 1.5 | |
| 2507 | + */ | |
| 2508 | + public BigDecimal scaleByPowerOfTen(int n) { | |
| 2509 | + return new BigDecimal(intVal, intCompact, | |
| 2510 | + checkScale((long)scale - n), precision); | |
| 2511 | + } | |
| 2512 | + | |
| 2513 | + /** | |
| 2514 | + * Returns a {@code BigDecimal} which is numerically equal to | |
| 2515 | + * this one but with any trailing zeros removed from the | |
| 2516 | + * representation. For example, stripping the trailing zeros from | |
| 2517 | + * the {@code BigDecimal} value {@code 600.0}, which has | |
| 2518 | + * [{@code BigInteger}, {@code scale}] components equals to | |
| 2519 | + * [6000, 1], yields {@code 6E2} with [{@code BigInteger}, | |
| 2520 | + * {@code scale}] components equals to [6, -2] | |
| 2521 | + * | |
| 2522 | + * @return a numerically equal {@code BigDecimal} with any | |
| 2523 | + * trailing zeros removed. | |
| 2524 | + * @since 1.5 | |
| 2525 | + */ | |
| 2526 | + public BigDecimal stripTrailingZeros() { | |
| 2527 | + this.inflate(); | |
| 2528 | + BigDecimal result = new BigDecimal(intVal, scale); | |
| 2529 | + result.stripZerosToMatchScale(Long.MIN_VALUE); | |
| 2530 | + return result; | |
| 2531 | + } | |
| 2532 | + | |
| 2533 | + // Comparison Operations | |
| 2534 | + | |
| 2535 | + /** | |
| 2536 | + * Compares this {@code BigDecimal} with the specified | |
| 2537 | + * {@code BigDecimal}. Two {@code BigDecimal} objects that are | |
| 2538 | + * equal in value but have a different scale (like 2.0 and 2.00) | |
| 2539 | + * are considered equal by this method. This method is provided | |
| 2540 | + * in preference to individual methods for each of the six boolean | |
| 2541 | + * comparison operators ({@literal <}, ==, | |
| 2542 | + * {@literal >}, {@literal >=}, !=, {@literal <=}). The | |
| 2543 | + * suggested idiom for performing these comparisons is: | |
| 2544 | + * {@code (x.compareTo(y)} <<i>op</i>> {@code 0)}, where | |
| 2545 | + * <<i>op</i>> is one of the six comparison operators. | |
| 2546 | + * | |
| 2547 | + * @param val {@code BigDecimal} to which this {@code BigDecimal} is | |
| 2548 | + * to be compared. | |
| 2549 | + * @return -1, 0, or 1 as this {@code BigDecimal} is numerically | |
| 2550 | + * less than, equal to, or greater than {@code val}. | |
| 2551 | + */ | |
| 2552 | + public int compareTo(BigDecimal val) { | |
| 2553 | + // Quick path for equal scale and non-inflated case. | |
| 2554 | + if (scale == val.scale) { | |
| 2555 | + long xs = intCompact; | |
| 2556 | + long ys = val.intCompact; | |
| 2557 | + if (xs != INFLATED && ys != INFLATED) | |
| 2558 | + return xs != ys ? ((xs > ys) ? 1 : -1) : 0; | |
| 2559 | + } | |
| 2560 | + int xsign = this.signum(); | |
| 2561 | + int ysign = val.signum(); | |
| 2562 | + if (xsign != ysign) | |
| 2563 | + return (xsign > ysign) ? 1 : -1; | |
| 2564 | + if (xsign == 0) | |
| 2565 | + return 0; | |
| 2566 | + int cmp = compareMagnitude(val); | |
| 2567 | + return (xsign > 0) ? cmp : -cmp; | |
| 2568 | + } | |
| 2569 | + | |
| 2570 | + /** | |
| 2571 | + * Version of compareTo that ignores sign. | |
| 2572 | + */ | |
| 2573 | + private int compareMagnitude(BigDecimal val) { | |
| 2574 | + // Match scales, avoid unnecessary inflation | |
| 2575 | + long ys = val.intCompact; | |
| 2576 | + long xs = this.intCompact; | |
| 2577 | + if (xs == 0) | |
| 2578 | + return (ys == 0) ? 0 : -1; | |
| 2579 | + if (ys == 0) | |
| 2580 | + return 1; | |
| 2581 | + | |
| 2582 | + int sdiff = this.scale - val.scale; | |
| 2583 | + if (sdiff != 0) { | |
| 2584 | + // Avoid matching scales if the (adjusted) exponents differ | |
| 2585 | + int xae = this.precision() - this.scale; // [-1] | |
| 2586 | + int yae = val.precision() - val.scale; // [-1] | |
| 2587 | + if (xae < yae) | |
| 2588 | + return -1; | |
| 2589 | + if (xae > yae) | |
| 2590 | + return 1; | |
| 2591 | + BigInteger rb = null; | |
| 2592 | + if (sdiff < 0) { | |
| 2593 | + if ( (xs == INFLATED || | |
| 2594 | + (xs = longMultiplyPowerTen(xs, -sdiff)) == INFLATED) && | |
| 2595 | + ys == INFLATED) { | |
| 2596 | + rb = bigMultiplyPowerTen(-sdiff); | |
| 2597 | + return rb.compareMagnitude(val.intVal); | |
| 2598 | + } | |
| 2599 | + } else { // sdiff > 0 | |
| 2600 | + if ( (ys == INFLATED || | |
| 2601 | + (ys = longMultiplyPowerTen(ys, sdiff)) == INFLATED) && | |
| 2602 | + xs == INFLATED) { | |
| 2603 | + rb = val.bigMultiplyPowerTen(sdiff); | |
| 2604 | + return this.intVal.compareMagnitude(rb); | |
| 2605 | + } | |
| 2606 | + } | |
| 2607 | + } | |
| 2608 | + if (xs != INFLATED) | |
| 2609 | + return (ys != INFLATED) ? longCompareMagnitude(xs, ys) : -1; | |
| 2610 | + else if (ys != INFLATED) | |
| 2611 | + return 1; | |
| 2612 | + else | |
| 2613 | + return this.intVal.compareMagnitude(val.intVal); | |
| 2614 | + } | |
| 2615 | + | |
| 2616 | + /** | |
| 2617 | + * Compares this {@code BigDecimal} with the specified | |
| 2618 | + * {@code Object} for equality. Unlike {@link | |
| 2619 | + * #compareTo(BigDecimal) compareTo}, this method considers two | |
| 2620 | + * {@code BigDecimal} objects equal only if they are equal in | |
| 2621 | + * value and scale (thus 2.0 is not equal to 2.00 when compared by | |
| 2622 | + * this method). | |
| 2623 | + * | |
| 2624 | + * @param x {@code Object} to which this {@code BigDecimal} is | |
| 2625 | + * to be compared. | |
| 2626 | + * @return {@code true} if and only if the specified {@code Object} is a | |
| 2627 | + * {@code BigDecimal} whose value and scale are equal to this | |
| 2628 | + * {@code BigDecimal}'s. | |
| 2629 | + * @see #compareTo(java.math.BigDecimal) | |
| 2630 | + * @see #hashCode | |
| 2631 | + */ | |
| 2632 | + @Override | |
| 2633 | + public boolean equals(Object x) { | |
| 2634 | + if (!(x instanceof BigDecimal)) | |
| 2635 | + return false; | |
| 2636 | + BigDecimal xDec = (BigDecimal) x; | |
| 2637 | + if (x == this) | |
| 2638 | + return true; | |
| 2639 | + if (scale != xDec.scale) | |
| 2640 | + return false; | |
| 2641 | + long s = this.intCompact; | |
| 2642 | + long xs = xDec.intCompact; | |
| 2643 | + if (s != INFLATED) { | |
| 2644 | + if (xs == INFLATED) | |
| 2645 | + xs = compactValFor(xDec.intVal); | |
| 2646 | + return xs == s; | |
| 2647 | + } else if (xs != INFLATED) | |
| 2648 | + return xs == compactValFor(this.intVal); | |
| 2649 | + | |
| 2650 | + return this.inflate().equals(xDec.inflate()); | |
| 2651 | + } | |
| 2652 | + | |
| 2653 | + /** | |
| 2654 | + * Returns the minimum of this {@code BigDecimal} and | |
| 2655 | + * {@code val}. | |
| 2656 | + * | |
| 2657 | + * @param val value with which the minimum is to be computed. | |
| 2658 | + * @return the {@code BigDecimal} whose value is the lesser of this | |
| 2659 | + * {@code BigDecimal} and {@code val}. If they are equal, | |
| 2660 | + * as defined by the {@link #compareTo(BigDecimal) compareTo} | |
| 2661 | + * method, {@code this} is returned. | |
| 2662 | + * @see #compareTo(java.math.BigDecimal) | |
| 2663 | + */ | |
| 2664 | + public BigDecimal min(BigDecimal val) { | |
| 2665 | + return (compareTo(val) <= 0 ? this : val); | |
| 2666 | + } | |
| 2667 | + | |
| 2668 | + /** | |
| 2669 | + * Returns the maximum of this {@code BigDecimal} and {@code val}. | |
| 2670 | + * | |
| 2671 | + * @param val value with which the maximum is to be computed. | |
| 2672 | + * @return the {@code BigDecimal} whose value is the greater of this | |
| 2673 | + * {@code BigDecimal} and {@code val}. If they are equal, | |
| 2674 | + * as defined by the {@link #compareTo(BigDecimal) compareTo} | |
| 2675 | + * method, {@code this} is returned. | |
| 2676 | + * @see #compareTo(java.math.BigDecimal) | |
| 2677 | + */ | |
| 2678 | + public BigDecimal max(BigDecimal val) { | |
| 2679 | + return (compareTo(val) >= 0 ? this : val); | |
| 2680 | + } | |
| 2681 | + | |
| 2682 | + // Hash Function | |
| 2683 | + | |
| 2684 | + /** | |
| 2685 | + * Returns the hash code for this {@code BigDecimal}. Note that | |
| 2686 | + * two {@code BigDecimal} objects that are numerically equal but | |
| 2687 | + * differ in scale (like 2.0 and 2.00) will generally <i>not</i> | |
| 2688 | + * have the same hash code. | |
| 2689 | + * | |
| 2690 | + * @return hash code for this {@code BigDecimal}. | |
| 2691 | + * @see #equals(Object) | |
| 2692 | + */ | |
| 2693 | + @Override | |
| 2694 | + public int hashCode() { | |
| 2695 | + if (intCompact != INFLATED) { | |
| 2696 | + long val2 = (intCompact < 0)? -intCompact : intCompact; | |
| 2697 | + int temp = (int)( ((int)(val2 >>> 32)) * 31 + | |
| 2698 | + (val2 & LONG_MASK)); | |
| 2699 | + return 31*((intCompact < 0) ?-temp:temp) + scale; | |
| 2700 | + } else | |
| 2701 | + return 31*intVal.hashCode() + scale; | |
| 2702 | + } | |
| 2703 | + | |
| 2704 | + // Format Converters | |
| 2705 | + | |
| 2706 | + /** | |
| 2707 | + * Returns the string representation of this {@code BigDecimal}, | |
| 2708 | + * using scientific notation if an exponent is needed. | |
| 2709 | + * | |
| 2710 | + * <p>A standard canonical string form of the {@code BigDecimal} | |
| 2711 | + * is created as though by the following steps: first, the | |
| 2712 | + * absolute value of the unscaled value of the {@code BigDecimal} | |
| 2713 | + * is converted to a string in base ten using the characters | |
| 2714 | + * {@code '0'} through {@code '9'} with no leading zeros (except | |
| 2715 | + * if its value is zero, in which case a single {@code '0'} | |
| 2716 | + * character is used). | |
| 2717 | + * | |
| 2718 | + * <p>Next, an <i>adjusted exponent</i> is calculated; this is the | |
| 2719 | + * negated scale, plus the number of characters in the converted | |
| 2720 | + * unscaled value, less one. That is, | |
| 2721 | + * {@code -scale+(ulength-1)}, where {@code ulength} is the | |
| 2722 | + * length of the absolute value of the unscaled value in decimal | |
| 2723 | + * digits (its <i>precision</i>). | |
| 2724 | + * | |
| 2725 | + * <p>If the scale is greater than or equal to zero and the | |
| 2726 | + * adjusted exponent is greater than or equal to {@code -6}, the | |
| 2727 | + * number will be converted to a character form without using | |
| 2728 | + * exponential notation. In this case, if the scale is zero then | |
| 2729 | + * no decimal point is added and if the scale is positive a | |
| 2730 | + * decimal point will be inserted with the scale specifying the | |
| 2731 | + * number of characters to the right of the decimal point. | |
| 2732 | + * {@code '0'} characters are added to the left of the converted | |
| 2733 | + * unscaled value as necessary. If no character precedes the | |
| 2734 | + * decimal point after this insertion then a conventional | |
| 2735 | + * {@code '0'} character is prefixed. | |
| 2736 | + * | |
| 2737 | + * <p>Otherwise (that is, if the scale is negative, or the | |
| 2738 | + * adjusted exponent is less than {@code -6}), the number will be | |
| 2739 | + * converted to a character form using exponential notation. In | |
| 2740 | + * this case, if the converted {@code BigInteger} has more than | |
| 2741 | + * one digit a decimal point is inserted after the first digit. | |
| 2742 | + * An exponent in character form is then suffixed to the converted | |
| 2743 | + * unscaled value (perhaps with inserted decimal point); this | |
| 2744 | + * comprises the letter {@code 'E'} followed immediately by the | |
| 2745 | + * adjusted exponent converted to a character form. The latter is | |
| 2746 | + * in base ten, using the characters {@code '0'} through | |
| 2747 | + * {@code '9'} with no leading zeros, and is always prefixed by a | |
| 2748 | + * sign character {@code '-'} (<tt>'\u002D'</tt>) if the | |
| 2749 | + * adjusted exponent is negative, {@code '+'} | |
| 2750 | + * (<tt>'\u002B'</tt>) otherwise). | |
| 2751 | + * | |
| 2752 | + * <p>Finally, the entire string is prefixed by a minus sign | |
| 2753 | + * character {@code '-'} (<tt>'\u002D'</tt>) if the unscaled | |
| 2754 | + * value is less than zero. No sign character is prefixed if the | |
| 2755 | + * unscaled value is zero or positive. | |
| 2756 | + * | |
| 2757 | + * <p><b>Examples:</b> | |
| 2758 | + * <p>For each representation [<i>unscaled value</i>, <i>scale</i>] | |
| 2759 | + * on the left, the resulting string is shown on the right. | |
| 2760 | + * <pre> | |
| 2761 | + * [123,0] "123" | |
| 2762 | + * [-123,0] "-123" | |
| 2763 | + * [123,-1] "1.23E+3" | |
| 2764 | + * [123,-3] "1.23E+5" | |
| 2765 | + * [123,1] "12.3" | |
| 2766 | + * [123,5] "0.00123" | |
| 2767 | + * [123,10] "1.23E-8" | |
| 2768 | + * [-123,12] "-1.23E-10" | |
| 2769 | + * </pre> | |
| 2770 | + * | |
| 2771 | + * <b>Notes:</b> | |
| 2772 | + * <ol> | |
| 2773 | + * | |
| 2774 | + * <li>There is a one-to-one mapping between the distinguishable | |
| 2775 | + * {@code BigDecimal} values and the result of this conversion. | |
| 2776 | + * That is, every distinguishable {@code BigDecimal} value | |
| 2777 | + * (unscaled value and scale) has a unique string representation | |
| 2778 | + * as a result of using {@code toString}. If that string | |
| 2779 | + * representation is converted back to a {@code BigDecimal} using | |
| 2780 | + * the {@link #BigDecimal(String)} constructor, then the original | |
| 2781 | + * value will be recovered. | |
| 2782 | + * | |
| 2783 | + * <li>The string produced for a given number is always the same; | |
| 2784 | + * it is not affected by locale. This means that it can be used | |
| 2785 | + * as a canonical string representation for exchanging decimal | |
| 2786 | + * data, or as a key for a Hashtable, etc. Locale-sensitive | |
| 2787 | + * number formatting and parsing is handled by the {@link | |
| 2788 | + * java.text.NumberFormat} class and its subclasses. | |
| 2789 | + * | |
| 2790 | + * <li>The {@link #toEngineeringString} method may be used for | |
| 2791 | + * presenting numbers with exponents in engineering notation, and the | |
| 2792 | + * {@link #setScale(int,RoundingMode) setScale} method may be used for | |
| 2793 | + * rounding a {@code BigDecimal} so it has a known number of digits after | |
| 2794 | + * the decimal point. | |
| 2795 | + * | |
| 2796 | + * <li>The digit-to-character mapping provided by | |
| 2797 | + * {@code Character.forDigit} is used. | |
| 2798 | + * | |
| 2799 | + * </ol> | |
| 2800 | + * | |
| 2801 | + * @return string representation of this {@code BigDecimal}. | |
| 2802 | + * @see Character#forDigit | |
| 2803 | + * @see #BigDecimal(java.lang.String) | |
| 2804 | + */ | |
| 2805 | + @Override | |
| 2806 | + public String toString() { | |
| 2807 | + String sc = stringCache; | |
| 2808 | + if (sc == null) | |
| 2809 | + stringCache = sc = layoutChars(true); | |
| 2810 | + return sc; | |
| 2811 | + } | |
| 2812 | + | |
| 2813 | + /** | |
| 2814 | + * Returns a string representation of this {@code BigDecimal}, | |
| 2815 | + * using engineering notation if an exponent is needed. | |
| 2816 | + * | |
| 2817 | + * <p>Returns a string that represents the {@code BigDecimal} as | |
| 2818 | + * described in the {@link #toString()} method, except that if | |
| 2819 | + * exponential notation is used, the power of ten is adjusted to | |
| 2820 | + * be a multiple of three (engineering notation) such that the | |
| 2821 | + * integer part of nonzero values will be in the range 1 through | |
| 2822 | + * 999. If exponential notation is used for zero values, a | |
| 2823 | + * decimal point and one or two fractional zero digits are used so | |
| 2824 | + * that the scale of the zero value is preserved. Note that | |
| 2825 | + * unlike the output of {@link #toString()}, the output of this | |
| 2826 | + * method is <em>not</em> guaranteed to recover the same [integer, | |
| 2827 | + * scale] pair of this {@code BigDecimal} if the output string is | |
| 2828 | + * converting back to a {@code BigDecimal} using the {@linkplain | |
| 2829 | + * #BigDecimal(String) string constructor}. The result of this method meets | |
| 2830 | + * the weaker constraint of always producing a numerically equal | |
| 2831 | + * result from applying the string constructor to the method's output. | |
| 2832 | + * | |
| 2833 | + * @return string representation of this {@code BigDecimal}, using | |
| 2834 | + * engineering notation if an exponent is needed. | |
| 2835 | + * @since 1.5 | |
| 2836 | + */ | |
| 2837 | + public String toEngineeringString() { | |
| 2838 | + return layoutChars(false); | |
| 2839 | + } | |
| 2840 | + | |
| 2841 | + /** | |
| 2842 | + * Returns a string representation of this {@code BigDecimal} | |
| 2843 | + * without an exponent field. For values with a positive scale, | |
| 2844 | + * the number of digits to the right of the decimal point is used | |
| 2845 | + * to indicate scale. For values with a zero or negative scale, | |
| 2846 | + * the resulting string is generated as if the value were | |
| 2847 | + * converted to a numerically equal value with zero scale and as | |
| 2848 | + * if all the trailing zeros of the zero scale value were present | |
| 2849 | + * in the result. | |
| 2850 | + * | |
| 2851 | + * The entire string is prefixed by a minus sign character '-' | |
| 2852 | + * (<tt>'\u002D'</tt>) if the unscaled value is less than | |
| 2853 | + * zero. No sign character is prefixed if the unscaled value is | |
| 2854 | + * zero or positive. | |
| 2855 | + * | |
| 2856 | + * Note that if the result of this method is passed to the | |
| 2857 | + * {@linkplain #BigDecimal(String) string constructor}, only the | |
| 2858 | + * numerical value of this {@code BigDecimal} will necessarily be | |
| 2859 | + * recovered; the representation of the new {@code BigDecimal} | |
| 2860 | + * may have a different scale. In particular, if this | |
| 2861 | + * {@code BigDecimal} has a negative scale, the string resulting | |
| 2862 | + * from this method will have a scale of zero when processed by | |
| 2863 | + * the string constructor. | |
| 2864 | + * | |
| 2865 | + * (This method behaves analogously to the {@code toString} | |
| 2866 | + * method in 1.4 and earlier releases.) | |
| 2867 | + * | |
| 2868 | + * @return a string representation of this {@code BigDecimal} | |
| 2869 | + * without an exponent field. | |
| 2870 | + * @since 1.5 | |
| 2871 | + * @see #toString() | |
| 2872 | + * @see #toEngineeringString() | |
| 2873 | + */ | |
| 2874 | + public String toPlainString() { | |
| 2875 | + BigDecimal bd = this; | |
| 2876 | + if (bd.scale < 0) | |
| 2877 | + bd = bd.setScale(0); | |
| 2878 | + bd.inflate(); | |
| 2879 | + if (bd.scale == 0) // No decimal point | |
| 2880 | + return bd.intVal.toString(); | |
| 2881 | + return bd.getValueString(bd.signum(), bd.intVal.abs().toString(), bd.scale); | |
| 2882 | + } | |
| 2883 | + | |
| 2884 | + /* Returns a digit.digit string */ | |
| 2885 | + private String getValueString(int signum, String intString, int scale) { | |
| 2886 | + /* Insert decimal point */ | |
| 2887 | + StringBuilder buf; | |
| 2888 | + int insertionPoint = intString.length() - scale; | |
| 2889 | + if (insertionPoint == 0) { /* Point goes right before intVal */ | |
| 2890 | + return (signum<0 ? "-0." : "0.") + intString; | |
| 2891 | + } else if (insertionPoint > 0) { /* Point goes inside intVal */ | |
| 2892 | + buf = new StringBuilder(intString); | |
| 2893 | + buf.insert(insertionPoint, '.'); | |
| 2894 | + if (signum < 0) | |
| 2895 | + buf.insert(0, '-'); | |
| 2896 | + } else { /* We must insert zeros between point and intVal */ | |
| 2897 | + buf = new StringBuilder(3-insertionPoint + intString.length()); | |
| 2898 | + buf.append(signum<0 ? "-0." : "0."); | |
| 2899 | + for (int i=0; i<-insertionPoint; i++) | |
| 2900 | + buf.append('0'); | |
| 2901 | + buf.append(intString); | |
| 2902 | + } | |
| 2903 | + return buf.toString(); | |
| 2904 | + } | |
| 2905 | + | |
| 2906 | + /** | |
| 2907 | + * Converts this {@code BigDecimal} to a {@code BigInteger}. | |
| 2908 | + * This conversion is analogous to the | |
| 2909 | + * <i>narrowing primitive conversion</i> from {@code double} to | |
| 2910 | + * {@code long} as defined in section 5.1.3 of | |
| 2911 | + * <cite>The Java™ Language Specification</cite>: | |
| 2912 | + * any fractional part of this | |
| 2913 | + * {@code BigDecimal} will be discarded. Note that this | |
| 2914 | + * conversion can lose information about the precision of the | |
| 2915 | + * {@code BigDecimal} value. | |
| 2916 | + * <p> | |
| 2917 | + * To have an exception thrown if the conversion is inexact (in | |
| 2918 | + * other words if a nonzero fractional part is discarded), use the | |
| 2919 | + * {@link #toBigIntegerExact()} method. | |
| 2920 | + * | |
| 2921 | + * @return this {@code BigDecimal} converted to a {@code BigInteger}. | |
| 2922 | + */ | |
| 2923 | + public BigInteger toBigInteger() { | |
| 2924 | + // force to an integer, quietly | |
| 2925 | + return this.setScale(0, ROUND_DOWN).inflate(); | |
| 2926 | + } | |
| 2927 | + | |
| 2928 | + /** | |
| 2929 | + * Converts this {@code BigDecimal} to a {@code BigInteger}, | |
| 2930 | + * checking for lost information. An exception is thrown if this | |
| 2931 | + * {@code BigDecimal} has a nonzero fractional part. | |
| 2932 | + * | |
| 2933 | + * @return this {@code BigDecimal} converted to a {@code BigInteger}. | |
| 2934 | + * @throws ArithmeticException if {@code this} has a nonzero | |
| 2935 | + * fractional part. | |
| 2936 | + * @since 1.5 | |
| 2937 | + */ | |
| 2938 | + public BigInteger toBigIntegerExact() { | |
| 2939 | + // round to an integer, with Exception if decimal part non-0 | |
| 2940 | + return this.setScale(0, ROUND_UNNECESSARY).inflate(); | |
| 2941 | + } | |
| 2942 | + | |
| 2943 | + /** | |
| 2944 | + * Converts this {@code BigDecimal} to a {@code long}. | |
| 2945 | + * This conversion is analogous to the | |
| 2946 | + * <i>narrowing primitive conversion</i> from {@code double} to | |
| 2947 | + * {@code short} as defined in section 5.1.3 of | |
| 2948 | + * <cite>The Java™ Language Specification</cite>: | |
| 2949 | + * any fractional part of this | |
| 2950 | + * {@code BigDecimal} will be discarded, and if the resulting | |
| 2951 | + * "{@code BigInteger}" is too big to fit in a | |
| 2952 | + * {@code long}, only the low-order 64 bits are returned. | |
| 2953 | + * Note that this conversion can lose information about the | |
| 2954 | + * overall magnitude and precision of this {@code BigDecimal} value as well | |
| 2955 | + * as return a result with the opposite sign. | |
| 2956 | + * | |
| 2957 | + * @return this {@code BigDecimal} converted to a {@code long}. | |
| 2958 | + */ | |
| 2959 | + public long longValue(){ | |
| 2960 | + return (intCompact != INFLATED && scale == 0) ? | |
| 2961 | + intCompact: | |
| 2962 | + toBigInteger().longValue(); | |
| 2963 | + } | |
| 2964 | + | |
| 2965 | + /** | |
| 2966 | + * Converts this {@code BigDecimal} to a {@code long}, checking | |
| 2967 | + * for lost information. If this {@code BigDecimal} has a | |
| 2968 | + * nonzero fractional part or is out of the possible range for a | |
| 2969 | + * {@code long} result then an {@code ArithmeticException} is | |
| 2970 | + * thrown. | |
| 2971 | + * | |
| 2972 | + * @return this {@code BigDecimal} converted to a {@code long}. | |
| 2973 | + * @throws ArithmeticException if {@code this} has a nonzero | |
| 2974 | + * fractional part, or will not fit in a {@code long}. | |
| 2975 | + * @since 1.5 | |
| 2976 | + */ | |
| 2977 | + public long longValueExact() { | |
| 2978 | + if (intCompact != INFLATED && scale == 0) | |
| 2979 | + return intCompact; | |
| 2980 | + // If more than 19 digits in integer part it cannot possibly fit | |
| 2981 | + if ((precision() - scale) > 19) // [OK for negative scale too] | |
| 2982 | + throw new java.lang.ArithmeticException("Overflow"); | |
| 2983 | + // Fastpath zero and < 1.0 numbers (the latter can be very slow | |
| 2984 | + // to round if very small) | |
| 2985 | + if (this.signum() == 0) | |
| 2986 | + return 0; | |
| 2987 | + if ((this.precision() - this.scale) <= 0) | |
| 2988 | + throw new ArithmeticException("Rounding necessary"); | |
| 2989 | + // round to an integer, with Exception if decimal part non-0 | |
| 2990 | + BigDecimal num = this.setScale(0, ROUND_UNNECESSARY); | |
| 2991 | + if (num.precision() >= 19) // need to check carefully | |
| 2992 | + LongOverflow.check(num); | |
| 2993 | + return num.inflate().longValue(); | |
| 2994 | + } | |
| 2995 | + | |
| 2996 | + private static class LongOverflow { | |
| 2997 | + /** BigInteger equal to Long.MIN_VALUE. */ | |
| 2998 | + private static final BigInteger LONGMIN = BigInteger.valueOf(Long.MIN_VALUE); | |
| 2999 | + | |
| 3000 | + /** BigInteger equal to Long.MAX_VALUE. */ | |
| 3001 | + private static final BigInteger LONGMAX = BigInteger.valueOf(Long.MAX_VALUE); | |
| 3002 | + | |
| 3003 | + public static void check(BigDecimal num) { | |
| 3004 | + num.inflate(); | |
| 3005 | + if ((num.intVal.compareTo(LONGMIN) < 0) || | |
| 3006 | + (num.intVal.compareTo(LONGMAX) > 0)) | |
| 3007 | + throw new java.lang.ArithmeticException("Overflow"); | |
| 3008 | + } | |
| 3009 | + } | |
| 3010 | + | |
| 3011 | + /** | |
| 3012 | + * Converts this {@code BigDecimal} to an {@code int}. | |
| 3013 | + * This conversion is analogous to the | |
| 3014 | + * <i>narrowing primitive conversion</i> from {@code double} to | |
| 3015 | + * {@code short} as defined in section 5.1.3 of | |
| 3016 | + * <cite>The Java™ Language Specification</cite>: | |
| 3017 | + * any fractional part of this | |
| 3018 | + * {@code BigDecimal} will be discarded, and if the resulting | |
| 3019 | + * "{@code BigInteger}" is too big to fit in an | |
| 3020 | + * {@code int}, only the low-order 32 bits are returned. | |
| 3021 | + * Note that this conversion can lose information about the | |
| 3022 | + * overall magnitude and precision of this {@code BigDecimal} | |
| 3023 | + * value as well as return a result with the opposite sign. | |
| 3024 | + * | |
| 3025 | + * @return this {@code BigDecimal} converted to an {@code int}. | |
| 3026 | + */ | |
| 3027 | + public int intValue() { | |
| 3028 | + return (intCompact != INFLATED && scale == 0) ? | |
| 3029 | + (int)intCompact : | |
| 3030 | + toBigInteger().intValue(); | |
| 3031 | + } | |
| 3032 | + | |
| 3033 | + /** | |
| 3034 | + * Converts this {@code BigDecimal} to an {@code int}, checking | |
| 3035 | + * for lost information. If this {@code BigDecimal} has a | |
| 3036 | + * nonzero fractional part or is out of the possible range for an | |
| 3037 | + * {@code int} result then an {@code ArithmeticException} is | |
| 3038 | + * thrown. | |
| 3039 | + * | |
| 3040 | + * @return this {@code BigDecimal} converted to an {@code int}. | |
| 3041 | + * @throws ArithmeticException if {@code this} has a nonzero | |
| 3042 | + * fractional part, or will not fit in an {@code int}. | |
| 3043 | + * @since 1.5 | |
| 3044 | + */ | |
| 3045 | + public int intValueExact() { | |
| 3046 | + long num; | |
| 3047 | + num = this.longValueExact(); // will check decimal part | |
| 3048 | + if ((int)num != num) | |
| 3049 | + throw new java.lang.ArithmeticException("Overflow"); | |
| 3050 | + return (int)num; | |
| 3051 | + } | |
| 3052 | + | |
| 3053 | + /** | |
| 3054 | + * Converts this {@code BigDecimal} to a {@code short}, checking | |
| 3055 | + * for lost information. If this {@code BigDecimal} has a | |
| 3056 | + * nonzero fractional part or is out of the possible range for a | |
| 3057 | + * {@code short} result then an {@code ArithmeticException} is | |
| 3058 | + * thrown. | |
| 3059 | + * | |
| 3060 | + * @return this {@code BigDecimal} converted to a {@code short}. | |
| 3061 | + * @throws ArithmeticException if {@code this} has a nonzero | |
| 3062 | + * fractional part, or will not fit in a {@code short}. | |
| 3063 | + * @since 1.5 | |
| 3064 | + */ | |
| 3065 | + public short shortValueExact() { | |
| 3066 | + long num; | |
| 3067 | + num = this.longValueExact(); // will check decimal part | |
| 3068 | + if ((short)num != num) | |
| 3069 | + throw new java.lang.ArithmeticException("Overflow"); | |
| 3070 | + return (short)num; | |
| 3071 | + } | |
| 3072 | + | |
| 3073 | + /** | |
| 3074 | + * Converts this {@code BigDecimal} to a {@code byte}, checking | |
| 3075 | + * for lost information. If this {@code BigDecimal} has a | |
| 3076 | + * nonzero fractional part or is out of the possible range for a | |
| 3077 | + * {@code byte} result then an {@code ArithmeticException} is | |
| 3078 | + * thrown. | |
| 3079 | + * | |
| 3080 | + * @return this {@code BigDecimal} converted to a {@code byte}. | |
| 3081 | + * @throws ArithmeticException if {@code this} has a nonzero | |
| 3082 | + * fractional part, or will not fit in a {@code byte}. | |
| 3083 | + * @since 1.5 | |
| 3084 | + */ | |
| 3085 | + public byte byteValueExact() { | |
| 3086 | + long num; | |
| 3087 | + num = this.longValueExact(); // will check decimal part | |
| 3088 | + if ((byte)num != num) | |
| 3089 | + throw new java.lang.ArithmeticException("Overflow"); | |
| 3090 | + return (byte)num; | |
| 3091 | + } | |
| 3092 | + | |
| 3093 | + /** | |
| 3094 | + * Converts this {@code BigDecimal} to a {@code float}. | |
| 3095 | + * This conversion is similar to the | |
| 3096 | + * <i>narrowing primitive conversion</i> from {@code double} to | |
| 3097 | + * {@code float} as defined in section 5.1.3 of | |
| 3098 | + * <cite>The Java™ Language Specification</cite>: | |
| 3099 | + * if this {@code BigDecimal} has too great a | |
| 3100 | + * magnitude to represent as a {@code float}, it will be | |
| 3101 | + * converted to {@link Float#NEGATIVE_INFINITY} or {@link | |
| 3102 | + * Float#POSITIVE_INFINITY} as appropriate. Note that even when | |
| 3103 | + * the return value is finite, this conversion can lose | |
| 3104 | + * information about the precision of the {@code BigDecimal} | |
| 3105 | + * value. | |
| 3106 | + * | |
| 3107 | + * @return this {@code BigDecimal} converted to a {@code float}. | |
| 3108 | + */ | |
| 3109 | + public float floatValue(){ | |
| 3110 | + if (scale == 0 && intCompact != INFLATED) | |
| 3111 | + return (float)intCompact; | |
| 3112 | + // Somewhat inefficient, but guaranteed to work. | |
| 3113 | + return Float.parseFloat(this.toString()); | |
| 3114 | + } | |
| 3115 | + | |
| 3116 | + /** | |
| 3117 | + * Converts this {@code BigDecimal} to a {@code double}. | |
| 3118 | + * This conversion is similar to the | |
| 3119 | + * <i>narrowing primitive conversion</i> from {@code double} to | |
| 3120 | + * {@code float} as defined in section 5.1.3 of | |
| 3121 | + * <cite>The Java™ Language Specification</cite>: | |
| 3122 | + * if this {@code BigDecimal} has too great a | |
| 3123 | + * magnitude represent as a {@code double}, it will be | |
| 3124 | + * converted to {@link Double#NEGATIVE_INFINITY} or {@link | |
| 3125 | + * Double#POSITIVE_INFINITY} as appropriate. Note that even when | |
| 3126 | + * the return value is finite, this conversion can lose | |
| 3127 | + * information about the precision of the {@code BigDecimal} | |
| 3128 | + * value. | |
| 3129 | + * | |
| 3130 | + * @return this {@code BigDecimal} converted to a {@code double}. | |
| 3131 | + */ | |
| 3132 | + public double doubleValue(){ | |
| 3133 | + if (scale == 0 && intCompact != INFLATED) | |
| 3134 | + return (double)intCompact; | |
| 3135 | + // Somewhat inefficient, but guaranteed to work. | |
| 3136 | + return Double.parseDouble(this.toString()); | |
| 3137 | + } | |
| 3138 | + | |
| 3139 | + /** | |
| 3140 | + * Returns the size of an ulp, a unit in the last place, of this | |
| 3141 | + * {@code BigDecimal}. An ulp of a nonzero {@code BigDecimal} | |
| 3142 | + * value is the positive distance between this value and the | |
| 3143 | + * {@code BigDecimal} value next larger in magnitude with the | |
| 3144 | + * same number of digits. An ulp of a zero value is numerically | |
| 3145 | + * equal to 1 with the scale of {@code this}. The result is | |
| 3146 | + * stored with the same scale as {@code this} so the result | |
| 3147 | + * for zero and nonzero values is equal to {@code [1, | |
| 3148 | + * this.scale()]}. | |
| 3149 | + * | |
| 3150 | + * @return the size of an ulp of {@code this} | |
| 3151 | + * @since 1.5 | |
| 3152 | + */ | |
| 3153 | + public BigDecimal ulp() { | |
| 3154 | + return BigDecimal.valueOf(1, this.scale()); | |
| 3155 | + } | |
| 3156 | + | |
| 3157 | + | |
| 3158 | + // Private class to build a string representation for BigDecimal object. | |
| 3159 | + // "StringBuilderHelper" is constructed as a thread local variable so it is | |
| 3160 | + // thread safe. The StringBuilder field acts as a buffer to hold the temporary | |
| 3161 | + // representation of BigDecimal. The cmpCharArray holds all the characters for | |
| 3162 | + // the compact representation of BigDecimal (except for '-' sign' if it is | |
| 3163 | + // negative) if its intCompact field is not INFLATED. It is shared by all | |
| 3164 | + // calls to toString() and its variants in that particular thread. | |
| 3165 | + static class StringBuilderHelper { | |
| 3166 | + final StringBuilder sb; // Placeholder for BigDecimal string | |
| 3167 | + final char[] cmpCharArray; // character array to place the intCompact | |
| 3168 | + | |
| 3169 | + StringBuilderHelper() { | |
| 3170 | + sb = new StringBuilder(); | |
| 3171 | + // All non negative longs can be made to fit into 19 character array. | |
| 3172 | + cmpCharArray = new char[19]; | |
| 3173 | + } | |
| 3174 | + | |
| 3175 | + // Accessors. | |
| 3176 | + StringBuilder getStringBuilder() { | |
| 3177 | + sb.setLength(0); | |
| 3178 | + return sb; | |
| 3179 | + } | |
| 3180 | + | |
| 3181 | + char[] getCompactCharArray() { | |
| 3182 | + return cmpCharArray; | |
| 3183 | + } | |
| 3184 | + | |
| 3185 | + /** | |
| 3186 | + * Places characters representing the intCompact in {@code long} into | |
| 3187 | + * cmpCharArray and returns the offset to the array where the | |
| 3188 | + * representation starts. | |
| 3189 | + * | |
| 3190 | + * @param intCompact the number to put into the cmpCharArray. | |
| 3191 | + * @return offset to the array where the representation starts. | |
| 3192 | + * Note: intCompact must be greater or equal to zero. | |
| 3193 | + */ | |
| 3194 | + int putIntCompact(long intCompact) { | |
| 3195 | + assert intCompact >= 0; | |
| 3196 | + | |
| 3197 | + long q; | |
| 3198 | + int r; | |
| 3199 | + // since we start from the least significant digit, charPos points to | |
| 3200 | + // the last character in cmpCharArray. | |
| 3201 | + int charPos = cmpCharArray.length; | |
| 3202 | + | |
| 3203 | + // Get 2 digits/iteration using longs until quotient fits into an int | |
| 3204 | + while (intCompact > Integer.MAX_VALUE) { | |
| 3205 | + q = intCompact / 100; | |
| 3206 | + r = (int)(intCompact - q * 100); | |
| 3207 | + intCompact = q; | |
| 3208 | + cmpCharArray[--charPos] = DIGIT_ONES[r]; | |
| 3209 | + cmpCharArray[--charPos] = DIGIT_TENS[r]; | |
| 3210 | + } | |
| 3211 | + | |
| 3212 | + // Get 2 digits/iteration using ints when i2 >= 100 | |
| 3213 | + int q2; | |
| 3214 | + int i2 = (int)intCompact; | |
| 3215 | + while (i2 >= 100) { | |
| 3216 | + q2 = i2 / 100; | |
| 3217 | + r = i2 - q2 * 100; | |
| 3218 | + i2 = q2; | |
| 3219 | + cmpCharArray[--charPos] = DIGIT_ONES[r]; | |
| 3220 | + cmpCharArray[--charPos] = DIGIT_TENS[r]; | |
| 3221 | + } | |
| 3222 | + | |
| 3223 | + cmpCharArray[--charPos] = DIGIT_ONES[i2]; | |
| 3224 | + if (i2 >= 10) | |
| 3225 | + cmpCharArray[--charPos] = DIGIT_TENS[i2]; | |
| 3226 | + | |
| 3227 | + return charPos; | |
| 3228 | + } | |
| 3229 | + | |
| 3230 | + final static char[] DIGIT_TENS = { | |
| 3231 | + '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', | |
| 3232 | + '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', | |
| 3233 | + '2', '2', '2', '2', '2', '2', '2', '2', '2', '2', | |
| 3234 | + '3', '3', '3', '3', '3', '3', '3', '3', '3', '3', | |
| 3235 | + '4', '4', '4', '4', '4', '4', '4', '4', '4', '4', | |
| 3236 | + '5', '5', '5', '5', '5', '5', '5', '5', '5', '5', | |
| 3237 | + '6', '6', '6', '6', '6', '6', '6', '6', '6', '6', | |
| 3238 | + '7', '7', '7', '7', '7', '7', '7', '7', '7', '7', | |
| 3239 | + '8', '8', '8', '8', '8', '8', '8', '8', '8', '8', | |
| 3240 | + '9', '9', '9', '9', '9', '9', '9', '9', '9', '9', | |
| 3241 | + }; | |
| 3242 | + | |
| 3243 | + final static char[] DIGIT_ONES = { | |
| 3244 | + '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', | |
| 3245 | + '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', | |
| 3246 | + '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', | |
| 3247 | + '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', | |
| 3248 | + '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', | |
| 3249 | + '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', | |
| 3250 | + '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', | |
| 3251 | + '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', | |
| 3252 | + '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', | |
| 3253 | + '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', | |
| 3254 | + }; | |
| 3255 | + } | |
| 3256 | + | |
| 3257 | + /** | |
| 3258 | + * Lay out this {@code BigDecimal} into a {@code char[]} array. | |
| 3259 | + * The Java 1.2 equivalent to this was called {@code getValueString}. | |
| 3260 | + * | |
| 3261 | + * @param sci {@code true} for Scientific exponential notation; | |
| 3262 | + * {@code false} for Engineering | |
| 3263 | + * @return string with canonical string representation of this | |
| 3264 | + * {@code BigDecimal} | |
| 3265 | + */ | |
| 3266 | + private String layoutChars(boolean sci) { | |
| 3267 | + if (scale == 0) // zero scale is trivial | |
| 3268 | + return (intCompact != INFLATED) ? | |
| 3269 | + Long.toString(intCompact): | |
| 3270 | + intVal.toString(); | |
| 3271 | + | |
| 3272 | + StringBuilderHelper sbHelper = threadLocalStringBuilderHelper.get(); | |
| 3273 | + char[] coeff; | |
| 3274 | + int offset; // offset is the starting index for coeff array | |
| 3275 | + // Get the significand as an absolute value | |
| 3276 | + if (intCompact != INFLATED) { | |
| 3277 | + offset = sbHelper.putIntCompact(Math.abs(intCompact)); | |
| 3278 | + coeff = sbHelper.getCompactCharArray(); | |
| 3279 | + } else { | |
| 3280 | + offset = 0; | |
| 3281 | + coeff = intVal.abs().toString().toCharArray(); | |
| 3282 | + } | |
| 3283 | + | |
| 3284 | + // Construct a buffer, with sufficient capacity for all cases. | |
| 3285 | + // If E-notation is needed, length will be: +1 if negative, +1 | |
| 3286 | + // if '.' needed, +2 for "E+", + up to 10 for adjusted exponent. | |
| 3287 | + // Otherwise it could have +1 if negative, plus leading "0.00000" | |
| 3288 | + StringBuilder buf = sbHelper.getStringBuilder(); | |
| 3289 | + if (signum() < 0) // prefix '-' if negative | |
| 3290 | + buf.append('-'); | |
| 3291 | + int coeffLen = coeff.length - offset; | |
| 3292 | + long adjusted = -(long)scale + (coeffLen -1); | |
| 3293 | + if ((scale >= 0) && (adjusted >= -6)) { // plain number | |
| 3294 | + int pad = scale - coeffLen; // count of padding zeros | |
| 3295 | + if (pad >= 0) { // 0.xxx form | |
| 3296 | + buf.append('0'); | |
| 3297 | + buf.append('.'); | |
| 3298 | + for (; pad>0; pad--) { | |
| 3299 | + buf.append('0'); | |
| 3300 | + } | |
| 3301 | + buf.append(coeff, offset, coeffLen); | |
| 3302 | + } else { // xx.xx form | |
| 3303 | + buf.append(coeff, offset, -pad); | |
| 3304 | + buf.append('.'); | |
| 3305 | + buf.append(coeff, -pad + offset, scale); | |
| 3306 | + } | |
| 3307 | + } else { // E-notation is needed | |
| 3308 | + if (sci) { // Scientific notation | |
| 3309 | + buf.append(coeff[offset]); // first character | |
| 3310 | + if (coeffLen > 1) { // more to come | |
| 3311 | + buf.append('.'); | |
| 3312 | + buf.append(coeff, offset + 1, coeffLen - 1); | |
| 3313 | + } | |
| 3314 | + } else { // Engineering notation | |
| 3315 | + int sig = (int)(adjusted % 3); | |
| 3316 | + if (sig < 0) | |
| 3317 | + sig += 3; // [adjusted was negative] | |
| 3318 | + adjusted -= sig; // now a multiple of 3 | |
| 3319 | + sig++; | |
| 3320 | + if (signum() == 0) { | |
| 3321 | + switch (sig) { | |
| 3322 | + case 1: | |
| 3323 | + buf.append('0'); // exponent is a multiple of three | |
| 3324 | + break; | |
| 3325 | + case 2: | |
| 3326 | + buf.append("0.00"); | |
| 3327 | + adjusted += 3; | |
| 3328 | + break; | |
| 3329 | + case 3: | |
| 3330 | + buf.append("0.0"); | |
| 3331 | + adjusted += 3; | |
| 3332 | + break; | |
| 3333 | + default: | |
| 3334 | + throw new AssertionError("Unexpected sig value " + sig); | |
| 3335 | + } | |
| 3336 | + } else if (sig >= coeffLen) { // significand all in integer | |
| 3337 | + buf.append(coeff, offset, coeffLen); | |
| 3338 | + // may need some zeros, too | |
| 3339 | + for (int i = sig - coeffLen; i > 0; i--) | |
| 3340 | + buf.append('0'); | |
| 3341 | + } else { // xx.xxE form | |
| 3342 | + buf.append(coeff, offset, sig); | |
| 3343 | + buf.append('.'); | |
| 3344 | + buf.append(coeff, offset + sig, coeffLen - sig); | |
| 3345 | + } | |
| 3346 | + } | |
| 3347 | + if (adjusted != 0) { // [!sci could have made 0] | |
| 3348 | + buf.append('E'); | |
| 3349 | + if (adjusted > 0) // force sign for positive | |
| 3350 | + buf.append('+'); | |
| 3351 | + buf.append(adjusted); | |
| 3352 | + } | |
| 3353 | + } | |
| 3354 | + return buf.toString(); | |
| 3355 | + } | |
| 3356 | + | |
| 3357 | + /** | |
| 3358 | + * Return 10 to the power n, as a {@code BigInteger}. | |
| 3359 | + * | |
| 3360 | + * @param n the power of ten to be returned (>=0) | |
| 3361 | + * @return a {@code BigInteger} with the value (10<sup>n</sup>) | |
| 3362 | + */ | |
| 3363 | + private static BigInteger bigTenToThe(int n) { | |
| 3364 | + if (n < 0) | |
| 3365 | + return BigInteger.ZERO; | |
| 3366 | + | |
| 3367 | + if (n < BIG_TEN_POWERS_TABLE_MAX) { | |
| 3368 | + BigInteger[] pows = BIG_TEN_POWERS_TABLE; | |
| 3369 | + if (n < pows.length) | |
| 3370 | + return pows[n]; | |
| 3371 | + else | |
| 3372 | + return expandBigIntegerTenPowers(n); | |
| 3373 | + } | |
| 3374 | + // BigInteger.pow is slow, so make 10**n by constructing a | |
| 3375 | + // BigInteger from a character string (still not very fast) | |
| 3376 | + char tenpow[] = new char[n + 1]; | |
| 3377 | + tenpow[0] = '1'; | |
| 3378 | + for (int i = 1; i <= n; i++) | |
| 3379 | + tenpow[i] = '0'; | |
| 3380 | + return new BigInteger(tenpow); | |
| 3381 | + } | |
| 3382 | + | |
| 3383 | + /** | |
| 3384 | + * Expand the BIG_TEN_POWERS_TABLE array to contain at least 10**n. | |
| 3385 | + * | |
| 3386 | + * @param n the power of ten to be returned (>=0) | |
| 3387 | + * @return a {@code BigDecimal} with the value (10<sup>n</sup>) and | |
| 3388 | + * in the meantime, the BIG_TEN_POWERS_TABLE array gets | |
| 3389 | + * expanded to the size greater than n. | |
| 3390 | + */ | |
| 3391 | + private static BigInteger expandBigIntegerTenPowers(int n) { | |
| 3392 | + synchronized(BigDecimal.class) { | |
| 3393 | + BigInteger[] pows = BIG_TEN_POWERS_TABLE; | |
| 3394 | + int curLen = pows.length; | |
| 3395 | + // The following comparison and the above synchronized statement is | |
| 3396 | + // to prevent multiple threads from expanding the same array. | |
| 3397 | + if (curLen <= n) { | |
| 3398 | + int newLen = curLen << 1; | |
| 3399 | + while (newLen <= n) | |
| 3400 | + newLen <<= 1; | |
| 3401 | + pows = Arrays.copyOf(pows, newLen); | |
| 3402 | + for (int i = curLen; i < newLen; i++) | |
| 3403 | + pows[i] = pows[i - 1].multiply(BigInteger.TEN); | |
| 3404 | + // Based on the following facts: | |
| 3405 | + // 1. pows is a private local varible; | |
| 3406 | + // 2. the following store is a volatile store. | |
| 3407 | + // the newly created array elements can be safely published. | |
| 3408 | + BIG_TEN_POWERS_TABLE = pows; | |
| 3409 | + } | |
| 3410 | + return pows[n]; | |
| 3411 | + } | |
| 3412 | + } | |
| 3413 | + | |
| 3414 | + private static final long[] LONG_TEN_POWERS_TABLE = { | |
| 3415 | + 1, // 0 / 10^0 | |
| 3416 | + 10, // 1 / 10^1 | |
| 3417 | + 100, // 2 / 10^2 | |
| 3418 | + 1000, // 3 / 10^3 | |
| 3419 | + 10000, // 4 / 10^4 | |
| 3420 | + 100000, // 5 / 10^5 | |
| 3421 | + 1000000, // 6 / 10^6 | |
| 3422 | + 10000000, // 7 / 10^7 | |
| 3423 | + 100000000, // 8 / 10^8 | |
| 3424 | + 1000000000, // 9 / 10^9 | |
| 3425 | + 10000000000L, // 10 / 10^10 | |
| 3426 | + 100000000000L, // 11 / 10^11 | |
| 3427 | + 1000000000000L, // 12 / 10^12 | |
| 3428 | + 10000000000000L, // 13 / 10^13 | |
| 3429 | + 100000000000000L, // 14 / 10^14 | |
| 3430 | + 1000000000000000L, // 15 / 10^15 | |
| 3431 | + 10000000000000000L, // 16 / 10^16 | |
| 3432 | + 100000000000000000L, // 17 / 10^17 | |
| 3433 | + 1000000000000000000L // 18 / 10^18 | |
| 3434 | + }; | |
| 3435 | + | |
| 3436 | + private static volatile BigInteger BIG_TEN_POWERS_TABLE[] = {BigInteger.ONE, | |
| 3437 | + BigInteger.valueOf(10), BigInteger.valueOf(100), | |
| 3438 | + BigInteger.valueOf(1000), BigInteger.valueOf(10000), | |
| 3439 | + BigInteger.valueOf(100000), BigInteger.valueOf(1000000), | |
| 3440 | + BigInteger.valueOf(10000000), BigInteger.valueOf(100000000), | |
| 3441 | + BigInteger.valueOf(1000000000), | |
| 3442 | + BigInteger.valueOf(10000000000L), | |
| 3443 | + BigInteger.valueOf(100000000000L), | |
| 3444 | + BigInteger.valueOf(1000000000000L), | |
| 3445 | + BigInteger.valueOf(10000000000000L), | |
| 3446 | + BigInteger.valueOf(100000000000000L), | |
| 3447 | + BigInteger.valueOf(1000000000000000L), | |
| 3448 | + BigInteger.valueOf(10000000000000000L), | |
| 3449 | + BigInteger.valueOf(100000000000000000L), | |
| 3450 | + BigInteger.valueOf(1000000000000000000L) | |
| 3451 | + }; | |
| 3452 | + | |
| 3453 | + private static final int BIG_TEN_POWERS_TABLE_INITLEN = | |
| 3454 | + BIG_TEN_POWERS_TABLE.length; | |
| 3455 | + private static final int BIG_TEN_POWERS_TABLE_MAX = | |
| 3456 | + 16 * BIG_TEN_POWERS_TABLE_INITLEN; | |
| 3457 | + | |
| 3458 | + private static final long THRESHOLDS_TABLE[] = { | |
| 3459 | + Long.MAX_VALUE, // 0 | |
| 3460 | + Long.MAX_VALUE/10L, // 1 | |
| 3461 | + Long.MAX_VALUE/100L, // 2 | |
| 3462 | + Long.MAX_VALUE/1000L, // 3 | |
| 3463 | + Long.MAX_VALUE/10000L, // 4 | |
| 3464 | + Long.MAX_VALUE/100000L, // 5 | |
| 3465 | + Long.MAX_VALUE/1000000L, // 6 | |
| 3466 | + Long.MAX_VALUE/10000000L, // 7 | |
| 3467 | + Long.MAX_VALUE/100000000L, // 8 | |
| 3468 | + Long.MAX_VALUE/1000000000L, // 9 | |
| 3469 | + Long.MAX_VALUE/10000000000L, // 10 | |
| 3470 | + Long.MAX_VALUE/100000000000L, // 11 | |
| 3471 | + Long.MAX_VALUE/1000000000000L, // 12 | |
| 3472 | + Long.MAX_VALUE/10000000000000L, // 13 | |
| 3473 | + Long.MAX_VALUE/100000000000000L, // 14 | |
| 3474 | + Long.MAX_VALUE/1000000000000000L, // 15 | |
| 3475 | + Long.MAX_VALUE/10000000000000000L, // 16 | |
| 3476 | + Long.MAX_VALUE/100000000000000000L, // 17 | |
| 3477 | + Long.MAX_VALUE/1000000000000000000L // 18 | |
| 3478 | + }; | |
| 3479 | + | |
| 3480 | + /** | |
| 3481 | + * Compute val * 10 ^ n; return this product if it is | |
| 3482 | + * representable as a long, INFLATED otherwise. | |
| 3483 | + */ | |
| 3484 | + private static long longMultiplyPowerTen(long val, int n) { | |
| 3485 | + if (val == 0 || n <= 0) | |
| 3486 | + return val; | |
| 3487 | + long[] tab = LONG_TEN_POWERS_TABLE; | |
| 3488 | + long[] bounds = THRESHOLDS_TABLE; | |
| 3489 | + if (n < tab.length && n < bounds.length) { | |
| 3490 | + long tenpower = tab[n]; | |
| 3491 | + if (val == 1) | |
| 3492 | + return tenpower; | |
| 3493 | + if (Math.abs(val) <= bounds[n]) | |
| 3494 | + return val * tenpower; | |
| 3495 | + } | |
| 3496 | + return INFLATED; | |
| 3497 | + } | |
| 3498 | + | |
| 3499 | + /** | |
| 3500 | + * Compute this * 10 ^ n. | |
| 3501 | + * Needed mainly to allow special casing to trap zero value | |
| 3502 | + */ | |
| 3503 | + private BigInteger bigMultiplyPowerTen(int n) { | |
| 3504 | + if (n <= 0) | |
| 3505 | + return this.inflate(); | |
| 3506 | + | |
| 3507 | + if (intCompact != INFLATED) | |
| 3508 | + return bigTenToThe(n).multiply(intCompact); | |
| 3509 | + else | |
| 3510 | + return intVal.multiply(bigTenToThe(n)); | |
| 3511 | + } | |
| 3512 | + | |
| 3513 | + /** | |
| 3514 | + * Assign appropriate BigInteger to intVal field if intVal is | |
| 3515 | + * null, i.e. the compact representation is in use. | |
| 3516 | + */ | |
| 3517 | + private BigInteger inflate() { | |
| 3518 | + if (intVal == null) | |
| 3519 | + intVal = BigInteger.valueOf(intCompact); | |
| 3520 | + return intVal; | |
| 3521 | + } | |
| 3522 | + | |
| 3523 | + /** | |
| 3524 | + * Match the scales of two {@code BigDecimal}s to align their | |
| 3525 | + * least significant digits. | |
| 3526 | + * | |
| 3527 | + * <p>If the scales of val[0] and val[1] differ, rescale | |
| 3528 | + * (non-destructively) the lower-scaled {@code BigDecimal} so | |
| 3529 | + * they match. That is, the lower-scaled reference will be | |
| 3530 | + * replaced by a reference to a new object with the same scale as | |
| 3531 | + * the other {@code BigDecimal}. | |
| 3532 | + * | |
| 3533 | + * @param val array of two elements referring to the two | |
| 3534 | + * {@code BigDecimal}s to be aligned. | |
| 3535 | + */ | |
| 3536 | + private static void matchScale(BigDecimal[] val) { | |
| 3537 | + if (val[0].scale == val[1].scale) { | |
| 3538 | + return; | |
| 3539 | + } else if (val[0].scale < val[1].scale) { | |
| 3540 | + val[0] = val[0].setScale(val[1].scale, ROUND_UNNECESSARY); | |
| 3541 | + } else if (val[1].scale < val[0].scale) { | |
| 3542 | + val[1] = val[1].setScale(val[0].scale, ROUND_UNNECESSARY); | |
| 3543 | + } | |
| 3544 | + } | |
| 3545 | + | |
| 3546 | + /** | |
| 3547 | + * Reconstitute the {@code BigDecimal} instance from a stream (that is, | |
| 3548 | + * deserialize it). | |
| 3549 | + * | |
| 3550 | + * @param s the stream being read. | |
| 3551 | + */ | |
| 3552 | + private void readObject(java.io.ObjectInputStream s) | |
| 3553 | + throws java.io.IOException, ClassNotFoundException { | |
| 3554 | + // Read in all fields | |
| 3555 | + s.defaultReadObject(); | |
| 3556 | + // validate possibly bad fields | |
| 3557 | + if (intVal == null) { | |
| 3558 | + String message = "BigDecimal: null intVal in stream"; | |
| 3559 | + throw new java.io.StreamCorruptedException(message); | |
| 3560 | + // [all values of scale are now allowed] | |
| 3561 | + } | |
| 3562 | + intCompact = compactValFor(intVal); | |
| 3563 | + } | |
| 3564 | + | |
| 3565 | + /** | |
| 3566 | + * Serialize this {@code BigDecimal} to the stream in question | |
| 3567 | + * | |
| 3568 | + * @param s the stream to serialize to. | |
| 3569 | + */ | |
| 3570 | + private void writeObject(java.io.ObjectOutputStream s) | |
| 3571 | + throws java.io.IOException { | |
| 3572 | + // Must inflate to maintain compatible serial form. | |
| 3573 | + this.inflate(); | |
| 3574 | + | |
| 3575 | + // Write proper fields | |
| 3576 | + s.defaultWriteObject(); | |
| 3577 | + } | |
| 3578 | + | |
| 3579 | + | |
| 3580 | + /** | |
| 3581 | + * Returns the length of the absolute value of a {@code long}, in decimal | |
| 3582 | + * digits. | |
| 3583 | + * | |
| 3584 | + * @param x the {@code long} | |
| 3585 | + * @return the length of the unscaled value, in deciaml digits. | |
| 3586 | + */ | |
| 3587 | + private static int longDigitLength(long x) { | |
| 3588 | + /* | |
| 3589 | + * As described in "Bit Twiddling Hacks" by Sean Anderson, | |
| 3590 | + * (http://graphics.stanford.edu/~seander/bithacks.html) | |
| 3591 | + * integer log 10 of x is within 1 of | |
| 3592 | + * (1233/4096)* (1 + integer log 2 of x). | |
| 3593 | + * The fraction 1233/4096 approximates log10(2). So we first | |
| 3594 | + * do a version of log2 (a variant of Long class with | |
| 3595 | + * pre-checks and opposite directionality) and then scale and | |
| 3596 | + * check against powers table. This is a little simpler in | |
| 3597 | + * present context than the version in Hacker's Delight sec | |
| 3598 | + * 11-4. Adding one to bit length allows comparing downward | |
| 3599 | + * from the LONG_TEN_POWERS_TABLE that we need anyway. | |
| 3600 | + */ | |
| 3601 | + assert x != INFLATED; | |
| 3602 | + if (x < 0) | |
| 3603 | + x = -x; | |
| 3604 | + if (x < 10) // must screen for 0, might as well 10 | |
| 3605 | + return 1; | |
| 3606 | + int n = 64; // not 63, to avoid needing to add 1 later | |
| 3607 | + int y = (int)(x >>> 32); | |
| 3608 | + if (y == 0) { n -= 32; y = (int)x; } | |
| 3609 | + if (y >>> 16 == 0) { n -= 16; y <<= 16; } | |
| 3610 | + if (y >>> 24 == 0) { n -= 8; y <<= 8; } | |
| 3611 | + if (y >>> 28 == 0) { n -= 4; y <<= 4; } | |
| 3612 | + if (y >>> 30 == 0) { n -= 2; y <<= 2; } | |
| 3613 | + int r = (((y >>> 31) + n) * 1233) >>> 12; | |
| 3614 | + long[] tab = LONG_TEN_POWERS_TABLE; | |
| 3615 | + // if r >= length, must have max possible digits for long | |
| 3616 | + return (r >= tab.length || x < tab[r])? r : r+1; | |
| 3617 | + } | |
| 3618 | + | |
| 3619 | + /** | |
| 3620 | + * Returns the length of the absolute value of a BigInteger, in | |
| 3621 | + * decimal digits. | |
| 3622 | + * | |
| 3623 | + * @param b the BigInteger | |
| 3624 | + * @return the length of the unscaled value, in decimal digits | |
| 3625 | + */ | |
| 3626 | + private static int bigDigitLength(BigInteger b) { | |
| 3627 | + /* | |
| 3628 | + * Same idea as the long version, but we need a better | |
| 3629 | + * approximation of log10(2). Using 646456993/2^31 | |
| 3630 | + * is accurate up to max possible reported bitLength. | |
| 3631 | + */ | |
| 3632 | + if (b.signum == 0) | |
| 3633 | + return 1; | |
| 3634 | + int r = (int)((((long)b.bitLength() + 1) * 646456993) >>> 31); | |
| 3635 | + return b.compareMagnitude(bigTenToThe(r)) < 0? r : r+1; | |
| 3636 | + } | |
| 3637 | + | |
| 3638 | + | |
| 3639 | + /** | |
| 3640 | + * Remove insignificant trailing zeros from this | |
| 3641 | + * {@code BigDecimal} until the preferred scale is reached or no | |
| 3642 | + * more zeros can be removed. If the preferred scale is less than | |
| 3643 | + * Integer.MIN_VALUE, all the trailing zeros will be removed. | |
| 3644 | + * | |
| 3645 | + * {@code BigInteger} assistance could help, here? | |
| 3646 | + * | |
| 3647 | + * <p>WARNING: This method should only be called on new objects as | |
| 3648 | + * it mutates the value fields. | |
| 3649 | + * | |
| 3650 | + * @return this {@code BigDecimal} with a scale possibly reduced | |
| 3651 | + * to be closed to the preferred scale. | |
| 3652 | + */ | |
| 3653 | + private BigDecimal stripZerosToMatchScale(long preferredScale) { | |
| 3654 | + this.inflate(); | |
| 3655 | + BigInteger qr[]; // quotient-remainder pair | |
| 3656 | + while ( intVal.compareMagnitude(BigInteger.TEN) >= 0 && | |
| 3657 | + scale > preferredScale) { | |
| 3658 | + if (intVal.testBit(0)) | |
| 3659 | + break; // odd number cannot end in 0 | |
| 3660 | + qr = intVal.divideAndRemainder(BigInteger.TEN); | |
| 3661 | + if (qr[1].signum() != 0) | |
| 3662 | + break; // non-0 remainder | |
| 3663 | + intVal=qr[0]; | |
| 3664 | + scale = checkScale((long)scale-1); // could Overflow | |
| 3665 | + if (precision > 0) // adjust precision if known | |
| 3666 | + precision--; | |
| 3667 | + } | |
| 3668 | + if (intVal != null) | |
| 3669 | + intCompact = compactValFor(intVal); | |
| 3670 | + return this; | |
| 3671 | + } | |
| 3672 | + | |
| 3673 | + /** | |
| 3674 | + * Check a scale for Underflow or Overflow. If this BigDecimal is | |
| 3675 | + * nonzero, throw an exception if the scale is outof range. If this | |
| 3676 | + * is zero, saturate the scale to the extreme value of the right | |
| 3677 | + * sign if the scale is out of range. | |
| 3678 | + * | |
| 3679 | + * @param val The new scale. | |
| 3680 | + * @throws ArithmeticException (overflow or underflow) if the new | |
| 3681 | + * scale is out of range. | |
| 3682 | + * @return validated scale as an int. | |
| 3683 | + */ | |
| 3684 | + private int checkScale(long val) { | |
| 3685 | + int asInt = (int)val; | |
| 3686 | + if (asInt != val) { | |
| 3687 | + asInt = val>Integer.MAX_VALUE ? Integer.MAX_VALUE : Integer.MIN_VALUE; | |
| 3688 | + BigInteger b; | |
| 3689 | + if (intCompact != 0 && | |
| 3690 | + ((b = intVal) == null || b.signum() != 0)) | |
| 3691 | + throw new ArithmeticException(asInt>0 ? "Underflow":"Overflow"); | |
| 3692 | + } | |
| 3693 | + return asInt; | |
| 3694 | + } | |
| 3695 | + | |
| 3696 | + /** | |
| 3697 | + * Round an operand; used only if digits > 0. Does not change | |
| 3698 | + * {@code this}; if rounding is needed a new {@code BigDecimal} | |
| 3699 | + * is created and returned. | |
| 3700 | + * | |
| 3701 | + * @param mc the context to use. | |
| 3702 | + * @throws ArithmeticException if the result is inexact but the | |
| 3703 | + * rounding mode is {@code UNNECESSARY}. | |
| 3704 | + */ | |
| 3705 | + private BigDecimal roundOp(MathContext mc) { | |
| 3706 | + BigDecimal rounded = doRound(this, mc); | |
| 3707 | + return rounded; | |
| 3708 | + } | |
| 3709 | + | |
| 3710 | + /** Round this BigDecimal according to the MathContext settings; | |
| 3711 | + * used only if precision {@literal >} 0. | |
| 3712 | + * | |
| 3713 | + * <p>WARNING: This method should only be called on new objects as | |
| 3714 | + * it mutates the value fields. | |
| 3715 | + * | |
| 3716 | + * @param mc the context to use. | |
| 3717 | + * @throws ArithmeticException if the rounding mode is | |
| 3718 | + * {@code RoundingMode.UNNECESSARY} and the | |
| 3719 | + * {@code BigDecimal} operation would require rounding. | |
| 3720 | + */ | |
| 3721 | + private void roundThis(MathContext mc) { | |
| 3722 | + BigDecimal rounded = doRound(this, mc); | |
| 3723 | + if (rounded == this) // wasn't rounded | |
| 3724 | + return; | |
| 3725 | + this.intVal = rounded.intVal; | |
| 3726 | + this.intCompact = rounded.intCompact; | |
| 3727 | + this.scale = rounded.scale; | |
| 3728 | + this.precision = rounded.precision; | |
| 3729 | + } | |
| 3730 | + | |
| 3731 | + /** | |
| 3732 | + * Returns a {@code BigDecimal} rounded according to the | |
| 3733 | + * MathContext settings; used only if {@code mc.precision > 0}. | |
| 3734 | + * Does not change {@code this}; if rounding is needed a new | |
| 3735 | + * {@code BigDecimal} is created and returned. | |
| 3736 | + * | |
| 3737 | + * @param mc the context to use. | |
| 3738 | + * @return a {@code BigDecimal} rounded according to the MathContext | |
| 3739 | + * settings. May return this, if no rounding needed. | |
| 3740 | + * @throws ArithmeticException if the rounding mode is | |
| 3741 | + * {@code RoundingMode.UNNECESSARY} and the | |
| 3742 | + * result is inexact. | |
| 3743 | + */ | |
| 3744 | + private static BigDecimal doRound(BigDecimal d, MathContext mc) { | |
| 3745 | + int mcp = mc.precision; | |
| 3746 | + int drop; | |
| 3747 | + // This might (rarely) iterate to cover the 999=>1000 case | |
| 3748 | + while ((drop = d.precision() - mcp) > 0) { | |
| 3749 | + int newScale = d.checkScale((long)d.scale - drop); | |
| 3750 | + int mode = mc.roundingMode.oldMode; | |
| 3751 | + if (drop < LONG_TEN_POWERS_TABLE.length) | |
| 3752 | + d = divideAndRound(d.intCompact, d.intVal, | |
| 3753 | + LONG_TEN_POWERS_TABLE[drop], null, | |
| 3754 | + newScale, mode, newScale); | |
| 3755 | + else | |
| 3756 | + d = divideAndRound(d.intCompact, d.intVal, | |
| 3757 | + INFLATED, bigTenToThe(drop), | |
| 3758 | + newScale, mode, newScale); | |
| 3759 | + } | |
| 3760 | + return d; | |
| 3761 | + } | |
| 3762 | + | |
| 3763 | + /** | |
| 3764 | + * Returns the compact value for given {@code BigInteger}, or | |
| 3765 | + * INFLATED if too big. Relies on internal representation of | |
| 3766 | + * {@code BigInteger}. | |
| 3767 | + */ | |
| 3768 | + private static long compactValFor(BigInteger b) { | |
| 3769 | + int[] m = b.mag; | |
| 3770 | + int len = m.length; | |
| 3771 | + if (len == 0) | |
| 3772 | + return 0; | |
| 3773 | + int d = m[0]; | |
| 3774 | + if (len > 2 || (len == 2 && d < 0)) | |
| 3775 | + return INFLATED; | |
| 3776 | + | |
| 3777 | + long u = (len == 2)? | |
| 3778 | + (((long) m[1] & LONG_MASK) + (((long)d) << 32)) : | |
| 3779 | + (((long)d) & LONG_MASK); | |
| 3780 | + return (b.signum < 0)? -u : u; | |
| 3781 | + } | |
| 3782 | + | |
| 3783 | + private static int longCompareMagnitude(long x, long y) { | |
| 3784 | + if (x < 0) | |
| 3785 | + x = -x; | |
| 3786 | + if (y < 0) | |
| 3787 | + y = -y; | |
| 3788 | + return (x < y) ? -1 : ((x == y) ? 0 : 1); | |
| 3789 | + } | |
| 3790 | + | |
| 3791 | + private static int saturateLong(long s) { | |
| 3792 | + int i = (int)s; | |
| 3793 | + return (s == i) ? i : (s < 0 ? Integer.MIN_VALUE : Integer.MAX_VALUE); | |
| 3794 | + } | |
| 3795 | + | |
| 3796 | + /* | |
| 3797 | + * Internal printing routine | |
| 3798 | + */ | |
| 3799 | + private static void print(String name, BigDecimal bd) { | |
| 3800 | + System.err.format("%s:\tintCompact %d\tintVal %d\tscale %d\tprecision %d%n", | |
| 3801 | + name, | |
| 3802 | + bd.intCompact, | |
| 3803 | + bd.intVal, | |
| 3804 | + bd.scale, | |
| 3805 | + bd.precision); | |
| 3806 | + } | |
| 3807 | + | |
| 3808 | + /** | |
| 3809 | + * Check internal invariants of this BigDecimal. These invariants | |
| 3810 | + * include: | |
| 3811 | + * | |
| 3812 | + * <ul> | |
| 3813 | + * | |
| 3814 | + * <li>The object must be initialized; either intCompact must not be | |
| 3815 | + * INFLATED or intVal is non-null. Both of these conditions may | |
| 3816 | + * be true. | |
| 3817 | + * | |
| 3818 | + * <li>If both intCompact and intVal and set, their values must be | |
| 3819 | + * consistent. | |
| 3820 | + * | |
| 3821 | + * <li>If precision is nonzero, it must have the right value. | |
| 3822 | + * </ul> | |
| 3823 | + * | |
| 3824 | + * Note: Since this is an audit method, we are not supposed to change the | |
| 3825 | + * state of this BigDecimal object. | |
| 3826 | + */ | |
| 3827 | + private BigDecimal audit() { | |
| 3828 | + if (intCompact == INFLATED) { | |
| 3829 | + if (intVal == null) { | |
| 3830 | + print("audit", this); | |
| 3831 | + throw new AssertionError("null intVal"); | |
| 3832 | + } | |
| 3833 | + // Check precision | |
| 3834 | + if (precision > 0 && precision != bigDigitLength(intVal)) { | |
| 3835 | + print("audit", this); | |
| 3836 | + throw new AssertionError("precision mismatch"); | |
| 3837 | + } | |
| 3838 | + } else { | |
| 3839 | + if (intVal != null) { | |
| 3840 | + long val = intVal.longValue(); | |
| 3841 | + if (val != intCompact) { | |
| 3842 | + print("audit", this); | |
| 3843 | + throw new AssertionError("Inconsistent state, intCompact=" + | |
| 3844 | + intCompact + "\t intVal=" + val); | |
| 3845 | + } | |
| 3846 | + } | |
| 3847 | + // Check precision | |
| 3848 | + if (precision > 0 && precision != longDigitLength(intCompact)) { | |
| 3849 | + print("audit", this); | |
| 3850 | + throw new AssertionError("precision mismatch"); | |
| 3851 | + } | |
| 3852 | + } | |
| 3853 | + return this; | |
| 3854 | + } | |
| 3855 | +} | |
Binary file not shown.
| @@ -0,0 +1,3186 @@ | ||
| 1 | +/* | |
| 2 | + * Copyright (c) 1996, 2007, Oracle and/or its affiliates. All rights reserved. | |
| 3 | + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. | |
| 4 | + * | |
| 5 | + * This code is free software; you can redistribute it and/or modify it | |
| 6 | + * under the terms of the GNU General Public License version 2 only, as | |
| 7 | + * published by the Free Software Foundation. Oracle designates this | |
| 8 | + * particular file as subject to the "Classpath" exception as provided | |
| 9 | + * by Oracle in the LICENSE file that accompanied this code. | |
| 10 | + * | |
| 11 | + * This code is distributed in the hope that it will be useful, but WITHOUT | |
| 12 | + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or | |
| 13 | + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License | |
| 14 | + * version 2 for more details (a copy is included in the LICENSE file that | |
| 15 | + * accompanied this code). | |
| 16 | + * | |
| 17 | + * You should have received a copy of the GNU General Public License version | |
| 18 | + * 2 along with this work; if not, write to the Free Software Foundation, | |
| 19 | + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. | |
| 20 | + * | |
| 21 | + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA | |
| 22 | + * or visit www.oracle.com if you need additional information or have any | |
| 23 | + * questions. | |
| 24 | + */ | |
| 25 | + | |
| 26 | +/* | |
| 27 | + * Portions Copyright (c) 1995 Colin Plumb. All rights reserved. | |
| 28 | + */ | |
| 29 | + | |
| 30 | +package java.math; | |
| 31 | + | |
| 32 | +import java.util.Random; | |
| 33 | +import java.io.*; | |
| 34 | + | |
| 35 | +/** | |
| 36 | + * Immutable arbitrary-precision integers. All operations behave as if | |
| 37 | + * BigIntegers were represented in two's-complement notation (like Java's | |
| 38 | + * primitive integer types). BigInteger provides analogues to all of Java's | |
| 39 | + * primitive integer operators, and all relevant methods from java.lang.Math. | |
| 40 | + * Additionally, BigInteger provides operations for modular arithmetic, GCD | |
| 41 | + * calculation, primality testing, prime generation, bit manipulation, | |
| 42 | + * and a few other miscellaneous operations. | |
| 43 | + * | |
| 44 | + * <p>Semantics of arithmetic operations exactly mimic those of Java's integer | |
| 45 | + * arithmetic operators, as defined in <i>The Java Language Specification</i>. | |
| 46 | + * For example, division by zero throws an {@code ArithmeticException}, and | |
| 47 | + * division of a negative by a positive yields a negative (or zero) remainder. | |
| 48 | + * All of the details in the Spec concerning overflow are ignored, as | |
| 49 | + * BigIntegers are made as large as necessary to accommodate the results of an | |
| 50 | + * operation. | |
| 51 | + * | |
| 52 | + * <p>Semantics of shift operations extend those of Java's shift operators | |
| 53 | + * to allow for negative shift distances. A right-shift with a negative | |
| 54 | + * shift distance results in a left shift, and vice-versa. The unsigned | |
| 55 | + * right shift operator ({@code >>>}) is omitted, as this operation makes | |
| 56 | + * little sense in combination with the "infinite word size" abstraction | |
| 57 | + * provided by this class. | |
| 58 | + * | |
| 59 | + * <p>Semantics of bitwise logical operations exactly mimic those of Java's | |
| 60 | + * bitwise integer operators. The binary operators ({@code and}, | |
| 61 | + * {@code or}, {@code xor}) implicitly perform sign extension on the shorter | |
| 62 | + * of the two operands prior to performing the operation. | |
| 63 | + * | |
| 64 | + * <p>Comparison operations perform signed integer comparisons, analogous to | |
| 65 | + * those performed by Java's relational and equality operators. | |
| 66 | + * | |
| 67 | + * <p>Modular arithmetic operations are provided to compute residues, perform | |
| 68 | + * exponentiation, and compute multiplicative inverses. These methods always | |
| 69 | + * return a non-negative result, between {@code 0} and {@code (modulus - 1)}, | |
| 70 | + * inclusive. | |
| 71 | + * | |
| 72 | + * <p>Bit operations operate on a single bit of the two's-complement | |
| 73 | + * representation of their operand. If necessary, the operand is sign- | |
| 74 | + * extended so that it contains the designated bit. None of the single-bit | |
| 75 | + * operations can produce a BigInteger with a different sign from the | |
| 76 | + * BigInteger being operated on, as they affect only a single bit, and the | |
| 77 | + * "infinite word size" abstraction provided by this class ensures that there | |
| 78 | + * are infinitely many "virtual sign bits" preceding each BigInteger. | |
| 79 | + * | |
| 80 | + * <p>For the sake of brevity and clarity, pseudo-code is used throughout the | |
| 81 | + * descriptions of BigInteger methods. The pseudo-code expression | |
| 82 | + * {@code (i + j)} is shorthand for "a BigInteger whose value is | |
| 83 | + * that of the BigInteger {@code i} plus that of the BigInteger {@code j}." | |
| 84 | + * The pseudo-code expression {@code (i == j)} is shorthand for | |
| 85 | + * "{@code true} if and only if the BigInteger {@code i} represents the same | |
| 86 | + * value as the BigInteger {@code j}." Other pseudo-code expressions are | |
| 87 | + * interpreted similarly. | |
| 88 | + * | |
| 89 | + * <p>All methods and constructors in this class throw | |
| 90 | + * {@code NullPointerException} when passed | |
| 91 | + * a null object reference for any input parameter. | |
| 92 | + * | |
| 93 | + * @see BigDecimal | |
| 94 | + * @author Josh Bloch | |
| 95 | + * @author Michael McCloskey | |
| 96 | + * @since JDK1.1 | |
| 97 | + */ | |
| 98 | + | |
| 99 | +public class BigInteger extends Number implements Comparable<BigInteger> { | |
| 100 | + /** | |
| 101 | + * The signum of this BigInteger: -1 for negative, 0 for zero, or | |
| 102 | + * 1 for positive. Note that the BigInteger zero <i>must</i> have | |
| 103 | + * a signum of 0. This is necessary to ensures that there is exactly one | |
| 104 | + * representation for each BigInteger value. | |
| 105 | + * | |
| 106 | + * @serial | |
| 107 | + */ | |
| 108 | + final int signum; | |
| 109 | + | |
| 110 | + /** | |
| 111 | + * The magnitude of this BigInteger, in <i>big-endian</i> order: the | |
| 112 | + * zeroth element of this array is the most-significant int of the | |
| 113 | + * magnitude. The magnitude must be "minimal" in that the most-significant | |
| 114 | + * int ({@code mag[0]}) must be non-zero. This is necessary to | |
| 115 | + * ensure that there is exactly one representation for each BigInteger | |
| 116 | + * value. Note that this implies that the BigInteger zero has a | |
| 117 | + * zero-length mag array. | |
| 118 | + */ | |
| 119 | + final int[] mag; | |
| 120 | + | |
| 121 | + // These "redundant fields" are initialized with recognizable nonsense | |
| 122 | + // values, and cached the first time they are needed (or never, if they | |
| 123 | + // aren't needed). | |
| 124 | + | |
| 125 | + /** | |
| 126 | + * One plus the bitCount of this BigInteger. Zeros means unitialized. | |
| 127 | + * | |
| 128 | + * @serial | |
| 129 | + * @see #bitCount | |
| 130 | + * @deprecated Deprecated since logical value is offset from stored | |
| 131 | + * value and correction factor is applied in accessor method. | |
| 132 | + */ | |
| 133 | + @Deprecated | |
| 134 | + private int bitCount; | |
| 135 | + | |
| 136 | + /** | |
| 137 | + * One plus the bitLength of this BigInteger. Zeros means unitialized. | |
| 138 | + * (either value is acceptable). | |
| 139 | + * | |
| 140 | + * @serial | |
| 141 | + * @see #bitLength() | |
| 142 | + * @deprecated Deprecated since logical value is offset from stored | |
| 143 | + * value and correction factor is applied in accessor method. | |
| 144 | + */ | |
| 145 | + @Deprecated | |
| 146 | + private int bitLength; | |
| 147 | + | |
| 148 | + /** | |
| 149 | + * Two plus the lowest set bit of this BigInteger, as returned by | |
| 150 | + * getLowestSetBit(). | |
| 151 | + * | |
| 152 | + * @serial | |
| 153 | + * @see #getLowestSetBit | |
| 154 | + * @deprecated Deprecated since logical value is offset from stored | |
| 155 | + * value and correction factor is applied in accessor method. | |
| 156 | + */ | |
| 157 | + @Deprecated | |
| 158 | + private int lowestSetBit; | |
| 159 | + | |
| 160 | + /** | |
| 161 | + * Two plus the index of the lowest-order int in the magnitude of this | |
| 162 | + * BigInteger that contains a nonzero int, or -2 (either value is acceptable). | |
| 163 | + * The least significant int has int-number 0, the next int in order of | |
| 164 | + * increasing significance has int-number 1, and so forth. | |
| 165 | + * @deprecated Deprecated since logical value is offset from stored | |
| 166 | + * value and correction factor is applied in accessor method. | |
| 167 | + */ | |
| 168 | + @Deprecated | |
| 169 | + private int firstNonzeroIntNum; | |
| 170 | + | |
| 171 | + /** | |
| 172 | + * This mask is used to obtain the value of an int as if it were unsigned. | |
| 173 | + */ | |
| 174 | + final static long LONG_MASK = 0xffffffffL; | |
| 175 | + | |
| 176 | + //Constructors | |
| 177 | + | |
| 178 | + /** | |
| 179 | + * Translates a byte array containing the two's-complement binary | |
| 180 | + * representation of a BigInteger into a BigInteger. The input array is | |
| 181 | + * assumed to be in <i>big-endian</i> byte-order: the most significant | |
| 182 | + * byte is in the zeroth element. | |
| 183 | + * | |
| 184 | + * @param val big-endian two's-complement binary representation of | |
| 185 | + * BigInteger. | |
| 186 | + * @throws NumberFormatException {@code val} is zero bytes long. | |
| 187 | + */ | |
| 188 | + public BigInteger(byte[] val) { | |
| 189 | + if (val.length == 0) | |
| 190 | + throw new NumberFormatException("Zero length BigInteger"); | |
| 191 | + | |
| 192 | + if (val[0] < 0) { | |
| 193 | + mag = makePositive(val); | |
| 194 | + signum = -1; | |
| 195 | + } else { | |
| 196 | + mag = stripLeadingZeroBytes(val); | |
| 197 | + signum = (mag.length == 0 ? 0 : 1); | |
| 198 | + } | |
| 199 | + } | |
| 200 | + | |
| 201 | + /** | |
| 202 | + * This private constructor translates an int array containing the | |
| 203 | + * two's-complement binary representation of a BigInteger into a | |
| 204 | + * BigInteger. The input array is assumed to be in <i>big-endian</i> | |
| 205 | + * int-order: the most significant int is in the zeroth element. | |
| 206 | + */ | |
| 207 | + private BigInteger(int[] val) { | |
| 208 | + if (val.length == 0) | |
| 209 | + throw new NumberFormatException("Zero length BigInteger"); | |
| 210 | + | |
| 211 | + if (val[0] < 0) { | |
| 212 | + mag = makePositive(val); | |
| 213 | + signum = -1; | |
| 214 | + } else { | |
| 215 | + mag = trustedStripLeadingZeroInts(val); | |
| 216 | + signum = (mag.length == 0 ? 0 : 1); | |
| 217 | + } | |
| 218 | + } | |
| 219 | + | |
| 220 | + /** | |
| 221 | + * Translates the sign-magnitude representation of a BigInteger into a | |
| 222 | + * BigInteger. The sign is represented as an integer signum value: -1 for | |
| 223 | + * negative, 0 for zero, or 1 for positive. The magnitude is a byte array | |
| 224 | + * in <i>big-endian</i> byte-order: the most significant byte is in the | |
| 225 | + * zeroth element. A zero-length magnitude array is permissible, and will | |
| 226 | + * result in a BigInteger value of 0, whether signum is -1, 0 or 1. | |
| 227 | + * | |
| 228 | + * @param signum signum of the number (-1 for negative, 0 for zero, 1 | |
| 229 | + * for positive). | |
| 230 | + * @param magnitude big-endian binary representation of the magnitude of | |
| 231 | + * the number. | |
| 232 | + * @throws NumberFormatException {@code signum} is not one of the three | |
| 233 | + * legal values (-1, 0, and 1), or {@code signum} is 0 and | |
| 234 | + * {@code magnitude} contains one or more non-zero bytes. | |
| 235 | + */ | |
| 236 | + public BigInteger(int signum, byte[] magnitude) { | |
| 237 | + this.mag = stripLeadingZeroBytes(magnitude); | |
| 238 | + | |
| 239 | + if (signum < -1 || signum > 1) | |
| 240 | + throw(new NumberFormatException("Invalid signum value")); | |
| 241 | + | |
| 242 | + if (this.mag.length==0) { | |
| 243 | + this.signum = 0; | |
| 244 | + } else { | |
| 245 | + if (signum == 0) | |
| 246 | + throw(new NumberFormatException("signum-magnitude mismatch")); | |
| 247 | + this.signum = signum; | |
| 248 | + } | |
| 249 | + } | |
| 250 | + | |
| 251 | + /** | |
| 252 | + * A constructor for internal use that translates the sign-magnitude | |
| 253 | + * representation of a BigInteger into a BigInteger. It checks the | |
| 254 | + * arguments and copies the magnitude so this constructor would be | |
| 255 | + * safe for external use. | |
| 256 | + */ | |
| 257 | + private BigInteger(int signum, int[] magnitude) { | |
| 258 | + this.mag = stripLeadingZeroInts(magnitude); | |
| 259 | + | |
| 260 | + if (signum < -1 || signum > 1) | |
| 261 | + throw(new NumberFormatException("Invalid signum value")); | |
| 262 | + | |
| 263 | + if (this.mag.length==0) { | |
| 264 | + this.signum = 0; | |
| 265 | + } else { | |
| 266 | + if (signum == 0) | |
| 267 | + throw(new NumberFormatException("signum-magnitude mismatch")); | |
| 268 | + this.signum = signum; | |
| 269 | + } | |
| 270 | + } | |
| 271 | + | |
| 272 | + /** | |
| 273 | + * Translates the String representation of a BigInteger in the | |
| 274 | + * specified radix into a BigInteger. The String representation | |
| 275 | + * consists of an optional minus or plus sign followed by a | |
| 276 | + * sequence of one or more digits in the specified radix. The | |
| 277 | + * character-to-digit mapping is provided by {@code | |
| 278 | + * Character.digit}. The String may not contain any extraneous | |
| 279 | + * characters (whitespace, for example). | |
| 280 | + * | |
| 281 | + * @param val String representation of BigInteger. | |
| 282 | + * @param radix radix to be used in interpreting {@code val}. | |
| 283 | + * @throws NumberFormatException {@code val} is not a valid representation | |
| 284 | + * of a BigInteger in the specified radix, or {@code radix} is | |
| 285 | + * outside the range from {@link Character#MIN_RADIX} to | |
| 286 | + * {@link Character#MAX_RADIX}, inclusive. | |
| 287 | + * @see Character#digit | |
| 288 | + */ | |
| 289 | + public BigInteger(String val, int radix) { | |
| 290 | + int cursor = 0, numDigits; | |
| 291 | + final int len = val.length(); | |
| 292 | + | |
| 293 | + if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX) | |
| 294 | + throw new NumberFormatException("Radix out of range"); | |
| 295 | + if (len == 0) | |
| 296 | + throw new NumberFormatException("Zero length BigInteger"); | |
| 297 | + | |
| 298 | + // Check for at most one leading sign | |
| 299 | + int sign = 1; | |
| 300 | + int index1 = val.lastIndexOf('-'); | |
| 301 | + int index2 = val.lastIndexOf('+'); | |
| 302 | + if ((index1 + index2) <= -1) { | |
| 303 | + // No leading sign character or at most one leading sign character | |
| 304 | + if (index1 == 0 || index2 == 0) { | |
| 305 | + cursor = 1; | |
| 306 | + if (len == 1) | |
| 307 | + throw new NumberFormatException("Zero length BigInteger"); | |
| 308 | + } | |
| 309 | + if (index1 == 0) | |
| 310 | + sign = -1; | |
| 311 | + } else | |
| 312 | + throw new NumberFormatException("Illegal embedded sign character"); | |
| 313 | + | |
| 314 | + // Skip leading zeros and compute number of digits in magnitude | |
| 315 | + while (cursor < len && | |
| 316 | + Character.digit(val.charAt(cursor), radix) == 0) | |
| 317 | + cursor++; | |
| 318 | + if (cursor == len) { | |
| 319 | + signum = 0; | |
| 320 | + mag = ZERO.mag; | |
| 321 | + return; | |
| 322 | + } | |
| 323 | + | |
| 324 | + numDigits = len - cursor; | |
| 325 | + signum = sign; | |
| 326 | + | |
| 327 | + // Pre-allocate array of expected size. May be too large but can | |
| 328 | + // never be too small. Typically exact. | |
| 329 | + int numBits = (int)(((numDigits * bitsPerDigit[radix]) >>> 10) + 1); | |
| 330 | + int numWords = (numBits + 31) >>> 5; | |
| 331 | + int[] magnitude = new int[numWords]; | |
| 332 | + | |
| 333 | + // Process first (potentially short) digit group | |
| 334 | + int firstGroupLen = numDigits % digitsPerInt[radix]; | |
| 335 | + if (firstGroupLen == 0) | |
| 336 | + firstGroupLen = digitsPerInt[radix]; | |
| 337 | + String group = val.substring(cursor, cursor += firstGroupLen); | |
| 338 | + magnitude[numWords - 1] = Integer.parseInt(group, radix); | |
| 339 | + if (magnitude[numWords - 1] < 0) | |
| 340 | + throw new NumberFormatException("Illegal digit"); | |
| 341 | + | |
| 342 | + // Process remaining digit groups | |
| 343 | + int superRadix = intRadix[radix]; | |
| 344 | + int groupVal = 0; | |
| 345 | + while (cursor < len) { | |
| 346 | + group = val.substring(cursor, cursor += digitsPerInt[radix]); | |
| 347 | + groupVal = Integer.parseInt(group, radix); | |
| 348 | + if (groupVal < 0) | |
| 349 | + throw new NumberFormatException("Illegal digit"); | |
| 350 | + destructiveMulAdd(magnitude, superRadix, groupVal); | |
| 351 | + } | |
| 352 | + // Required for cases where the array was overallocated. | |
| 353 | + mag = trustedStripLeadingZeroInts(magnitude); | |
| 354 | + } | |
| 355 | + | |
| 356 | + // Constructs a new BigInteger using a char array with radix=10 | |
| 357 | + BigInteger(char[] val) { | |
| 358 | + int cursor = 0, numDigits; | |
| 359 | + int len = val.length; | |
| 360 | + | |
| 361 | + // Check for leading minus sign | |
| 362 | + int sign = 1; | |
| 363 | + if (val[0] == '-') { | |
| 364 | + if (len == 1) | |
| 365 | + throw new NumberFormatException("Zero length BigInteger"); | |
| 366 | + sign = -1; | |
| 367 | + cursor = 1; | |
| 368 | + } else if (val[0] == '+') { | |
| 369 | + if (len == 1) | |
| 370 | + throw new NumberFormatException("Zero length BigInteger"); | |
| 371 | + cursor = 1; | |
| 372 | + } | |
| 373 | + | |
| 374 | + // Skip leading zeros and compute number of digits in magnitude | |
| 375 | + while (cursor < len && Character.digit(val[cursor], 10) == 0) | |
| 376 | + cursor++; | |
| 377 | + if (cursor == len) { | |
| 378 | + signum = 0; | |
| 379 | + mag = ZERO.mag; | |
| 380 | + return; | |
| 381 | + } | |
| 382 | + | |
| 383 | + numDigits = len - cursor; | |
| 384 | + signum = sign; | |
| 385 | + | |
| 386 | + // Pre-allocate array of expected size | |
| 387 | + int numWords; | |
| 388 | + if (len < 10) { | |
| 389 | + numWords = 1; | |
| 390 | + } else { | |
| 391 | + int numBits = (int)(((numDigits * bitsPerDigit[10]) >>> 10) + 1); | |
| 392 | + numWords = (numBits + 31) >>> 5; | |
| 393 | + } | |
| 394 | + int[] magnitude = new int[numWords]; | |
| 395 | + | |
| 396 | + // Process first (potentially short) digit group | |
| 397 | + int firstGroupLen = numDigits % digitsPerInt[10]; | |
| 398 | + if (firstGroupLen == 0) | |
| 399 | + firstGroupLen = digitsPerInt[10]; | |
| 400 | + magnitude[numWords - 1] = parseInt(val, cursor, cursor += firstGroupLen); | |
| 401 | + | |
| 402 | + // Process remaining digit groups | |
| 403 | + while (cursor < len) { | |
| 404 | + int groupVal = parseInt(val, cursor, cursor += digitsPerInt[10]); | |
| 405 | + destructiveMulAdd(magnitude, intRadix[10], groupVal); | |
| 406 | + } | |
| 407 | + mag = trustedStripLeadingZeroInts(magnitude); | |
| 408 | + } | |
| 409 | + | |
| 410 | + // Create an integer with the digits between the two indexes | |
| 411 | + // Assumes start < end. The result may be negative, but it | |
| 412 | + // is to be treated as an unsigned value. | |
| 413 | + private int parseInt(char[] source, int start, int end) { | |
| 414 | + int result = Character.digit(source[start++], 10); | |
| 415 | + if (result == -1) | |
| 416 | + throw new NumberFormatException(new String(source)); | |
| 417 | + | |
| 418 | + for (int index = start; index<end; index++) { | |
| 419 | + int nextVal = Character.digit(source[index], 10); | |
| 420 | + if (nextVal == -1) | |
| 421 | + throw new NumberFormatException(new String(source)); | |
| 422 | + result = 10*result + nextVal; | |
| 423 | + } | |
| 424 | + | |
| 425 | + return result; | |
| 426 | + } | |
| 427 | + | |
| 428 | + // bitsPerDigit in the given radix times 1024 | |
| 429 | + // Rounded up to avoid underallocation. | |
| 430 | + private static long bitsPerDigit[] = { 0, 0, | |
| 431 | + 1024, 1624, 2048, 2378, 2648, 2875, 3072, 3247, 3402, 3543, 3672, | |
| 432 | + 3790, 3899, 4001, 4096, 4186, 4271, 4350, 4426, 4498, 4567, 4633, | |
| 433 | + 4696, 4756, 4814, 4870, 4923, 4975, 5025, 5074, 5120, 5166, 5210, | |
| 434 | + 5253, 5295}; | |
| 435 | + | |
| 436 | + // Multiply x array times word y in place, and add word z | |
| 437 | + private static void destructiveMulAdd(int[] x, int y, int z) { | |
| 438 | + // Perform the multiplication word by word | |
| 439 | + long ylong = y & LONG_MASK; | |
| 440 | + long zlong = z & LONG_MASK; | |
| 441 | + int len = x.length; | |
| 442 | + | |
| 443 | + long product = 0; | |
| 444 | + long carry = 0; | |
| 445 | + for (int i = len-1; i >= 0; i--) { | |
| 446 | + product = ylong * (x[i] & LONG_MASK) + carry; | |
| 447 | + x[i] = (int)product; | |
| 448 | + carry = product >>> 32; | |
| 449 | + } | |
| 450 | + | |
| 451 | + // Perform the addition | |
| 452 | + long sum = (x[len-1] & LONG_MASK) + zlong; | |
| 453 | + x[len-1] = (int)sum; | |
| 454 | + carry = sum >>> 32; | |
| 455 | + for (int i = len-2; i >= 0; i--) { | |
| 456 | + sum = (x[i] & LONG_MASK) + carry; | |
| 457 | + x[i] = (int)sum; | |
| 458 | + carry = sum >>> 32; | |
| 459 | + } | |
| 460 | + } | |
| 461 | + | |
| 462 | + /** | |
| 463 | + * Translates the decimal String representation of a BigInteger into a | |
| 464 | + * BigInteger. The String representation consists of an optional minus | |
| 465 | + * sign followed by a sequence of one or more decimal digits. The | |
| 466 | + * character-to-digit mapping is provided by {@code Character.digit}. | |
| 467 | + * The String may not contain any extraneous characters (whitespace, for | |
| 468 | + * example). | |
| 469 | + * | |
| 470 | + * @param val decimal String representation of BigInteger. | |
| 471 | + * @throws NumberFormatException {@code val} is not a valid representation | |
| 472 | + * of a BigInteger. | |
| 473 | + * @see Character#digit | |
| 474 | + */ | |
| 475 | + public BigInteger(String val) { | |
| 476 | + this(val, 10); | |
| 477 | + } | |
| 478 | + | |
| 479 | + /** | |
| 480 | + * Constructs a randomly generated BigInteger, uniformly distributed over | |
| 481 | + * the range 0 to (2<sup>{@code numBits}</sup> - 1), inclusive. | |
| 482 | + * The uniformity of the distribution assumes that a fair source of random | |
| 483 | + * bits is provided in {@code rnd}. Note that this constructor always | |
| 484 | + * constructs a non-negative BigInteger. | |
| 485 | + * | |
| 486 | + * @param numBits maximum bitLength of the new BigInteger. | |
| 487 | + * @param rnd source of randomness to be used in computing the new | |
| 488 | + * BigInteger. | |
| 489 | + * @throws IllegalArgumentException {@code numBits} is negative. | |
| 490 | + * @see #bitLength() | |
| 491 | + */ | |
| 492 | + public BigInteger(int numBits, Random rnd) { | |
| 493 | + this(1, randomBits(numBits, rnd)); | |
| 494 | + } | |
| 495 | + | |
| 496 | + private static byte[] randomBits(int numBits, Random rnd) { | |
| 497 | + if (numBits < 0) | |
| 498 | + throw new IllegalArgumentException("numBits must be non-negative"); | |
| 499 | + int numBytes = (int)(((long)numBits+7)/8); // avoid overflow | |
| 500 | + byte[] randomBits = new byte[numBytes]; | |
| 501 | + | |
| 502 | + // Generate random bytes and mask out any excess bits | |
| 503 | + if (numBytes > 0) { | |
| 504 | + rnd.nextBytes(randomBits); | |
| 505 | + int excessBits = 8*numBytes - numBits; | |
| 506 | + randomBits[0] &= (1 << (8-excessBits)) - 1; | |
| 507 | + } | |
| 508 | + return randomBits; | |
| 509 | + } | |
| 510 | + | |
| 511 | + /** | |
| 512 | + * Constructs a randomly generated positive BigInteger that is probably | |
| 513 | + * prime, with the specified bitLength. | |
| 514 | + * | |
| 515 | + * <p>It is recommended that the {@link #probablePrime probablePrime} | |
| 516 | + * method be used in preference to this constructor unless there | |
| 517 | + * is a compelling need to specify a certainty. | |
| 518 | + * | |
| 519 | + * @param bitLength bitLength of the returned BigInteger. | |
| 520 | + * @param certainty a measure of the uncertainty that the caller is | |
| 521 | + * willing to tolerate. The probability that the new BigInteger | |
| 522 | + * represents a prime number will exceed | |
| 523 | + * (1 - 1/2<sup>{@code certainty}</sup>). The execution time of | |
| 524 | + * this constructor is proportional to the value of this parameter. | |
| 525 | + * @param rnd source of random bits used to select candidates to be | |
| 526 | + * tested for primality. | |
| 527 | + * @throws ArithmeticException {@code bitLength < 2}. | |
| 528 | + * @see #bitLength() | |
| 529 | + */ | |
| 530 | + public BigInteger(int bitLength, int certainty, Random rnd) { | |
| 531 | + BigInteger prime; | |
| 532 | + | |
| 533 | + if (bitLength < 2) | |
| 534 | + throw new ArithmeticException("bitLength < 2"); | |
| 535 | + // The cutoff of 95 was chosen empirically for best performance | |
| 536 | + prime = (bitLength < 95 ? smallPrime(bitLength, certainty, rnd) | |
| 537 | + : largePrime(bitLength, certainty, rnd)); | |
| 538 | + signum = 1; | |
| 539 | + mag = prime.mag; | |
| 540 | + } | |
| 541 | + | |
| 542 | + // Minimum size in bits that the requested prime number has | |
| 543 | + // before we use the large prime number generating algorithms | |
| 544 | + private static final int SMALL_PRIME_THRESHOLD = 95; | |
| 545 | + | |
| 546 | + // Certainty required to meet the spec of probablePrime | |
| 547 | + private static final int DEFAULT_PRIME_CERTAINTY = 100; | |
| 548 | + | |
| 549 | + /** | |
| 550 | + * Returns a positive BigInteger that is probably prime, with the | |
| 551 | + * specified bitLength. The probability that a BigInteger returned | |
| 552 | + * by this method is composite does not exceed 2<sup>-100</sup>. | |
| 553 | + * | |
| 554 | + * @param bitLength bitLength of the returned BigInteger. | |
| 555 | + * @param rnd source of random bits used to select candidates to be | |
| 556 | + * tested for primality. | |
| 557 | + * @return a BigInteger of {@code bitLength} bits that is probably prime | |
| 558 | + * @throws ArithmeticException {@code bitLength < 2}. | |
| 559 | + * @see #bitLength() | |
| 560 | + * @since 1.4 | |
| 561 | + */ | |
| 562 | + public static BigInteger probablePrime(int bitLength, Random rnd) { | |
| 563 | + if (bitLength < 2) | |
| 564 | + throw new ArithmeticException("bitLength < 2"); | |
| 565 | + | |
| 566 | + // The cutoff of 95 was chosen empirically for best performance | |
| 567 | + return (bitLength < SMALL_PRIME_THRESHOLD ? | |
| 568 | + smallPrime(bitLength, DEFAULT_PRIME_CERTAINTY, rnd) : | |
| 569 | + largePrime(bitLength, DEFAULT_PRIME_CERTAINTY, rnd)); | |
| 570 | + } | |
| 571 | + | |
| 572 | + /** | |
| 573 | + * Find a random number of the specified bitLength that is probably prime. | |
| 574 | + * This method is used for smaller primes, its performance degrades on | |
| 575 | + * larger bitlengths. | |
| 576 | + * | |
| 577 | + * This method assumes bitLength > 1. | |
| 578 | + */ | |
| 579 | + private static BigInteger smallPrime(int bitLength, int certainty, Random rnd) { | |
| 580 | + int magLen = (bitLength + 31) >>> 5; | |
| 581 | + int temp[] = new int[magLen]; | |
| 582 | + int highBit = 1 << ((bitLength+31) & 0x1f); // High bit of high int | |
| 583 | + int highMask = (highBit << 1) - 1; // Bits to keep in high int | |
| 584 | + | |
| 585 | + while(true) { | |
| 586 | + // Construct a candidate | |
| 587 | + for (int i=0; i<magLen; i++) | |
| 588 | + temp[i] = rnd.nextInt(); | |
| 589 | + temp[0] = (temp[0] & highMask) | highBit; // Ensure exact length | |
| 590 | + if (bitLength > 2) | |
| 591 | + temp[magLen-1] |= 1; // Make odd if bitlen > 2 | |
| 592 | + | |
| 593 | + BigInteger p = new BigInteger(temp, 1); | |
| 594 | + | |
| 595 | + // Do cheap "pre-test" if applicable | |
| 596 | + if (bitLength > 6) { | |
| 597 | + long r = p.remainder(SMALL_PRIME_PRODUCT).longValue(); | |
| 598 | + if ((r%3==0) || (r%5==0) || (r%7==0) || (r%11==0) || | |
| 599 | + (r%13==0) || (r%17==0) || (r%19==0) || (r%23==0) || | |
| 600 | + (r%29==0) || (r%31==0) || (r%37==0) || (r%41==0)) | |
| 601 | + continue; // Candidate is composite; try another | |
| 602 | + } | |
| 603 | + | |
| 604 | + // All candidates of bitLength 2 and 3 are prime by this point | |
| 605 | + if (bitLength < 4) | |
| 606 | + return p; | |
| 607 | + | |
| 608 | + // Do expensive test if we survive pre-test (or it's inapplicable) | |
| 609 | + if (p.primeToCertainty(certainty, rnd)) | |
| 610 | + return p; | |
| 611 | + } | |
| 612 | + } | |
| 613 | + | |
| 614 | + private static final BigInteger SMALL_PRIME_PRODUCT | |
| 615 | + = valueOf(3L*5*7*11*13*17*19*23*29*31*37*41); | |
| 616 | + | |
| 617 | + /** | |
| 618 | + * Find a random number of the specified bitLength that is probably prime. | |
| 619 | + * This method is more appropriate for larger bitlengths since it uses | |
| 620 | + * a sieve to eliminate most composites before using a more expensive | |
| 621 | + * test. | |
| 622 | + */ | |
| 623 | + private static BigInteger largePrime(int bitLength, int certainty, Random rnd) { | |
| 624 | + BigInteger p; | |
| 625 | + p = new BigInteger(bitLength, rnd).setBit(bitLength-1); | |
| 626 | + p.mag[p.mag.length-1] &= 0xfffffffe; | |
| 627 | + | |
| 628 | + // Use a sieve length likely to contain the next prime number | |
| 629 | + int searchLen = (bitLength / 20) * 64; | |
| 630 | + BitSieve searchSieve = new BitSieve(p, searchLen); | |
| 631 | + BigInteger candidate = searchSieve.retrieve(p, certainty, rnd); | |
| 632 | + | |
| 633 | + while ((candidate == null) || (candidate.bitLength() != bitLength)) { | |
| 634 | + p = p.add(BigInteger.valueOf(2*searchLen)); | |
| 635 | + if (p.bitLength() != bitLength) | |
| 636 | + p = new BigInteger(bitLength, rnd).setBit(bitLength-1); | |
| 637 | + p.mag[p.mag.length-1] &= 0xfffffffe; | |
| 638 | + searchSieve = new BitSieve(p, searchLen); | |
| 639 | + candidate = searchSieve.retrieve(p, certainty, rnd); | |
| 640 | + } | |
| 641 | + return candidate; | |
| 642 | + } | |
| 643 | + | |
| 644 | + /** | |
| 645 | + * Returns the first integer greater than this {@code BigInteger} that | |
| 646 | + * is probably prime. The probability that the number returned by this | |
| 647 | + * method is composite does not exceed 2<sup>-100</sup>. This method will | |
| 648 | + * never skip over a prime when searching: if it returns {@code p}, there | |
| 649 | + * is no prime {@code q} such that {@code this < q < p}. | |
| 650 | + * | |
| 651 | + * @return the first integer greater than this {@code BigInteger} that | |
| 652 | + * is probably prime. | |
| 653 | + * @throws ArithmeticException {@code this < 0}. | |
| 654 | + * @since 1.5 | |
| 655 | + */ | |
| 656 | + public BigInteger nextProbablePrime() { | |
| 657 | + if (this.signum < 0) | |
| 658 | + throw new ArithmeticException("start < 0: " + this); | |
| 659 | + | |
| 660 | + // Handle trivial cases | |
| 661 | + if ((this.signum == 0) || this.equals(ONE)) | |
| 662 | + return TWO; | |
| 663 | + | |
| 664 | + BigInteger result = this.add(ONE); | |
| 665 | + | |
| 666 | + // Fastpath for small numbers | |
| 667 | + if (result.bitLength() < SMALL_PRIME_THRESHOLD) { | |
| 668 | + | |
| 669 | + // Ensure an odd number | |
| 670 | + if (!result.testBit(0)) | |
| 671 | + result = result.add(ONE); | |
| 672 | + | |
| 673 | + while(true) { | |
| 674 | + // Do cheap "pre-test" if applicable | |
| 675 | + if (result.bitLength() > 6) { | |
| 676 | + long r = result.remainder(SMALL_PRIME_PRODUCT).longValue(); | |
| 677 | + if ((r%3==0) || (r%5==0) || (r%7==0) || (r%11==0) || | |
| 678 | + (r%13==0) || (r%17==0) || (r%19==0) || (r%23==0) || | |
| 679 | + (r%29==0) || (r%31==0) || (r%37==0) || (r%41==0)) { | |
| 680 | + result = result.add(TWO); | |
| 681 | + continue; // Candidate is composite; try another | |
| 682 | + } | |
| 683 | + } | |
| 684 | + | |
| 685 | + // All candidates of bitLength 2 and 3 are prime by this point | |
| 686 | + if (result.bitLength() < 4) | |
| 687 | + return result; | |
| 688 | + | |
| 689 | + // The expensive test | |
| 690 | + if (result.primeToCertainty(DEFAULT_PRIME_CERTAINTY, null)) | |
| 691 | + return result; | |
| 692 | + | |
| 693 | + result = result.add(TWO); | |
| 694 | + } | |
| 695 | + } | |
| 696 | + | |
| 697 | + // Start at previous even number | |
| 698 | + if (result.testBit(0)) | |
| 699 | + result = result.subtract(ONE); | |
| 700 | + | |
| 701 | + // Looking for the next large prime | |
| 702 | + int searchLen = (result.bitLength() / 20) * 64; | |
| 703 | + | |
| 704 | + while(true) { | |
| 705 | + BitSieve searchSieve = new BitSieve(result, searchLen); | |
| 706 | + BigInteger candidate = searchSieve.retrieve(result, | |
| 707 | + DEFAULT_PRIME_CERTAINTY, null); | |
| 708 | + if (candidate != null) | |
| 709 | + return candidate; | |
| 710 | + result = result.add(BigInteger.valueOf(2 * searchLen)); | |
| 711 | + } | |
| 712 | + } | |
| 713 | + | |
| 714 | + /** | |
| 715 | + * Returns {@code true} if this BigInteger is probably prime, | |
| 716 | + * {@code false} if it's definitely composite. | |
| 717 | + * | |
| 718 | + * This method assumes bitLength > 2. | |
| 719 | + * | |
| 720 | + * @param certainty a measure of the uncertainty that the caller is | |
| 721 | + * willing to tolerate: if the call returns {@code true} | |
| 722 | + * the probability that this BigInteger is prime exceeds | |
| 723 | + * {@code (1 - 1/2<sup>certainty</sup>)}. The execution time of | |
| 724 | + * this method is proportional to the value of this parameter. | |
| 725 | + * @return {@code true} if this BigInteger is probably prime, | |
| 726 | + * {@code false} if it's definitely composite. | |
| 727 | + */ | |
| 728 | + boolean primeToCertainty(int certainty, Random random) { | |
| 729 | + int rounds = 0; | |
| 730 | + int n = (Math.min(certainty, Integer.MAX_VALUE-1)+1)/2; | |
| 731 | + | |
| 732 | + // The relationship between the certainty and the number of rounds | |
| 733 | + // we perform is given in the draft standard ANSI X9.80, "PRIME | |
| 734 | + // NUMBER GENERATION, PRIMALITY TESTING, AND PRIMALITY CERTIFICATES". | |
| 735 | + int sizeInBits = this.bitLength(); | |
| 736 | + if (sizeInBits < 100) { | |
| 737 | + rounds = 50; | |
| 738 | + rounds = n < rounds ? n : rounds; | |
| 739 | + return passesMillerRabin(rounds, random); | |
| 740 | + } | |
| 741 | + | |
| 742 | + if (sizeInBits < 256) { | |
| 743 | + rounds = 27; | |
| 744 | + } else if (sizeInBits < 512) { | |
| 745 | + rounds = 15; | |
| 746 | + } else if (sizeInBits < 768) { | |
| 747 | + rounds = 8; | |
| 748 | + } else if (sizeInBits < 1024) { | |
| 749 | + rounds = 4; | |
| 750 | + } else { | |
| 751 | + rounds = 2; | |
| 752 | + } | |
| 753 | + rounds = n < rounds ? n : rounds; | |
| 754 | + | |
| 755 | + return passesMillerRabin(rounds, random) && passesLucasLehmer(); | |
| 756 | + } | |
| 757 | + | |
| 758 | + /** | |
| 759 | + * Returns true iff this BigInteger is a Lucas-Lehmer probable prime. | |
| 760 | + * | |
| 761 | + * The following assumptions are made: | |
| 762 | + * This BigInteger is a positive, odd number. | |
| 763 | + */ | |
| 764 | + private boolean passesLucasLehmer() { | |
| 765 | + BigInteger thisPlusOne = this.add(ONE); | |
| 766 | + | |
| 767 | + // Step 1 | |
| 768 | + int d = 5; | |
| 769 | + while (jacobiSymbol(d, this) != -1) { | |
| 770 | + // 5, -7, 9, -11, ... | |
| 771 | + d = (d<0) ? Math.abs(d)+2 : -(d+2); | |
| 772 | + } | |
| 773 | + | |
| 774 | + // Step 2 | |
| 775 | + BigInteger u = lucasLehmerSequence(d, thisPlusOne, this); | |
| 776 | + | |
| 777 | + // Step 3 | |
| 778 | + return u.mod(this).equals(ZERO); | |
| 779 | + } | |
| 780 | + | |
| 781 | + /** | |
| 782 | + * Computes Jacobi(p,n). | |
| 783 | + * Assumes n positive, odd, n>=3. | |
| 784 | + */ | |
| 785 | + private static int jacobiSymbol(int p, BigInteger n) { | |
| 786 | + if (p == 0) | |
| 787 | + return 0; | |
| 788 | + | |
| 789 | + // Algorithm and comments adapted from Colin Plumb's C library. | |
| 790 | + int j = 1; | |
| 791 | + int u = n.mag[n.mag.length-1]; | |
| 792 | + | |
| 793 | + // Make p positive | |
| 794 | + if (p < 0) { | |
| 795 | + p = -p; | |
| 796 | + int n8 = u & 7; | |
| 797 | + if ((n8 == 3) || (n8 == 7)) | |
| 798 | + j = -j; // 3 (011) or 7 (111) mod 8 | |
| 799 | + } | |
| 800 | + | |
| 801 | + // Get rid of factors of 2 in p | |
| 802 | + while ((p & 3) == 0) | |
| 803 | + p >>= 2; | |
| 804 | + if ((p & 1) == 0) { | |
| 805 | + p >>= 1; | |
| 806 | + if (((u ^ (u>>1)) & 2) != 0) | |
| 807 | + j = -j; // 3 (011) or 5 (101) mod 8 | |
| 808 | + } | |
| 809 | + if (p == 1) | |
| 810 | + return j; | |
| 811 | + // Then, apply quadratic reciprocity | |
| 812 | + if ((p & u & 2) != 0) // p = u = 3 (mod 4)? | |
| 813 | + j = -j; | |
| 814 | + // And reduce u mod p | |
| 815 | + u = n.mod(BigInteger.valueOf(p)).intValue(); | |
| 816 | + | |
| 817 | + // Now compute Jacobi(u,p), u < p | |
| 818 | + while (u != 0) { | |
| 819 | + while ((u & 3) == 0) | |
| 820 | + u >>= 2; | |
| 821 | + if ((u & 1) == 0) { | |
| 822 | + u >>= 1; | |
| 823 | + if (((p ^ (p>>1)) & 2) != 0) | |
| 824 | + j = -j; // 3 (011) or 5 (101) mod 8 | |
| 825 | + } | |
| 826 | + if (u == 1) | |
| 827 | + return j; | |
| 828 | + // Now both u and p are odd, so use quadratic reciprocity | |
| 829 | + assert (u < p); | |
| 830 | + int t = u; u = p; p = t; | |
| 831 | + if ((u & p & 2) != 0) // u = p = 3 (mod 4)? | |
| 832 | + j = -j; | |
| 833 | + // Now u >= p, so it can be reduced | |
| 834 | + u %= p; | |
| 835 | + } | |
| 836 | + return 0; | |
| 837 | + } | |
| 838 | + | |
| 839 | + private static BigInteger lucasLehmerSequence(int z, BigInteger k, BigInteger n) { | |
| 840 | + BigInteger d = BigInteger.valueOf(z); | |
| 841 | + BigInteger u = ONE; BigInteger u2; | |
| 842 | + BigInteger v = ONE; BigInteger v2; | |
| 843 | + | |
| 844 | + for (int i=k.bitLength()-2; i>=0; i--) { | |
| 845 | + u2 = u.multiply(v).mod(n); | |
| 846 | + | |
| 847 | + v2 = v.square().add(d.multiply(u.square())).mod(n); | |
| 848 | + if (v2.testBit(0)) | |
| 849 | + v2 = v2.subtract(n); | |
| 850 | + | |
| 851 | + v2 = v2.shiftRight(1); | |
| 852 | + | |
| 853 | + u = u2; v = v2; | |
| 854 | + if (k.testBit(i)) { | |
| 855 | + u2 = u.add(v).mod(n); | |
| 856 | + if (u2.testBit(0)) | |
| 857 | + u2 = u2.subtract(n); | |
| 858 | + | |
| 859 | + u2 = u2.shiftRight(1); | |
| 860 | + v2 = v.add(d.multiply(u)).mod(n); | |
| 861 | + if (v2.testBit(0)) | |
| 862 | + v2 = v2.subtract(n); | |
| 863 | + v2 = v2.shiftRight(1); | |
| 864 | + | |
| 865 | + u = u2; v = v2; | |
| 866 | + } | |
| 867 | + } | |
| 868 | + return u; | |
| 869 | + } | |
| 870 | + | |
| 871 | + private static volatile Random staticRandom; | |
| 872 | + | |
| 873 | + private static Random getSecureRandom() { | |
| 874 | + if (staticRandom == null) { | |
| 875 | + staticRandom = new java.security.SecureRandom(); | |
| 876 | + } | |
| 877 | + return staticRandom; | |
| 878 | + } | |
| 879 | + | |
| 880 | + /** | |
| 881 | + * Returns true iff this BigInteger passes the specified number of | |
| 882 | + * Miller-Rabin tests. This test is taken from the DSA spec (NIST FIPS | |
| 883 | + * 186-2). | |
| 884 | + * | |
| 885 | + * The following assumptions are made: | |
| 886 | + * This BigInteger is a positive, odd number greater than 2. | |
| 887 | + * iterations<=50. | |
| 888 | + */ | |
| 889 | + private boolean passesMillerRabin(int iterations, Random rnd) { | |
| 890 | + // Find a and m such that m is odd and this == 1 + 2**a * m | |
| 891 | + BigInteger thisMinusOne = this.subtract(ONE); | |
| 892 | + BigInteger m = thisMinusOne; | |
| 893 | + int a = m.getLowestSetBit(); | |
| 894 | + m = m.shiftRight(a); | |
| 895 | + | |
| 896 | + // Do the tests | |
| 897 | + if (rnd == null) { | |
| 898 | + rnd = getSecureRandom(); | |
| 899 | + } | |
| 900 | + for (int i=0; i<iterations; i++) { | |
| 901 | + // Generate a uniform random on (1, this) | |
| 902 | + BigInteger b; | |
| 903 | + do { | |
| 904 | + b = new BigInteger(this.bitLength(), rnd); | |
| 905 | + } while (b.compareTo(ONE) <= 0 || b.compareTo(this) >= 0); | |
| 906 | + | |
| 907 | + int j = 0; | |
| 908 | + BigInteger z = b.modPow(m, this); | |
| 909 | + while(!((j==0 && z.equals(ONE)) || z.equals(thisMinusOne))) { | |
| 910 | + if (j>0 && z.equals(ONE) || ++j==a) | |
| 911 | + return false; | |
| 912 | + z = z.modPow(TWO, this); | |
| 913 | + } | |
| 914 | + } | |
| 915 | + return true; | |
| 916 | + } | |
| 917 | + | |
| 918 | + /** | |
| 919 | + * This internal constructor differs from its public cousin | |
| 920 | + * with the arguments reversed in two ways: it assumes that its | |
| 921 | + * arguments are correct, and it doesn't copy the magnitude array. | |
| 922 | + */ | |
| 923 | + BigInteger(int[] magnitude, int signum) { | |
| 924 | + this.signum = (magnitude.length==0 ? 0 : signum); | |
| 925 | + this.mag = magnitude; | |
| 926 | + } | |
| 927 | + | |
| 928 | + /** | |
| 929 | + * This private constructor is for internal use and assumes that its | |
| 930 | + * arguments are correct. | |
| 931 | + */ | |
| 932 | + private BigInteger(byte[] magnitude, int signum) { | |
| 933 | + this.signum = (magnitude.length==0 ? 0 : signum); | |
| 934 | + this.mag = stripLeadingZeroBytes(magnitude); | |
| 935 | + } | |
| 936 | + | |
| 937 | + //Static Factory Methods | |
| 938 | + | |
| 939 | + /** | |
| 940 | + * Returns a BigInteger whose value is equal to that of the | |
| 941 | + * specified {@code long}. This "static factory method" is | |
| 942 | + * provided in preference to a ({@code long}) constructor | |
| 943 | + * because it allows for reuse of frequently used BigIntegers. | |
| 944 | + * | |
| 945 | + * @param val value of the BigInteger to return. | |
| 946 | + * @return a BigInteger with the specified value. | |
| 947 | + */ | |
| 948 | + public static BigInteger valueOf(long val) { | |
| 949 | + // If -MAX_CONSTANT < val < MAX_CONSTANT, return stashed constant | |
| 950 | + if (val == 0) | |
| 951 | + return ZERO; | |
| 952 | + if (val > 0 && val <= MAX_CONSTANT) | |
| 953 | + return posConst[(int) val]; | |
| 954 | + else if (val < 0 && val >= -MAX_CONSTANT) | |
| 955 | + return negConst[(int) -val]; | |
| 956 | + | |
| 957 | + return new BigInteger(val); | |
| 958 | + } | |
| 959 | + | |
| 960 | + /** | |
| 961 | + * Constructs a BigInteger with the specified value, which may not be zero. | |
| 962 | + */ | |
| 963 | + private BigInteger(long val) { | |
| 964 | + if (val < 0) { | |
| 965 | + val = -val; | |
| 966 | + signum = -1; | |
| 967 | + } else { | |
| 968 | + signum = 1; | |
| 969 | + } | |
| 970 | + | |
| 971 | + int highWord = (int)(val >>> 32); | |
| 972 | + if (highWord==0) { | |
| 973 | + mag = new int[1]; | |
| 974 | + mag[0] = (int)val; | |
| 975 | + } else { | |
| 976 | + mag = new int[2]; | |
| 977 | + mag[0] = highWord; | |
| 978 | + mag[1] = (int)val; | |
| 979 | + } | |
| 980 | + } | |
| 981 | + | |
| 982 | + /** | |
| 983 | + * Returns a BigInteger with the given two's complement representation. | |
| 984 | + * Assumes that the input array will not be modified (the returned | |
| 985 | + * BigInteger will reference the input array if feasible). | |
| 986 | + */ | |
| 987 | + private static BigInteger valueOf(int val[]) { | |
| 988 | + return (val[0]>0 ? new BigInteger(val, 1) : new BigInteger(val)); | |
| 989 | + } | |
| 990 | + | |
| 991 | + // Constants | |
| 992 | + | |
| 993 | + /** | |
| 994 | + * Initialize static constant array when class is loaded. | |
| 995 | + */ | |
| 996 | + private final static int MAX_CONSTANT = 16; | |
| 997 | + private static BigInteger posConst[] = new BigInteger[MAX_CONSTANT+1]; | |
| 998 | + private static BigInteger negConst[] = new BigInteger[MAX_CONSTANT+1]; | |
| 999 | + static { | |
| 1000 | + for (int i = 1; i <= MAX_CONSTANT; i++) { | |
| 1001 | + int[] magnitude = new int[1]; | |
| 1002 | + magnitude[0] = i; | |
| 1003 | + posConst[i] = new BigInteger(magnitude, 1); | |
| 1004 | + negConst[i] = new BigInteger(magnitude, -1); | |
| 1005 | + } | |
| 1006 | + } | |
| 1007 | + | |
| 1008 | + /** | |
| 1009 | + * The BigInteger constant zero. | |
| 1010 | + * | |
| 1011 | + * @since 1.2 | |
| 1012 | + */ | |
| 1013 | + public static final BigInteger ZERO = new BigInteger(new int[0], 0); | |
| 1014 | + | |
| 1015 | + /** | |
| 1016 | + * The BigInteger constant one. | |
| 1017 | + * | |
| 1018 | + * @since 1.2 | |
| 1019 | + */ | |
| 1020 | + public static final BigInteger ONE = valueOf(1); | |
| 1021 | + | |
| 1022 | + /** | |
| 1023 | + * The BigInteger constant two. (Not exported.) | |
| 1024 | + */ | |
| 1025 | + private static final BigInteger TWO = valueOf(2); | |
| 1026 | + | |
| 1027 | + /** | |
| 1028 | + * The BigInteger constant ten. | |
| 1029 | + * | |
| 1030 | + * @since 1.5 | |
| 1031 | + */ | |
| 1032 | + public static final BigInteger TEN = valueOf(10); | |
| 1033 | + | |
| 1034 | + // Arithmetic Operations | |
| 1035 | + | |
| 1036 | + /** | |
| 1037 | + * Returns a BigInteger whose value is {@code (this + val)}. | |
| 1038 | + * | |
| 1039 | + * @param val value to be added to this BigInteger. | |
| 1040 | + * @return {@code this + val} | |
| 1041 | + */ | |
| 1042 | + public BigInteger add(BigInteger val) { | |
| 1043 | + if (val.signum == 0) | |
| 1044 | + return this; | |
| 1045 | + if (signum == 0) | |
| 1046 | + return val; | |
| 1047 | + if (val.signum == signum) | |
| 1048 | + return new BigInteger(add(mag, val.mag), signum); | |
| 1049 | + | |
| 1050 | + int cmp = compareMagnitude(val); | |
| 1051 | + if (cmp == 0) | |
| 1052 | + return ZERO; | |
| 1053 | + int[] resultMag = (cmp > 0 ? subtract(mag, val.mag) | |
| 1054 | + : subtract(val.mag, mag)); | |
| 1055 | + resultMag = trustedStripLeadingZeroInts(resultMag); | |
| 1056 | + | |
| 1057 | + return new BigInteger(resultMag, cmp == signum ? 1 : -1); | |
| 1058 | + } | |
| 1059 | + | |
| 1060 | + /** | |
| 1061 | + * Adds the contents of the int arrays x and y. This method allocates | |
| 1062 | + * a new int array to hold the answer and returns a reference to that | |
| 1063 | + * array. | |
| 1064 | + */ | |
| 1065 | + private static int[] add(int[] x, int[] y) { | |
| 1066 | + // If x is shorter, swap the two arrays | |
| 1067 | + if (x.length < y.length) { | |
| 1068 | + int[] tmp = x; | |
| 1069 | + x = y; | |
| 1070 | + y = tmp; | |
| 1071 | + } | |
| 1072 | + | |
| 1073 | + int xIndex = x.length; | |
| 1074 | + int yIndex = y.length; | |
| 1075 | + int result[] = new int[xIndex]; | |
| 1076 | + long sum = 0; | |
| 1077 | + | |
| 1078 | + // Add common parts of both numbers | |
| 1079 | + while(yIndex > 0) { | |
| 1080 | + sum = (x[--xIndex] & LONG_MASK) + | |
| 1081 | + (y[--yIndex] & LONG_MASK) + (sum >>> 32); | |
| 1082 | + result[xIndex] = (int)sum; | |
| 1083 | + } | |
| 1084 | + | |
| 1085 | + // Copy remainder of longer number while carry propagation is required | |
| 1086 | + boolean carry = (sum >>> 32 != 0); | |
| 1087 | + while (xIndex > 0 && carry) | |
| 1088 | + carry = ((result[--xIndex] = x[xIndex] + 1) == 0); | |
| 1089 | + | |
| 1090 | + // Copy remainder of longer number | |
| 1091 | + while (xIndex > 0) | |
| 1092 | + result[--xIndex] = x[xIndex]; | |
| 1093 | + | |
| 1094 | + // Grow result if necessary | |
| 1095 | + if (carry) { | |
| 1096 | + int bigger[] = new int[result.length + 1]; | |
| 1097 | + System.arraycopy(result, 0, bigger, 1, result.length); | |
| 1098 | + bigger[0] = 0x01; | |
| 1099 | + return bigger; | |
| 1100 | + } | |
| 1101 | + return result; | |
| 1102 | + } | |
| 1103 | + | |
| 1104 | + /** | |
| 1105 | + * Returns a BigInteger whose value is {@code (this - val)}. | |
| 1106 | + * | |
| 1107 | + * @param val value to be subtracted from this BigInteger. | |
| 1108 | + * @return {@code this - val} | |
| 1109 | + */ | |
| 1110 | + public BigInteger subtract(BigInteger val) { | |
| 1111 | + if (val.signum == 0) | |
| 1112 | + return this; | |
| 1113 | + if (signum == 0) | |
| 1114 | + return val.negate(); | |
| 1115 | + if (val.signum != signum) | |
| 1116 | + return new BigInteger(add(mag, val.mag), signum); | |
| 1117 | + | |
| 1118 | + int cmp = compareMagnitude(val); | |
| 1119 | + if (cmp == 0) | |
| 1120 | + return ZERO; | |
| 1121 | + int[] resultMag = (cmp > 0 ? subtract(mag, val.mag) | |
| 1122 | + : subtract(val.mag, mag)); | |
| 1123 | + resultMag = trustedStripLeadingZeroInts(resultMag); | |
| 1124 | + return new BigInteger(resultMag, cmp == signum ? 1 : -1); | |
| 1125 | + } | |
| 1126 | + | |
| 1127 | + /** | |
| 1128 | + * Subtracts the contents of the second int arrays (little) from the | |
| 1129 | + * first (big). The first int array (big) must represent a larger number | |
| 1130 | + * than the second. This method allocates the space necessary to hold the | |
| 1131 | + * answer. | |
| 1132 | + */ | |
| 1133 | + private static int[] subtract(int[] big, int[] little) { | |
| 1134 | + int bigIndex = big.length; | |
| 1135 | + int result[] = new int[bigIndex]; | |
| 1136 | + int littleIndex = little.length; | |
| 1137 | + long difference = 0; | |
| 1138 | + | |
| 1139 | + // Subtract common parts of both numbers | |
| 1140 | + while(littleIndex > 0) { | |
| 1141 | + difference = (big[--bigIndex] & LONG_MASK) - | |
| 1142 | + (little[--littleIndex] & LONG_MASK) + | |
| 1143 | + (difference >> 32); | |
| 1144 | + result[bigIndex] = (int)difference; | |
| 1145 | + } | |
| 1146 | + | |
| 1147 | + // Subtract remainder of longer number while borrow propagates | |
| 1148 | + boolean borrow = (difference >> 32 != 0); | |
| 1149 | + while (bigIndex > 0 && borrow) | |
| 1150 | + borrow = ((result[--bigIndex] = big[bigIndex] - 1) == -1); | |
| 1151 | + | |
| 1152 | + // Copy remainder of longer number | |
| 1153 | + while (bigIndex > 0) | |
| 1154 | + result[--bigIndex] = big[bigIndex]; | |
| 1155 | + | |
| 1156 | + return result; | |
| 1157 | + } | |
| 1158 | + | |
| 1159 | + /** | |
| 1160 | + * Returns a BigInteger whose value is {@code (this * val)}. | |
| 1161 | + * | |
| 1162 | + * @param val value to be multiplied by this BigInteger. | |
| 1163 | + * @return {@code this * val} | |
| 1164 | + */ | |
| 1165 | + public BigInteger multiply(BigInteger val) { | |
| 1166 | + if (val.signum == 0 || signum == 0) | |
| 1167 | + return ZERO; | |
| 1168 | + | |
| 1169 | + int[] result = multiplyToLen(mag, mag.length, | |
| 1170 | + val.mag, val.mag.length, null); | |
| 1171 | + result = trustedStripLeadingZeroInts(result); | |
| 1172 | + return new BigInteger(result, signum == val.signum ? 1 : -1); | |
| 1173 | + } | |
| 1174 | + | |
| 1175 | + /** | |
| 1176 | + * Package private methods used by BigDecimal code to multiply a BigInteger | |
| 1177 | + * with a long. Assumes v is not equal to INFLATED. | |
| 1178 | + */ | |
| 1179 | + BigInteger multiply(long v) { | |
| 1180 | + if (v == 0 || signum == 0) | |
| 1181 | + return ZERO; | |
| 1182 | + if (v == BigDecimal.INFLATED) | |
| 1183 | + return multiply(BigInteger.valueOf(v)); | |
| 1184 | + int rsign = (v > 0 ? signum : -signum); | |
| 1185 | + if (v < 0) | |
| 1186 | + v = -v; | |
| 1187 | + long dh = v >>> 32; // higher order bits | |
| 1188 | + long dl = v & LONG_MASK; // lower order bits | |
| 1189 | + | |
| 1190 | + int xlen = mag.length; | |
| 1191 | + int[] value = mag; | |
| 1192 | + int[] rmag = (dh == 0L) ? (new int[xlen + 1]) : (new int[xlen + 2]); | |
| 1193 | + long carry = 0; | |
| 1194 | + int rstart = rmag.length - 1; | |
| 1195 | + for (int i = xlen - 1; i >= 0; i--) { | |
| 1196 | + long product = (value[i] & LONG_MASK) * dl + carry; | |
| 1197 | + rmag[rstart--] = (int)product; | |
| 1198 | + carry = product >>> 32; | |
| 1199 | + } | |
| 1200 | + rmag[rstart] = (int)carry; | |
| 1201 | + if (dh != 0L) { | |
| 1202 | + carry = 0; | |
| 1203 | + rstart = rmag.length - 2; | |
| 1204 | + for (int i = xlen - 1; i >= 0; i--) { | |
| 1205 | + long product = (value[i] & LONG_MASK) * dh + | |
| 1206 | + (rmag[rstart] & LONG_MASK) + carry; | |
| 1207 | + rmag[rstart--] = (int)product; | |
| 1208 | + carry = product >>> 32; | |
| 1209 | + } | |
| 1210 | + rmag[0] = (int)carry; | |
| 1211 | + } | |
| 1212 | + if (carry == 0L) | |
| 1213 | + rmag = java.util.Arrays.copyOfRange(rmag, 1, rmag.length); | |
| 1214 | + return new BigInteger(rmag, rsign); | |
| 1215 | + } | |
| 1216 | + | |
| 1217 | + /** | |
| 1218 | + * Multiplies int arrays x and y to the specified lengths and places | |
| 1219 | + * the result into z. There will be no leading zeros in the resultant array. | |
| 1220 | + */ | |
| 1221 | + private int[] multiplyToLen(int[] x, int xlen, int[] y, int ylen, int[] z) { | |
| 1222 | + int xstart = xlen - 1; | |
| 1223 | + int ystart = ylen - 1; | |
| 1224 | + | |
| 1225 | + if (z == null || z.length < (xlen+ ylen)) | |
| 1226 | + z = new int[xlen+ylen]; | |
| 1227 | + | |
| 1228 | + long carry = 0; | |
| 1229 | + for (int j=ystart, k=ystart+1+xstart; j>=0; j--, k--) { | |
| 1230 | + long product = (y[j] & LONG_MASK) * | |
| 1231 | + (x[xstart] & LONG_MASK) + carry; | |
| 1232 | + z[k] = (int)product; | |
| 1233 | + carry = product >>> 32; | |
| 1234 | + } | |
| 1235 | + z[xstart] = (int)carry; | |
| 1236 | + | |
| 1237 | + for (int i = xstart-1; i >= 0; i--) { | |
| 1238 | + carry = 0; | |
| 1239 | + for (int j=ystart, k=ystart+1+i; j>=0; j--, k--) { | |
| 1240 | + long product = (y[j] & LONG_MASK) * | |
| 1241 | + (x[i] & LONG_MASK) + | |
| 1242 | + (z[k] & LONG_MASK) + carry; | |
| 1243 | + z[k] = (int)product; | |
| 1244 | + carry = product >>> 32; | |
| 1245 | + } | |
| 1246 | + z[i] = (int)carry; | |
| 1247 | + } | |
| 1248 | + return z; | |
| 1249 | + } | |
| 1250 | + | |
| 1251 | + /** | |
| 1252 | + * Returns a BigInteger whose value is {@code (this<sup>2</sup>)}. | |
| 1253 | + * | |
| 1254 | + * @return {@code this<sup>2</sup>} | |
| 1255 | + */ | |
| 1256 | + private BigInteger square() { | |
| 1257 | + if (signum == 0) | |
| 1258 | + return ZERO; | |
| 1259 | + int[] z = squareToLen(mag, mag.length, null); | |
| 1260 | + return new BigInteger(trustedStripLeadingZeroInts(z), 1); | |
| 1261 | + } | |
| 1262 | + | |
| 1263 | + /** | |
| 1264 | + * Squares the contents of the int array x. The result is placed into the | |
| 1265 | + * int array z. The contents of x are not changed. | |
| 1266 | + */ | |
| 1267 | + private static final int[] squareToLen(int[] x, int len, int[] z) { | |
| 1268 | + /* | |
| 1269 | + * The algorithm used here is adapted from Colin Plumb's C library. | |
| 1270 | + * Technique: Consider the partial products in the multiplication | |
| 1271 | + * of "abcde" by itself: | |
| 1272 | + * | |
| 1273 | + * a b c d e | |
| 1274 | + * * a b c d e | |
| 1275 | + * ================== | |
| 1276 | + * ae be ce de ee | |
| 1277 | + * ad bd cd dd de | |
| 1278 | + * ac bc cc cd ce | |
| 1279 | + * ab bb bc bd be | |
| 1280 | + * aa ab ac ad ae | |
| 1281 | + * | |
| 1282 | + * Note that everything above the main diagonal: | |
| 1283 | + * ae be ce de = (abcd) * e | |
| 1284 | + * ad bd cd = (abc) * d | |
| 1285 | + * ac bc = (ab) * c | |
| 1286 | + * ab = (a) * b | |
| 1287 | + * | |
| 1288 | + * is a copy of everything below the main diagonal: | |
| 1289 | + * de | |
| 1290 | + * cd ce | |
| 1291 | + * bc bd be | |
| 1292 | + * ab ac ad ae | |
| 1293 | + * | |
| 1294 | + * Thus, the sum is 2 * (off the diagonal) + diagonal. | |
| 1295 | + * | |
| 1296 | + * This is accumulated beginning with the diagonal (which | |
| 1297 | + * consist of the squares of the digits of the input), which is then | |
| 1298 | + * divided by two, the off-diagonal added, and multiplied by two | |
| 1299 | + * again. The low bit is simply a copy of the low bit of the | |
| 1300 | + * input, so it doesn't need special care. | |
| 1301 | + */ | |
| 1302 | + int zlen = len << 1; | |
| 1303 | + if (z == null || z.length < zlen) | |
| 1304 | + z = new int[zlen]; | |
| 1305 | + | |
| 1306 | + // Store the squares, right shifted one bit (i.e., divided by 2) | |
| 1307 | + int lastProductLowWord = 0; | |
| 1308 | + for (int j=0, i=0; j<len; j++) { | |
| 1309 | + long piece = (x[j] & LONG_MASK); | |
| 1310 | + long product = piece * piece; | |
| 1311 | + z[i++] = (lastProductLowWord << 31) | (int)(product >>> 33); | |
| 1312 | + z[i++] = (int)(product >>> 1); | |
| 1313 | + lastProductLowWord = (int)product; | |
| 1314 | + } | |
| 1315 | + | |
| 1316 | + // Add in off-diagonal sums | |
| 1317 | + for (int i=len, offset=1; i>0; i--, offset+=2) { | |
| 1318 | + int t = x[i-1]; | |
| 1319 | + t = mulAdd(z, x, offset, i-1, t); | |
| 1320 | + addOne(z, offset-1, i, t); | |
| 1321 | + } | |
| 1322 | + | |
| 1323 | + // Shift back up and set low bit | |
| 1324 | + primitiveLeftShift(z, zlen, 1); | |
| 1325 | + z[zlen-1] |= x[len-1] & 1; | |
| 1326 | + | |
| 1327 | + return z; | |
| 1328 | + } | |
| 1329 | + | |
| 1330 | + /** | |
| 1331 | + * Returns a BigInteger whose value is {@code (this / val)}. | |
| 1332 | + * | |
| 1333 | + * @param val value by which this BigInteger is to be divided. | |
| 1334 | + * @return {@code this / val} | |
| 1335 | + * @throws ArithmeticException if {@code val} is zero. | |
| 1336 | + */ | |
| 1337 | + public BigInteger divide(BigInteger val) { | |
| 1338 | + MutableBigInteger q = new MutableBigInteger(), | |
| 1339 | + a = new MutableBigInteger(this.mag), | |
| 1340 | + b = new MutableBigInteger(val.mag); | |
| 1341 | + | |
| 1342 | + a.divide(b, q); | |
| 1343 | + return q.toBigInteger(this.signum == val.signum ? 1 : -1); | |
| 1344 | + } | |
| 1345 | + | |
| 1346 | + /** | |
| 1347 | + * Returns an array of two BigIntegers containing {@code (this / val)} | |
| 1348 | + * followed by {@code (this % val)}. | |
| 1349 | + * | |
| 1350 | + * @param val value by which this BigInteger is to be divided, and the | |
| 1351 | + * remainder computed. | |
| 1352 | + * @return an array of two BigIntegers: the quotient {@code (this / val)} | |
| 1353 | + * is the initial element, and the remainder {@code (this % val)} | |
| 1354 | + * is the final element. | |
| 1355 | + * @throws ArithmeticException if {@code val} is zero. | |
| 1356 | + */ | |
| 1357 | + public BigInteger[] divideAndRemainder(BigInteger val) { | |
| 1358 | + BigInteger[] result = new BigInteger[2]; | |
| 1359 | + MutableBigInteger q = new MutableBigInteger(), | |
| 1360 | + a = new MutableBigInteger(this.mag), | |
| 1361 | + b = new MutableBigInteger(val.mag); | |
| 1362 | + MutableBigInteger r = a.divide(b, q); | |
| 1363 | + result[0] = q.toBigInteger(this.signum == val.signum ? 1 : -1); | |
| 1364 | + result[1] = r.toBigInteger(this.signum); | |
| 1365 | + return result; | |
| 1366 | + } | |
| 1367 | + | |
| 1368 | + /** | |
| 1369 | + * Returns a BigInteger whose value is {@code (this % val)}. | |
| 1370 | + * | |
| 1371 | + * @param val value by which this BigInteger is to be divided, and the | |
| 1372 | + * remainder computed. | |
| 1373 | + * @return {@code this % val} | |
| 1374 | + * @throws ArithmeticException if {@code val} is zero. | |
| 1375 | + */ | |
| 1376 | + public BigInteger remainder(BigInteger val) { | |
| 1377 | + MutableBigInteger q = new MutableBigInteger(), | |
| 1378 | + a = new MutableBigInteger(this.mag), | |
| 1379 | + b = new MutableBigInteger(val.mag); | |
| 1380 | + | |
| 1381 | + return a.divide(b, q).toBigInteger(this.signum); | |
| 1382 | + } | |
| 1383 | + | |
| 1384 | + /** | |
| 1385 | + * Returns a BigInteger whose value is <tt>(this<sup>exponent</sup>)</tt>. | |
| 1386 | + * Note that {@code exponent} is an integer rather than a BigInteger. | |
| 1387 | + * | |
| 1388 | + * @param exponent exponent to which this BigInteger is to be raised. | |
| 1389 | + * @return <tt>this<sup>exponent</sup></tt> | |
| 1390 | + * @throws ArithmeticException {@code exponent} is negative. (This would | |
| 1391 | + * cause the operation to yield a non-integer value.) | |
| 1392 | + */ | |
| 1393 | + public BigInteger pow(int exponent) { | |
| 1394 | + if (exponent < 0) | |
| 1395 | + throw new ArithmeticException("Negative exponent"); | |
| 1396 | + if (signum==0) | |
| 1397 | + return (exponent==0 ? ONE : this); | |
| 1398 | + | |
| 1399 | + // Perform exponentiation using repeated squaring trick | |
| 1400 | + int newSign = (signum<0 && (exponent&1)==1 ? -1 : 1); | |
| 1401 | + int[] baseToPow2 = this.mag; | |
| 1402 | + int[] result = {1}; | |
| 1403 | + | |
| 1404 | + while (exponent != 0) { | |
| 1405 | + if ((exponent & 1)==1) { | |
| 1406 | + result = multiplyToLen(result, result.length, | |
| 1407 | + baseToPow2, baseToPow2.length, null); | |
| 1408 | + result = trustedStripLeadingZeroInts(result); | |
| 1409 | + } | |
| 1410 | + if ((exponent >>>= 1) != 0) { | |
| 1411 | + baseToPow2 = squareToLen(baseToPow2, baseToPow2.length, null); | |
| 1412 | + baseToPow2 = trustedStripLeadingZeroInts(baseToPow2); | |
| 1413 | + } | |
| 1414 | + } | |
| 1415 | + return new BigInteger(result, newSign); | |
| 1416 | + } | |
| 1417 | + | |
| 1418 | + /** | |
| 1419 | + * Returns a BigInteger whose value is the greatest common divisor of | |
| 1420 | + * {@code abs(this)} and {@code abs(val)}. Returns 0 if | |
| 1421 | + * {@code this==0 && val==0}. | |
| 1422 | + * | |
| 1423 | + * @param val value with which the GCD is to be computed. | |
| 1424 | + * @return {@code GCD(abs(this), abs(val))} | |
| 1425 | + */ | |
| 1426 | + public BigInteger gcd(BigInteger val) { | |
| 1427 | + if (val.signum == 0) | |
| 1428 | + return this.abs(); | |
| 1429 | + else if (this.signum == 0) | |
| 1430 | + return val.abs(); | |
| 1431 | + | |
| 1432 | + MutableBigInteger a = new MutableBigInteger(this); | |
| 1433 | + MutableBigInteger b = new MutableBigInteger(val); | |
| 1434 | + | |
| 1435 | + MutableBigInteger result = a.hybridGCD(b); | |
| 1436 | + | |
| 1437 | + return result.toBigInteger(1); | |
| 1438 | + } | |
| 1439 | + | |
| 1440 | + /** | |
| 1441 | + * Package private method to return bit length for an integer. | |
| 1442 | + */ | |
| 1443 | + static int bitLengthForInt(int n) { | |
| 1444 | + return 32 - Integer.numberOfLeadingZeros(n); | |
| 1445 | + } | |
| 1446 | + | |
| 1447 | + /** | |
| 1448 | + * Left shift int array a up to len by n bits. Returns the array that | |
| 1449 | + * results from the shift since space may have to be reallocated. | |
| 1450 | + */ | |
| 1451 | + private static int[] leftShift(int[] a, int len, int n) { | |
| 1452 | + int nInts = n >>> 5; | |
| 1453 | + int nBits = n&0x1F; | |
| 1454 | + int bitsInHighWord = bitLengthForInt(a[0]); | |
| 1455 | + | |
| 1456 | + // If shift can be done without recopy, do so | |
| 1457 | + if (n <= (32-bitsInHighWord)) { | |
| 1458 | + primitiveLeftShift(a, len, nBits); | |
| 1459 | + return a; | |
| 1460 | + } else { // Array must be resized | |
| 1461 | + if (nBits <= (32-bitsInHighWord)) { | |
| 1462 | + int result[] = new int[nInts+len]; | |
| 1463 | + for (int i=0; i<len; i++) | |
| 1464 | + result[i] = a[i]; | |
| 1465 | + primitiveLeftShift(result, result.length, nBits); | |
| 1466 | + return result; | |
| 1467 | + } else { | |
| 1468 | + int result[] = new int[nInts+len+1]; | |
| 1469 | + for (int i=0; i<len; i++) | |
| 1470 | + result[i] = a[i]; | |
| 1471 | + primitiveRightShift(result, result.length, 32 - nBits); | |
| 1472 | + return result; | |
| 1473 | + } | |
| 1474 | + } | |
| 1475 | + } | |
| 1476 | + | |
| 1477 | + // shifts a up to len right n bits assumes no leading zeros, 0<n<32 | |
| 1478 | + static void primitiveRightShift(int[] a, int len, int n) { | |
| 1479 | + int n2 = 32 - n; | |
| 1480 | + for (int i=len-1, c=a[i]; i>0; i--) { | |
| 1481 | + int b = c; | |
| 1482 | + c = a[i-1]; | |
| 1483 | + a[i] = (c << n2) | (b >>> n); | |
| 1484 | + } | |
| 1485 | + a[0] >>>= n; | |
| 1486 | + } | |
| 1487 | + | |
| 1488 | + // shifts a up to len left n bits assumes no leading zeros, 0<=n<32 | |
| 1489 | + static void primitiveLeftShift(int[] a, int len, int n) { | |
| 1490 | + if (len == 0 || n == 0) | |
| 1491 | + return; | |
| 1492 | + | |
| 1493 | + int n2 = 32 - n; | |
| 1494 | + for (int i=0, c=a[i], m=i+len-1; i<m; i++) { | |
| 1495 | + int b = c; | |
| 1496 | + c = a[i+1]; | |
| 1497 | + a[i] = (b << n) | (c >>> n2); | |
| 1498 | + } | |
| 1499 | + a[len-1] <<= n; | |
| 1500 | + } | |
| 1501 | + | |
| 1502 | + /** | |
| 1503 | + * Calculate bitlength of contents of the first len elements an int array, | |
| 1504 | + * assuming there are no leading zero ints. | |
| 1505 | + */ | |
| 1506 | + private static int bitLength(int[] val, int len) { | |
| 1507 | + if (len == 0) | |
| 1508 | + return 0; | |
| 1509 | + return ((len - 1) << 5) + bitLengthForInt(val[0]); | |
| 1510 | + } | |
| 1511 | + | |
| 1512 | + /** | |
| 1513 | + * Returns a BigInteger whose value is the absolute value of this | |
| 1514 | + * BigInteger. | |
| 1515 | + * | |
| 1516 | + * @return {@code abs(this)} | |
| 1517 | + */ | |
| 1518 | + public BigInteger abs() { | |
| 1519 | + return (signum >= 0 ? this : this.negate()); | |
| 1520 | + } | |
| 1521 | + | |
| 1522 | + /** | |
| 1523 | + * Returns a BigInteger whose value is {@code (-this)}. | |
| 1524 | + * | |
| 1525 | + * @return {@code -this} | |
| 1526 | + */ | |
| 1527 | + public BigInteger negate() { | |
| 1528 | + return new BigInteger(this.mag, -this.signum); | |
| 1529 | + } | |
| 1530 | + | |
| 1531 | + /** | |
| 1532 | + * Returns the signum function of this BigInteger. | |
| 1533 | + * | |
| 1534 | + * @return -1, 0 or 1 as the value of this BigInteger is negative, zero or | |
| 1535 | + * positive. | |
| 1536 | + */ | |
| 1537 | + public int signum() { | |
| 1538 | + return this.signum; | |
| 1539 | + } | |
| 1540 | + | |
| 1541 | + // Modular Arithmetic Operations | |
| 1542 | + | |
| 1543 | + /** | |
| 1544 | + * Returns a BigInteger whose value is {@code (this mod m}). This method | |
| 1545 | + * differs from {@code remainder} in that it always returns a | |
| 1546 | + * <i>non-negative</i> BigInteger. | |
| 1547 | + * | |
| 1548 | + * @param m the modulus. | |
| 1549 | + * @return {@code this mod m} | |
| 1550 | + * @throws ArithmeticException {@code m} ≤ 0 | |
| 1551 | + * @see #remainder | |
| 1552 | + */ | |
| 1553 | + public BigInteger mod(BigInteger m) { | |
| 1554 | + if (m.signum <= 0) | |
| 1555 | + throw new ArithmeticException("BigInteger: modulus not positive"); | |
| 1556 | + | |
| 1557 | + BigInteger result = this.remainder(m); | |
| 1558 | + return (result.signum >= 0 ? result : result.add(m)); | |
| 1559 | + } | |
| 1560 | + | |
| 1561 | + /** | |
| 1562 | + * Returns a BigInteger whose value is | |
| 1563 | + * <tt>(this<sup>exponent</sup> mod m)</tt>. (Unlike {@code pow}, this | |
| 1564 | + * method permits negative exponents.) | |
| 1565 | + * | |
| 1566 | + * @param exponent the exponent. | |
| 1567 | + * @param m the modulus. | |
| 1568 | + * @return <tt>this<sup>exponent</sup> mod m</tt> | |
| 1569 | + * @throws ArithmeticException {@code m} ≤ 0 or the exponent is | |
| 1570 | + * negative and this BigInteger is not <i>relatively | |
| 1571 | + * prime</i> to {@code m}. | |
| 1572 | + * @see #modInverse | |
| 1573 | + */ | |
| 1574 | + public BigInteger modPow(BigInteger exponent, BigInteger m) { | |
| 1575 | + if (m.signum <= 0) | |
| 1576 | + throw new ArithmeticException("BigInteger: modulus not positive"); | |
| 1577 | + | |
| 1578 | + // Trivial cases | |
| 1579 | + if (exponent.signum == 0) | |
| 1580 | + return (m.equals(ONE) ? ZERO : ONE); | |
| 1581 | + | |
| 1582 | + if (this.equals(ONE)) | |
| 1583 | + return (m.equals(ONE) ? ZERO : ONE); | |
| 1584 | + | |
| 1585 | + if (this.equals(ZERO) && exponent.signum >= 0) | |
| 1586 | + return ZERO; | |
| 1587 | + | |
| 1588 | + if (this.equals(negConst[1]) && (!exponent.testBit(0))) | |
| 1589 | + return (m.equals(ONE) ? ZERO : ONE); | |
| 1590 | + | |
| 1591 | + boolean invertResult; | |
| 1592 | + if ((invertResult = (exponent.signum < 0))) | |
| 1593 | + exponent = exponent.negate(); | |
| 1594 | + | |
| 1595 | + BigInteger base = (this.signum < 0 || this.compareTo(m) >= 0 | |
| 1596 | + ? this.mod(m) : this); | |
| 1597 | + BigInteger result; | |
| 1598 | + if (m.testBit(0)) { // odd modulus | |
| 1599 | + result = base.oddModPow(exponent, m); | |
| 1600 | + } else { | |
| 1601 | + /* | |
| 1602 | + * Even modulus. Tear it into an "odd part" (m1) and power of two | |
| 1603 | + * (m2), exponentiate mod m1, manually exponentiate mod m2, and | |
| 1604 | + * use Chinese Remainder Theorem to combine results. | |
| 1605 | + */ | |
| 1606 | + | |
| 1607 | + // Tear m apart into odd part (m1) and power of 2 (m2) | |
| 1608 | + int p = m.getLowestSetBit(); // Max pow of 2 that divides m | |
| 1609 | + | |
| 1610 | + BigInteger m1 = m.shiftRight(p); // m/2**p | |
| 1611 | + BigInteger m2 = ONE.shiftLeft(p); // 2**p | |
| 1612 | + | |
| 1613 | + // Calculate new base from m1 | |
| 1614 | + BigInteger base2 = (this.signum < 0 || this.compareTo(m1) >= 0 | |
| 1615 | + ? this.mod(m1) : this); | |
| 1616 | + | |
| 1617 | + // Caculate (base ** exponent) mod m1. | |
| 1618 | + BigInteger a1 = (m1.equals(ONE) ? ZERO : | |
| 1619 | + base2.oddModPow(exponent, m1)); | |
| 1620 | + | |
| 1621 | + // Calculate (this ** exponent) mod m2 | |
| 1622 | + BigInteger a2 = base.modPow2(exponent, p); | |
| 1623 | + | |
| 1624 | + // Combine results using Chinese Remainder Theorem | |
| 1625 | + BigInteger y1 = m2.modInverse(m1); | |
| 1626 | + BigInteger y2 = m1.modInverse(m2); | |
| 1627 | + | |
| 1628 | + result = a1.multiply(m2).multiply(y1).add | |
| 1629 | + (a2.multiply(m1).multiply(y2)).mod(m); | |
| 1630 | + } | |
| 1631 | + | |
| 1632 | + return (invertResult ? result.modInverse(m) : result); | |
| 1633 | + } | |
| 1634 | + | |
| 1635 | + static int[] bnExpModThreshTable = {7, 25, 81, 241, 673, 1793, | |
| 1636 | + Integer.MAX_VALUE}; // Sentinel | |
| 1637 | + | |
| 1638 | + /** | |
| 1639 | + * Returns a BigInteger whose value is x to the power of y mod z. | |
| 1640 | + * Assumes: z is odd && x < z. | |
| 1641 | + */ | |
| 1642 | + private BigInteger oddModPow(BigInteger y, BigInteger z) { | |
| 1643 | + /* | |
| 1644 | + * The algorithm is adapted from Colin Plumb's C library. | |
| 1645 | + * | |
| 1646 | + * The window algorithm: | |
| 1647 | + * The idea is to keep a running product of b1 = n^(high-order bits of exp) | |
| 1648 | + * and then keep appending exponent bits to it. The following patterns | |
| 1649 | + * apply to a 3-bit window (k = 3): | |
| 1650 | + * To append 0: square | |
| 1651 | + * To append 1: square, multiply by n^1 | |
| 1652 | + * To append 10: square, multiply by n^1, square | |
| 1653 | + * To append 11: square, square, multiply by n^3 | |
| 1654 | + * To append 100: square, multiply by n^1, square, square | |
| 1655 | + * To append 101: square, square, square, multiply by n^5 | |
| 1656 | + * To append 110: square, square, multiply by n^3, square | |
| 1657 | + * To append 111: square, square, square, multiply by n^7 | |
| 1658 | + * | |
| 1659 | + * Since each pattern involves only one multiply, the longer the pattern | |
| 1660 | + * the better, except that a 0 (no multiplies) can be appended directly. | |
| 1661 | + * We precompute a table of odd powers of n, up to 2^k, and can then | |
| 1662 | + * multiply k bits of exponent at a time. Actually, assuming random | |
| 1663 | + * exponents, there is on average one zero bit between needs to | |
| 1664 | + * multiply (1/2 of the time there's none, 1/4 of the time there's 1, | |
| 1665 | + * 1/8 of the time, there's 2, 1/32 of the time, there's 3, etc.), so | |
| 1666 | + * you have to do one multiply per k+1 bits of exponent. | |
| 1667 | + * | |
| 1668 | + * The loop walks down the exponent, squaring the result buffer as | |
| 1669 | + * it goes. There is a wbits+1 bit lookahead buffer, buf, that is | |
| 1670 | + * filled with the upcoming exponent bits. (What is read after the | |
| 1671 | + * end of the exponent is unimportant, but it is filled with zero here.) | |
| 1672 | + * When the most-significant bit of this buffer becomes set, i.e. | |
| 1673 | + * (buf & tblmask) != 0, we have to decide what pattern to multiply | |
| 1674 | + * by, and when to do it. We decide, remember to do it in future | |
| 1675 | + * after a suitable number of squarings have passed (e.g. a pattern | |
| 1676 | + * of "100" in the buffer requires that we multiply by n^1 immediately; | |
| 1677 | + * a pattern of "110" calls for multiplying by n^3 after one more | |
| 1678 | + * squaring), clear the buffer, and continue. | |
| 1679 | + * | |
| 1680 | + * When we start, there is one more optimization: the result buffer | |
| 1681 | + * is implcitly one, so squaring it or multiplying by it can be | |
| 1682 | + * optimized away. Further, if we start with a pattern like "100" | |
| 1683 | + * in the lookahead window, rather than placing n into the buffer | |
| 1684 | + * and then starting to square it, we have already computed n^2 | |
| 1685 | + * to compute the odd-powers table, so we can place that into | |
| 1686 | + * the buffer and save a squaring. | |
| 1687 | + * | |
| 1688 | + * This means that if you have a k-bit window, to compute n^z, | |
| 1689 | + * where z is the high k bits of the exponent, 1/2 of the time | |
| 1690 | + * it requires no squarings. 1/4 of the time, it requires 1 | |
| 1691 | + * squaring, ... 1/2^(k-1) of the time, it reqires k-2 squarings. | |
| 1692 | + * And the remaining 1/2^(k-1) of the time, the top k bits are a | |
| 1693 | + * 1 followed by k-1 0 bits, so it again only requires k-2 | |
| 1694 | + * squarings, not k-1. The average of these is 1. Add that | |
| 1695 | + * to the one squaring we have to do to compute the table, | |
| 1696 | + * and you'll see that a k-bit window saves k-2 squarings | |
| 1697 | + * as well as reducing the multiplies. (It actually doesn't | |
| 1698 | + * hurt in the case k = 1, either.) | |
| 1699 | + */ | |
| 1700 | + // Special case for exponent of one | |
| 1701 | + if (y.equals(ONE)) | |
| 1702 | + return this; | |
| 1703 | + | |
| 1704 | + // Special case for base of zero | |
| 1705 | + if (signum==0) | |
| 1706 | + return ZERO; | |
| 1707 | + | |
| 1708 | + int[] base = mag.clone(); | |
| 1709 | + int[] exp = y.mag; | |
| 1710 | + int[] mod = z.mag; | |
| 1711 | + int modLen = mod.length; | |
| 1712 | + | |
| 1713 | + // Select an appropriate window size | |
| 1714 | + int wbits = 0; | |
| 1715 | + int ebits = bitLength(exp, exp.length); | |
| 1716 | + // if exponent is 65537 (0x10001), use minimum window size | |
| 1717 | + if ((ebits != 17) || (exp[0] != 65537)) { | |
| 1718 | + while (ebits > bnExpModThreshTable[wbits]) { | |
| 1719 | + wbits++; | |
| 1720 | + } | |
| 1721 | + } | |
| 1722 | + | |
| 1723 | + // Calculate appropriate table size | |
| 1724 | + int tblmask = 1 << wbits; | |
| 1725 | + | |
| 1726 | + // Allocate table for precomputed odd powers of base in Montgomery form | |
| 1727 | + int[][] table = new int[tblmask][]; | |
| 1728 | + for (int i=0; i<tblmask; i++) | |
| 1729 | + table[i] = new int[modLen]; | |
| 1730 | + | |
| 1731 | + // Compute the modular inverse | |
| 1732 | + int inv = -MutableBigInteger.inverseMod32(mod[modLen-1]); | |
| 1733 | + | |
| 1734 | + // Convert base to Montgomery form | |
| 1735 | + int[] a = leftShift(base, base.length, modLen << 5); | |
| 1736 | + | |
| 1737 | + MutableBigInteger q = new MutableBigInteger(), | |
| 1738 | + a2 = new MutableBigInteger(a), | |
| 1739 | + b2 = new MutableBigInteger(mod); | |
| 1740 | + | |
| 1741 | + MutableBigInteger r= a2.divide(b2, q); | |
| 1742 | + table[0] = r.toIntArray(); | |
| 1743 | + | |
| 1744 | + // Pad table[0] with leading zeros so its length is at least modLen | |
| 1745 | + if (table[0].length < modLen) { | |
| 1746 | + int offset = modLen - table[0].length; | |
| 1747 | + int[] t2 = new int[modLen]; | |
| 1748 | + for (int i=0; i<table[0].length; i++) | |
| 1749 | + t2[i+offset] = table[0][i]; | |
| 1750 | + table[0] = t2; | |
| 1751 | + } | |
| 1752 | + | |
| 1753 | + // Set b to the square of the base | |
| 1754 | + int[] b = squareToLen(table[0], modLen, null); | |
| 1755 | + b = montReduce(b, mod, modLen, inv); | |
| 1756 | + | |
| 1757 | + // Set t to high half of b | |
| 1758 | + int[] t = new int[modLen]; | |
| 1759 | + for(int i=0; i<modLen; i++) | |
| 1760 | + t[i] = b[i]; | |
| 1761 | + | |
| 1762 | + // Fill in the table with odd powers of the base | |
| 1763 | + for (int i=1; i<tblmask; i++) { | |
| 1764 | + int[] prod = multiplyToLen(t, modLen, table[i-1], modLen, null); | |
| 1765 | + table[i] = montReduce(prod, mod, modLen, inv); | |
| 1766 | + } | |
| 1767 | + | |
| 1768 | + // Pre load the window that slides over the exponent | |
| 1769 | + int bitpos = 1 << ((ebits-1) & (32-1)); | |
| 1770 | + | |
| 1771 | + int buf = 0; | |
| 1772 | + int elen = exp.length; | |
| 1773 | + int eIndex = 0; | |
| 1774 | + for (int i = 0; i <= wbits; i++) { | |
| 1775 | + buf = (buf << 1) | (((exp[eIndex] & bitpos) != 0)?1:0); | |
| 1776 | + bitpos >>>= 1; | |
| 1777 | + if (bitpos == 0) { | |
| 1778 | + eIndex++; | |
| 1779 | + bitpos = 1 << (32-1); | |
| 1780 | + elen--; | |
| 1781 | + } | |
| 1782 | + } | |
| 1783 | + | |
| 1784 | + int multpos = ebits; | |
| 1785 | + | |
| 1786 | + // The first iteration, which is hoisted out of the main loop | |
| 1787 | + ebits--; | |
| 1788 | + boolean isone = true; | |
| 1789 | + | |
| 1790 | + multpos = ebits - wbits; | |
| 1791 | + while ((buf & 1) == 0) { | |
| 1792 | + buf >>>= 1; | |
| 1793 | + multpos++; | |
| 1794 | + } | |
| 1795 | + | |
| 1796 | + int[] mult = table[buf >>> 1]; | |
| 1797 | + | |
| 1798 | + buf = 0; | |
| 1799 | + if (multpos == ebits) | |
| 1800 | + isone = false; | |
| 1801 | + | |
| 1802 | + // The main loop | |
| 1803 | + while(true) { | |
| 1804 | + ebits--; | |
| 1805 | + // Advance the window | |
| 1806 | + buf <<= 1; | |
| 1807 | + | |
| 1808 | + if (elen != 0) { | |
| 1809 | + buf |= ((exp[eIndex] & bitpos) != 0) ? 1 : 0; | |
| 1810 | + bitpos >>>= 1; | |
| 1811 | + if (bitpos == 0) { | |
| 1812 | + eIndex++; | |
| 1813 | + bitpos = 1 << (32-1); | |
| 1814 | + elen--; | |
| 1815 | + } | |
| 1816 | + } | |
| 1817 | + | |
| 1818 | + // Examine the window for pending multiplies | |
| 1819 | + if ((buf & tblmask) != 0) { | |
| 1820 | + multpos = ebits - wbits; | |
| 1821 | + while ((buf & 1) == 0) { | |
| 1822 | + buf >>>= 1; | |
| 1823 | + multpos++; | |
| 1824 | + } | |
| 1825 | + mult = table[buf >>> 1]; | |
| 1826 | + buf = 0; | |
| 1827 | + } | |
| 1828 | + | |
| 1829 | + // Perform multiply | |
| 1830 | + if (ebits == multpos) { | |
| 1831 | + if (isone) { | |
| 1832 | + b = mult.clone(); | |
| 1833 | + isone = false; | |
| 1834 | + } else { | |
| 1835 | + t = b; | |
| 1836 | + a = multiplyToLen(t, modLen, mult, modLen, a); | |
| 1837 | + a = montReduce(a, mod, modLen, inv); | |
| 1838 | + t = a; a = b; b = t; | |
| 1839 | + } | |
| 1840 | + } | |
| 1841 | + | |
| 1842 | + // Check if done | |
| 1843 | + if (ebits == 0) | |
| 1844 | + break; | |
| 1845 | + | |
| 1846 | + // Square the input | |
| 1847 | + if (!isone) { | |
| 1848 | + t = b; | |
| 1849 | + a = squareToLen(t, modLen, a); | |
| 1850 | + a = montReduce(a, mod, modLen, inv); | |
| 1851 | + t = a; a = b; b = t; | |
| 1852 | + } | |
| 1853 | + } | |
| 1854 | + | |
| 1855 | + // Convert result out of Montgomery form and return | |
| 1856 | + int[] t2 = new int[2*modLen]; | |
| 1857 | + for(int i=0; i<modLen; i++) | |
| 1858 | + t2[i+modLen] = b[i]; | |
| 1859 | + | |
| 1860 | + b = montReduce(t2, mod, modLen, inv); | |
| 1861 | + | |
| 1862 | + t2 = new int[modLen]; | |
| 1863 | + for(int i=0; i<modLen; i++) | |
| 1864 | + t2[i] = b[i]; | |
| 1865 | + | |
| 1866 | + return new BigInteger(1, t2); | |
| 1867 | + } | |
| 1868 | + | |
| 1869 | + /** | |
| 1870 | + * Montgomery reduce n, modulo mod. This reduces modulo mod and divides | |
| 1871 | + * by 2^(32*mlen). Adapted from Colin Plumb's C library. | |
| 1872 | + */ | |
| 1873 | + private static int[] montReduce(int[] n, int[] mod, int mlen, int inv) { | |
| 1874 | + int c=0; | |
| 1875 | + int len = mlen; | |
| 1876 | + int offset=0; | |
| 1877 | + | |
| 1878 | + do { | |
| 1879 | + int nEnd = n[n.length-1-offset]; | |
| 1880 | + int carry = mulAdd(n, mod, offset, mlen, inv * nEnd); | |
| 1881 | + c += addOne(n, offset, mlen, carry); | |
| 1882 | + offset++; | |
| 1883 | + } while(--len > 0); | |
| 1884 | + | |
| 1885 | + while(c>0) | |
| 1886 | + c += subN(n, mod, mlen); | |
| 1887 | + | |
| 1888 | + while (intArrayCmpToLen(n, mod, mlen) >= 0) | |
| 1889 | + subN(n, mod, mlen); | |
| 1890 | + | |
| 1891 | + return n; | |
| 1892 | + } | |
| 1893 | + | |
| 1894 | + | |
| 1895 | + /* | |
| 1896 | + * Returns -1, 0 or +1 as big-endian unsigned int array arg1 is less than, | |
| 1897 | + * equal to, or greater than arg2 up to length len. | |
| 1898 | + */ | |
| 1899 | + private static int intArrayCmpToLen(int[] arg1, int[] arg2, int len) { | |
| 1900 | + for (int i=0; i<len; i++) { | |
| 1901 | + long b1 = arg1[i] & LONG_MASK; | |
| 1902 | + long b2 = arg2[i] & LONG_MASK; | |
| 1903 | + if (b1 < b2) | |
| 1904 | + return -1; | |
| 1905 | + if (b1 > b2) | |
| 1906 | + return 1; | |
| 1907 | + } | |
| 1908 | + return 0; | |
| 1909 | + } | |
| 1910 | + | |
| 1911 | + /** | |
| 1912 | + * Subtracts two numbers of same length, returning borrow. | |
| 1913 | + */ | |
| 1914 | + private static int subN(int[] a, int[] b, int len) { | |
| 1915 | + long sum = 0; | |
| 1916 | + | |
| 1917 | + while(--len >= 0) { | |
| 1918 | + sum = (a[len] & LONG_MASK) - | |
| 1919 | + (b[len] & LONG_MASK) + (sum >> 32); | |
| 1920 | + a[len] = (int)sum; | |
| 1921 | + } | |
| 1922 | + | |
| 1923 | + return (int)(sum >> 32); | |
| 1924 | + } | |
| 1925 | + | |
| 1926 | + /** | |
| 1927 | + * Multiply an array by one word k and add to result, return the carry | |
| 1928 | + */ | |
| 1929 | + static int mulAdd(int[] out, int[] in, int offset, int len, int k) { | |
| 1930 | + long kLong = k & LONG_MASK; | |
| 1931 | + long carry = 0; | |
| 1932 | + | |
| 1933 | + offset = out.length-offset - 1; | |
| 1934 | + for (int j=len-1; j >= 0; j--) { | |
| 1935 | + long product = (in[j] & LONG_MASK) * kLong + | |
| 1936 | + (out[offset] & LONG_MASK) + carry; | |
| 1937 | + out[offset--] = (int)product; | |
| 1938 | + carry = product >>> 32; | |
| 1939 | + } | |
| 1940 | + return (int)carry; | |
| 1941 | + } | |
| 1942 | + | |
| 1943 | + /** | |
| 1944 | + * Add one word to the number a mlen words into a. Return the resulting | |
| 1945 | + * carry. | |
| 1946 | + */ | |
| 1947 | + static int addOne(int[] a, int offset, int mlen, int carry) { | |
| 1948 | + offset = a.length-1-mlen-offset; | |
| 1949 | + long t = (a[offset] & LONG_MASK) + (carry & LONG_MASK); | |
| 1950 | + | |
| 1951 | + a[offset] = (int)t; | |
| 1952 | + if ((t >>> 32) == 0) | |
| 1953 | + return 0; | |
| 1954 | + while (--mlen >= 0) { | |
| 1955 | + if (--offset < 0) { // Carry out of number | |
| 1956 | + return 1; | |
| 1957 | + } else { | |
| 1958 | + a[offset]++; | |
| 1959 | + if (a[offset] != 0) | |
| 1960 | + return 0; | |
| 1961 | + } | |
| 1962 | + } | |
| 1963 | + return 1; | |
| 1964 | + } | |
| 1965 | + | |
| 1966 | + /** | |
| 1967 | + * Returns a BigInteger whose value is (this ** exponent) mod (2**p) | |
| 1968 | + */ | |
| 1969 | + private BigInteger modPow2(BigInteger exponent, int p) { | |
| 1970 | + /* | |
| 1971 | + * Perform exponentiation using repeated squaring trick, chopping off | |
| 1972 | + * high order bits as indicated by modulus. | |
| 1973 | + */ | |
| 1974 | + BigInteger result = valueOf(1); | |
| 1975 | + BigInteger baseToPow2 = this.mod2(p); | |
| 1976 | + int expOffset = 0; | |
| 1977 | + | |
| 1978 | + int limit = exponent.bitLength(); | |
| 1979 | + | |
| 1980 | + if (this.testBit(0)) | |
| 1981 | + limit = (p-1) < limit ? (p-1) : limit; | |
| 1982 | + | |
| 1983 | + while (expOffset < limit) { | |
| 1984 | + if (exponent.testBit(expOffset)) | |
| 1985 | + result = result.multiply(baseToPow2).mod2(p); | |
| 1986 | + expOffset++; | |
| 1987 | + if (expOffset < limit) | |
| 1988 | + baseToPow2 = baseToPow2.square().mod2(p); | |
| 1989 | + } | |
| 1990 | + | |
| 1991 | + return result; | |
| 1992 | + } | |
| 1993 | + | |
| 1994 | + /** | |
| 1995 | + * Returns a BigInteger whose value is this mod(2**p). | |
| 1996 | + * Assumes that this {@code BigInteger >= 0} and {@code p > 0}. | |
| 1997 | + */ | |
| 1998 | + private BigInteger mod2(int p) { | |
| 1999 | + if (bitLength() <= p) | |
| 2000 | + return this; | |
| 2001 | + | |
| 2002 | + // Copy remaining ints of mag | |
| 2003 | + int numInts = (p + 31) >>> 5; | |
| 2004 | + int[] mag = new int[numInts]; | |
| 2005 | + for (int i=0; i<numInts; i++) | |
| 2006 | + mag[i] = this.mag[i + (this.mag.length - numInts)]; | |
| 2007 | + | |
| 2008 | + // Mask out any excess bits | |
| 2009 | + int excessBits = (numInts << 5) - p; | |
| 2010 | + mag[0] &= (1L << (32-excessBits)) - 1; | |
| 2011 | + | |
| 2012 | + return (mag[0]==0 ? new BigInteger(1, mag) : new BigInteger(mag, 1)); | |
| 2013 | + } | |
| 2014 | + | |
| 2015 | + /** | |
| 2016 | + * Returns a BigInteger whose value is {@code (this}<sup>-1</sup> {@code mod m)}. | |
| 2017 | + * | |
| 2018 | + * @param m the modulus. | |
| 2019 | + * @return {@code this}<sup>-1</sup> {@code mod m}. | |
| 2020 | + * @throws ArithmeticException {@code m} ≤ 0, or this BigInteger | |
| 2021 | + * has no multiplicative inverse mod m (that is, this BigInteger | |
| 2022 | + * is not <i>relatively prime</i> to m). | |
| 2023 | + */ | |
| 2024 | + public BigInteger modInverse(BigInteger m) { | |
| 2025 | + if (m.signum != 1) | |
| 2026 | + throw new ArithmeticException("BigInteger: modulus not positive"); | |
| 2027 | + | |
| 2028 | + if (m.equals(ONE)) | |
| 2029 | + return ZERO; | |
| 2030 | + | |
| 2031 | + // Calculate (this mod m) | |
| 2032 | + BigInteger modVal = this; | |
| 2033 | + if (signum < 0 || (this.compareMagnitude(m) >= 0)) | |
| 2034 | + modVal = this.mod(m); | |
| 2035 | + | |
| 2036 | + if (modVal.equals(ONE)) | |
| 2037 | + return ONE; | |
| 2038 | + | |
| 2039 | + MutableBigInteger a = new MutableBigInteger(modVal); | |
| 2040 | + MutableBigInteger b = new MutableBigInteger(m); | |
| 2041 | + | |
| 2042 | + MutableBigInteger result = a.mutableModInverse(b); | |
| 2043 | + return result.toBigInteger(1); | |
| 2044 | + } | |
| 2045 | + | |
| 2046 | + // Shift Operations | |
| 2047 | + | |
| 2048 | + /** | |
| 2049 | + * Returns a BigInteger whose value is {@code (this << n)}. | |
| 2050 | + * The shift distance, {@code n}, may be negative, in which case | |
| 2051 | + * this method performs a right shift. | |
| 2052 | + * (Computes <tt>floor(this * 2<sup>n</sup>)</tt>.) | |
| 2053 | + * | |
| 2054 | + * @param n shift distance, in bits. | |
| 2055 | + * @return {@code this << n} | |
| 2056 | + * @throws ArithmeticException if the shift distance is {@code | |
| 2057 | + * Integer.MIN_VALUE}. | |
| 2058 | + * @see #shiftRight | |
| 2059 | + */ | |
| 2060 | + public BigInteger shiftLeft(int n) { | |
| 2061 | + if (signum == 0) | |
| 2062 | + return ZERO; | |
| 2063 | + if (n==0) | |
| 2064 | + return this; | |
| 2065 | + if (n<0) { | |
| 2066 | + if (n == Integer.MIN_VALUE) { | |
| 2067 | + throw new ArithmeticException("Shift distance of Integer.MIN_VALUE not supported."); | |
| 2068 | + } else { | |
| 2069 | + return shiftRight(-n); | |
| 2070 | + } | |
| 2071 | + } | |
| 2072 | + | |
| 2073 | + int nInts = n >>> 5; | |
| 2074 | + int nBits = n & 0x1f; | |
| 2075 | + int magLen = mag.length; | |
| 2076 | + int newMag[] = null; | |
| 2077 | + | |
| 2078 | + if (nBits == 0) { | |
| 2079 | + newMag = new int[magLen + nInts]; | |
| 2080 | + for (int i=0; i<magLen; i++) | |
| 2081 | + newMag[i] = mag[i]; | |
| 2082 | + } else { | |
| 2083 | + int i = 0; | |
| 2084 | + int nBits2 = 32 - nBits; | |
| 2085 | + int highBits = mag[0] >>> nBits2; | |
| 2086 | + if (highBits != 0) { | |
| 2087 | + newMag = new int[magLen + nInts + 1]; | |
| 2088 | + newMag[i++] = highBits; | |
| 2089 | + } else { | |
| 2090 | + newMag = new int[magLen + nInts]; | |
| 2091 | + } | |
| 2092 | + int j=0; | |
| 2093 | + while (j < magLen-1) | |
| 2094 | + newMag[i++] = mag[j++] << nBits | mag[j] >>> nBits2; | |
| 2095 | + newMag[i] = mag[j] << nBits; | |
| 2096 | + } | |
| 2097 | + | |
| 2098 | + return new BigInteger(newMag, signum); | |
| 2099 | + } | |
| 2100 | + | |
| 2101 | + /** | |
| 2102 | + * Returns a BigInteger whose value is {@code (this >> n)}. Sign | |
| 2103 | + * extension is performed. The shift distance, {@code n}, may be | |
| 2104 | + * negative, in which case this method performs a left shift. | |
| 2105 | + * (Computes <tt>floor(this / 2<sup>n</sup>)</tt>.) | |
| 2106 | + * | |
| 2107 | + * @param n shift distance, in bits. | |
| 2108 | + * @return {@code this >> n} | |
| 2109 | + * @throws ArithmeticException if the shift distance is {@code | |
| 2110 | + * Integer.MIN_VALUE}. | |
| 2111 | + * @see #shiftLeft | |
| 2112 | + */ | |
| 2113 | + public BigInteger shiftRight(int n) { | |
| 2114 | + if (n==0) | |
| 2115 | + return this; | |
| 2116 | + if (n<0) { | |
| 2117 | + if (n == Integer.MIN_VALUE) { | |
| 2118 | + throw new ArithmeticException("Shift distance of Integer.MIN_VALUE not supported."); | |
| 2119 | + } else { | |
| 2120 | + return shiftLeft(-n); | |
| 2121 | + } | |
| 2122 | + } | |
| 2123 | + | |
| 2124 | + int nInts = n >>> 5; | |
| 2125 | + int nBits = n & 0x1f; | |
| 2126 | + int magLen = mag.length; | |
| 2127 | + int newMag[] = null; | |
| 2128 | + | |
| 2129 | + // Special case: entire contents shifted off the end | |
| 2130 | + if (nInts >= magLen) | |
| 2131 | + return (signum >= 0 ? ZERO : negConst[1]); | |
| 2132 | + | |
| 2133 | + if (nBits == 0) { | |
| 2134 | + int newMagLen = magLen - nInts; | |
| 2135 | + newMag = new int[newMagLen]; | |
| 2136 | + for (int i=0; i<newMagLen; i++) | |
| 2137 | + newMag[i] = mag[i]; | |
| 2138 | + } else { | |
| 2139 | + int i = 0; | |
| 2140 | + int highBits = mag[0] >>> nBits; | |
| 2141 | + if (highBits != 0) { | |
| 2142 | + newMag = new int[magLen - nInts]; | |
| 2143 | + newMag[i++] = highBits; | |
| 2144 | + } else { | |
| 2145 | + newMag = new int[magLen - nInts -1]; | |
| 2146 | + } | |
| 2147 | + | |
| 2148 | + int nBits2 = 32 - nBits; | |
| 2149 | + int j=0; | |
| 2150 | + while (j < magLen - nInts - 1) | |
| 2151 | + newMag[i++] = (mag[j++] << nBits2) | (mag[j] >>> nBits); | |
| 2152 | + } | |
| 2153 | + | |
| 2154 | + if (signum < 0) { | |
| 2155 | + // Find out whether any one-bits were shifted off the end. | |
| 2156 | + boolean onesLost = false; | |
| 2157 | + for (int i=magLen-1, j=magLen-nInts; i>=j && !onesLost; i--) | |
| 2158 | + onesLost = (mag[i] != 0); | |
| 2159 | + if (!onesLost && nBits != 0) | |
| 2160 | + onesLost = (mag[magLen - nInts - 1] << (32 - nBits) != 0); | |
| 2161 | + | |
| 2162 | + if (onesLost) | |
| 2163 | + newMag = javaIncrement(newMag); | |
| 2164 | + } | |
| 2165 | + | |
| 2166 | + return new BigInteger(newMag, signum); | |
| 2167 | + } | |
| 2168 | + | |
| 2169 | + int[] javaIncrement(int[] val) { | |
| 2170 | + int lastSum = 0; | |
| 2171 | + for (int i=val.length-1; i >= 0 && lastSum == 0; i--) | |
| 2172 | + lastSum = (val[i] += 1); | |
| 2173 | + if (lastSum == 0) { | |
| 2174 | + val = new int[val.length+1]; | |
| 2175 | + val[0] = 1; | |
| 2176 | + } | |
| 2177 | + return val; | |
| 2178 | + } | |
| 2179 | + | |
| 2180 | + // Bitwise Operations | |
| 2181 | + | |
| 2182 | + /** | |
| 2183 | + * Returns a BigInteger whose value is {@code (this & val)}. (This | |
| 2184 | + * method returns a negative BigInteger if and only if this and val are | |
| 2185 | + * both negative.) | |
| 2186 | + * | |
| 2187 | + * @param val value to be AND'ed with this BigInteger. | |
| 2188 | + * @return {@code this & val} | |
| 2189 | + */ | |
| 2190 | + public BigInteger and(BigInteger val) { | |
| 2191 | + int[] result = new int[Math.max(intLength(), val.intLength())]; | |
| 2192 | + for (int i=0; i<result.length; i++) | |
| 2193 | + result[i] = (getInt(result.length-i-1) | |
| 2194 | + & val.getInt(result.length-i-1)); | |
| 2195 | + | |
| 2196 | + return valueOf(result); | |
| 2197 | + } | |
| 2198 | + | |
| 2199 | + /** | |
| 2200 | + * Returns a BigInteger whose value is {@code (this | val)}. (This method | |
| 2201 | + * returns a negative BigInteger if and only if either this or val is | |
| 2202 | + * negative.) | |
| 2203 | + * | |
| 2204 | + * @param val value to be OR'ed with this BigInteger. | |
| 2205 | + * @return {@code this | val} | |
| 2206 | + */ | |
| 2207 | + public BigInteger or(BigInteger val) { | |
| 2208 | + int[] result = new int[Math.max(intLength(), val.intLength())]; | |
| 2209 | + for (int i=0; i<result.length; i++) | |
| 2210 | + result[i] = (getInt(result.length-i-1) | |
| 2211 | + | val.getInt(result.length-i-1)); | |
| 2212 | + | |
| 2213 | + return valueOf(result); | |
| 2214 | + } | |
| 2215 | + | |
| 2216 | + /** | |
| 2217 | + * Returns a BigInteger whose value is {@code (this ^ val)}. (This method | |
| 2218 | + * returns a negative BigInteger if and only if exactly one of this and | |
| 2219 | + * val are negative.) | |
| 2220 | + * | |
| 2221 | + * @param val value to be XOR'ed with this BigInteger. | |
| 2222 | + * @return {@code this ^ val} | |
| 2223 | + */ | |
| 2224 | + public BigInteger xor(BigInteger val) { | |
| 2225 | + int[] result = new int[Math.max(intLength(), val.intLength())]; | |
| 2226 | + for (int i=0; i<result.length; i++) | |
| 2227 | + result[i] = (getInt(result.length-i-1) | |
| 2228 | + ^ val.getInt(result.length-i-1)); | |
| 2229 | + | |
| 2230 | + return valueOf(result); | |
| 2231 | + } | |
| 2232 | + | |
| 2233 | + /** | |
| 2234 | + * Returns a BigInteger whose value is {@code (~this)}. (This method | |
| 2235 | + * returns a negative value if and only if this BigInteger is | |
| 2236 | + * non-negative.) | |
| 2237 | + * | |
| 2238 | + * @return {@code ~this} | |
| 2239 | + */ | |
| 2240 | + public BigInteger not() { | |
| 2241 | + int[] result = new int[intLength()]; | |
| 2242 | + for (int i=0; i<result.length; i++) | |
| 2243 | + result[i] = ~getInt(result.length-i-1); | |
| 2244 | + | |
| 2245 | + return valueOf(result); | |
| 2246 | + } | |
| 2247 | + | |
| 2248 | + /** | |
| 2249 | + * Returns a BigInteger whose value is {@code (this & ~val)}. This | |
| 2250 | + * method, which is equivalent to {@code and(val.not())}, is provided as | |
| 2251 | + * a convenience for masking operations. (This method returns a negative | |
| 2252 | + * BigInteger if and only if {@code this} is negative and {@code val} is | |
| 2253 | + * positive.) | |
| 2254 | + * | |
| 2255 | + * @param val value to be complemented and AND'ed with this BigInteger. | |
| 2256 | + * @return {@code this & ~val} | |
| 2257 | + */ | |
| 2258 | + public BigInteger andNot(BigInteger val) { | |
| 2259 | + int[] result = new int[Math.max(intLength(), val.intLength())]; | |
| 2260 | + for (int i=0; i<result.length; i++) | |
| 2261 | + result[i] = (getInt(result.length-i-1) | |
| 2262 | + & ~val.getInt(result.length-i-1)); | |
| 2263 | + | |
| 2264 | + return valueOf(result); | |
| 2265 | + } | |
| 2266 | + | |
| 2267 | + | |
| 2268 | + // Single Bit Operations | |
| 2269 | + | |
| 2270 | + /** | |
| 2271 | + * Returns {@code true} if and only if the designated bit is set. | |
| 2272 | + * (Computes {@code ((this & (1<<n)) != 0)}.) | |
| 2273 | + * | |
| 2274 | + * @param n index of bit to test. | |
| 2275 | + * @return {@code true} if and only if the designated bit is set. | |
| 2276 | + * @throws ArithmeticException {@code n} is negative. | |
| 2277 | + */ | |
| 2278 | + public boolean testBit(int n) { | |
| 2279 | + if (n<0) | |
| 2280 | + throw new ArithmeticException("Negative bit address"); | |
| 2281 | + | |
| 2282 | + return (getInt(n >>> 5) & (1 << (n & 31))) != 0; | |
| 2283 | + } | |
| 2284 | + | |
| 2285 | + /** | |
| 2286 | + * Returns a BigInteger whose value is equivalent to this BigInteger | |
| 2287 | + * with the designated bit set. (Computes {@code (this | (1<<n))}.) | |
| 2288 | + * | |
| 2289 | + * @param n index of bit to set. | |
| 2290 | + * @return {@code this | (1<<n)} | |
| 2291 | + * @throws ArithmeticException {@code n} is negative. | |
| 2292 | + */ | |
| 2293 | + public BigInteger setBit(int n) { | |
| 2294 | + if (n<0) | |
| 2295 | + throw new ArithmeticException("Negative bit address"); | |
| 2296 | + | |
| 2297 | + int intNum = n >>> 5; | |
| 2298 | + int[] result = new int[Math.max(intLength(), intNum+2)]; | |
| 2299 | + | |
| 2300 | + for (int i=0; i<result.length; i++) | |
| 2301 | + result[result.length-i-1] = getInt(i); | |
| 2302 | + | |
| 2303 | + result[result.length-intNum-1] |= (1 << (n & 31)); | |
| 2304 | + | |
| 2305 | + return valueOf(result); | |
| 2306 | + } | |
| 2307 | + | |
| 2308 | + /** | |
| 2309 | + * Returns a BigInteger whose value is equivalent to this BigInteger | |
| 2310 | + * with the designated bit cleared. | |
| 2311 | + * (Computes {@code (this & ~(1<<n))}.) | |
| 2312 | + * | |
| 2313 | + * @param n index of bit to clear. | |
| 2314 | + * @return {@code this & ~(1<<n)} | |
| 2315 | + * @throws ArithmeticException {@code n} is negative. | |
| 2316 | + */ | |
| 2317 | + public BigInteger clearBit(int n) { | |
| 2318 | + if (n<0) | |
| 2319 | + throw new ArithmeticException("Negative bit address"); | |
| 2320 | + | |
| 2321 | + int intNum = n >>> 5; | |
| 2322 | + int[] result = new int[Math.max(intLength(), ((n + 1) >>> 5) + 1)]; | |
| 2323 | + | |
| 2324 | + for (int i=0; i<result.length; i++) | |
| 2325 | + result[result.length-i-1] = getInt(i); | |
| 2326 | + | |
| 2327 | + result[result.length-intNum-1] &= ~(1 << (n & 31)); | |
| 2328 | + | |
| 2329 | + return valueOf(result); | |
| 2330 | + } | |
| 2331 | + | |
| 2332 | + /** | |
| 2333 | + * Returns a BigInteger whose value is equivalent to this BigInteger | |
| 2334 | + * with the designated bit flipped. | |
| 2335 | + * (Computes {@code (this ^ (1<<n))}.) | |
| 2336 | + * | |
| 2337 | + * @param n index of bit to flip. | |
| 2338 | + * @return {@code this ^ (1<<n)} | |
| 2339 | + * @throws ArithmeticException {@code n} is negative. | |
| 2340 | + */ | |
| 2341 | + public BigInteger flipBit(int n) { | |
| 2342 | + if (n<0) | |
| 2343 | + throw new ArithmeticException("Negative bit address"); | |
| 2344 | + | |
| 2345 | + int intNum = n >>> 5; | |
| 2346 | + int[] result = new int[Math.max(intLength(), intNum+2)]; | |
| 2347 | + | |
| 2348 | + for (int i=0; i<result.length; i++) | |
| 2349 | + result[result.length-i-1] = getInt(i); | |
| 2350 | + | |
| 2351 | + result[result.length-intNum-1] ^= (1 << (n & 31)); | |
| 2352 | + | |
| 2353 | + return valueOf(result); | |
| 2354 | + } | |
| 2355 | + | |
| 2356 | + /** | |
| 2357 | + * Returns the index of the rightmost (lowest-order) one bit in this | |
| 2358 | + * BigInteger (the number of zero bits to the right of the rightmost | |
| 2359 | + * one bit). Returns -1 if this BigInteger contains no one bits. | |
| 2360 | + * (Computes {@code (this==0? -1 : log2(this & -this))}.) | |
| 2361 | + * | |
| 2362 | + * @return index of the rightmost one bit in this BigInteger. | |
| 2363 | + */ | |
| 2364 | + public int getLowestSetBit() { | |
| 2365 | + @SuppressWarnings("deprecation") int lsb = lowestSetBit - 2; | |
| 2366 | + if (lsb == -2) { // lowestSetBit not initialized yet | |
| 2367 | + lsb = 0; | |
| 2368 | + if (signum == 0) { | |
| 2369 | + lsb -= 1; | |
| 2370 | + } else { | |
| 2371 | + // Search for lowest order nonzero int | |
| 2372 | + int i,b; | |
| 2373 | + for (i=0; (b = getInt(i))==0; i++) | |
| 2374 | + ; | |
| 2375 | + lsb += (i << 5) + Integer.numberOfTrailingZeros(b); | |
| 2376 | + } | |
| 2377 | + lowestSetBit = lsb + 2; | |
| 2378 | + } | |
| 2379 | + return lsb; | |
| 2380 | + } | |
| 2381 | + | |
| 2382 | + | |
| 2383 | + // Miscellaneous Bit Operations | |
| 2384 | + | |
| 2385 | + /** | |
| 2386 | + * Returns the number of bits in the minimal two's-complement | |
| 2387 | + * representation of this BigInteger, <i>excluding</i> a sign bit. | |
| 2388 | + * For positive BigIntegers, this is equivalent to the number of bits in | |
| 2389 | + * the ordinary binary representation. (Computes | |
| 2390 | + * {@code (ceil(log2(this < 0 ? -this : this+1)))}.) | |
| 2391 | + * | |
| 2392 | + * @return number of bits in the minimal two's-complement | |
| 2393 | + * representation of this BigInteger, <i>excluding</i> a sign bit. | |
| 2394 | + */ | |
| 2395 | + public int bitLength() { | |
| 2396 | + @SuppressWarnings("deprecation") int n = bitLength - 1; | |
| 2397 | + if (n == -1) { // bitLength not initialized yet | |
| 2398 | + int[] m = mag; | |
| 2399 | + int len = m.length; | |
| 2400 | + if (len == 0) { | |
| 2401 | + n = 0; // offset by one to initialize | |
| 2402 | + } else { | |
| 2403 | + // Calculate the bit length of the magnitude | |
| 2404 | + int magBitLength = ((len - 1) << 5) + bitLengthForInt(mag[0]); | |
| 2405 | + if (signum < 0) { | |
| 2406 | + // Check if magnitude is a power of two | |
| 2407 | + boolean pow2 = (Integer.bitCount(mag[0]) == 1); | |
| 2408 | + for(int i=1; i< len && pow2; i++) | |
| 2409 | + pow2 = (mag[i] == 0); | |
| 2410 | + | |
| 2411 | + n = (pow2 ? magBitLength -1 : magBitLength); | |
| 2412 | + } else { | |
| 2413 | + n = magBitLength; | |
| 2414 | + } | |
| 2415 | + } | |
| 2416 | + bitLength = n + 1; | |
| 2417 | + } | |
| 2418 | + return n; | |
| 2419 | + } | |
| 2420 | + | |
| 2421 | + /** | |
| 2422 | + * Returns the number of bits in the two's complement representation | |
| 2423 | + * of this BigInteger that differ from its sign bit. This method is | |
| 2424 | + * useful when implementing bit-vector style sets atop BigIntegers. | |
| 2425 | + * | |
| 2426 | + * @return number of bits in the two's complement representation | |
| 2427 | + * of this BigInteger that differ from its sign bit. | |
| 2428 | + */ | |
| 2429 | + public int bitCount() { | |
| 2430 | + @SuppressWarnings("deprecation") int bc = bitCount - 1; | |
| 2431 | + if (bc == -1) { // bitCount not initialized yet | |
| 2432 | + bc = 0; // offset by one to initialize | |
| 2433 | + // Count the bits in the magnitude | |
| 2434 | + for (int i=0; i<mag.length; i++) | |
| 2435 | + bc += Integer.bitCount(mag[i]); | |
| 2436 | + if (signum < 0) { | |
| 2437 | + // Count the trailing zeros in the magnitude | |
| 2438 | + int magTrailingZeroCount = 0, j; | |
| 2439 | + for (j=mag.length-1; mag[j]==0; j--) | |
| 2440 | + magTrailingZeroCount += 32; | |
| 2441 | + magTrailingZeroCount += Integer.numberOfTrailingZeros(mag[j]); | |
| 2442 | + bc += magTrailingZeroCount - 1; | |
| 2443 | + } | |
| 2444 | + bitCount = bc + 1; | |
| 2445 | + } | |
| 2446 | + return bc; | |
| 2447 | + } | |
| 2448 | + | |
| 2449 | + // Primality Testing | |
| 2450 | + | |
| 2451 | + /** | |
| 2452 | + * Returns {@code true} if this BigInteger is probably prime, | |
| 2453 | + * {@code false} if it's definitely composite. If | |
| 2454 | + * {@code certainty} is ≤ 0, {@code true} is | |
| 2455 | + * returned. | |
| 2456 | + * | |
| 2457 | + * @param certainty a measure of the uncertainty that the caller is | |
| 2458 | + * willing to tolerate: if the call returns {@code true} | |
| 2459 | + * the probability that this BigInteger is prime exceeds | |
| 2460 | + * (1 - 1/2<sup>{@code certainty}</sup>). The execution time of | |
| 2461 | + * this method is proportional to the value of this parameter. | |
| 2462 | + * @return {@code true} if this BigInteger is probably prime, | |
| 2463 | + * {@code false} if it's definitely composite. | |
| 2464 | + */ | |
| 2465 | + public boolean isProbablePrime(int certainty) { | |
| 2466 | + if (certainty <= 0) | |
| 2467 | + return true; | |
| 2468 | + BigInteger w = this.abs(); | |
| 2469 | + if (w.equals(TWO)) | |
| 2470 | + return true; | |
| 2471 | + if (!w.testBit(0) || w.equals(ONE)) | |
| 2472 | + return false; | |
| 2473 | + | |
| 2474 | + return w.primeToCertainty(certainty, null); | |
| 2475 | + } | |
| 2476 | + | |
| 2477 | + // Comparison Operations | |
| 2478 | + | |
| 2479 | + /** | |
| 2480 | + * Compares this BigInteger with the specified BigInteger. This | |
| 2481 | + * method is provided in preference to individual methods for each | |
| 2482 | + * of the six boolean comparison operators ({@literal <}, ==, | |
| 2483 | + * {@literal >}, {@literal >=}, !=, {@literal <=}). The suggested | |
| 2484 | + * idiom for performing these comparisons is: {@code | |
| 2485 | + * (x.compareTo(y)} <<i>op</i>> {@code 0)}, where | |
| 2486 | + * <<i>op</i>> is one of the six comparison operators. | |
| 2487 | + * | |
| 2488 | + * @param val BigInteger to which this BigInteger is to be compared. | |
| 2489 | + * @return -1, 0 or 1 as this BigInteger is numerically less than, equal | |
| 2490 | + * to, or greater than {@code val}. | |
| 2491 | + */ | |
| 2492 | + public int compareTo(BigInteger val) { | |
| 2493 | + if (signum == val.signum) { | |
| 2494 | + switch (signum) { | |
| 2495 | + case 1: | |
| 2496 | + return compareMagnitude(val); | |
| 2497 | + case -1: | |
| 2498 | + return val.compareMagnitude(this); | |
| 2499 | + default: | |
| 2500 | + return 0; | |
| 2501 | + } | |
| 2502 | + } | |
| 2503 | + return signum > val.signum ? 1 : -1; | |
| 2504 | + } | |
| 2505 | + | |
| 2506 | + /** | |
| 2507 | + * Compares the magnitude array of this BigInteger with the specified | |
| 2508 | + * BigInteger's. This is the version of compareTo ignoring sign. | |
| 2509 | + * | |
| 2510 | + * @param val BigInteger whose magnitude array to be compared. | |
| 2511 | + * @return -1, 0 or 1 as this magnitude array is less than, equal to or | |
| 2512 | + * greater than the magnitude aray for the specified BigInteger's. | |
| 2513 | + */ | |
| 2514 | + final int compareMagnitude(BigInteger val) { | |
| 2515 | + int[] m1 = mag; | |
| 2516 | + int len1 = m1.length; | |
| 2517 | + int[] m2 = val.mag; | |
| 2518 | + int len2 = m2.length; | |
| 2519 | + if (len1 < len2) | |
| 2520 | + return -1; | |
| 2521 | + if (len1 > len2) | |
| 2522 | + return 1; | |
| 2523 | + for (int i = 0; i < len1; i++) { | |
| 2524 | + int a = m1[i]; | |
| 2525 | + int b = m2[i]; | |
| 2526 | + if (a != b) | |
| 2527 | + return ((a & LONG_MASK) < (b & LONG_MASK)) ? -1 : 1; | |
| 2528 | + } | |
| 2529 | + return 0; | |
| 2530 | + } | |
| 2531 | + | |
| 2532 | + /** | |
| 2533 | + * Compares this BigInteger with the specified Object for equality. | |
| 2534 | + * | |
| 2535 | + * @param x Object to which this BigInteger is to be compared. | |
| 2536 | + * @return {@code true} if and only if the specified Object is a | |
| 2537 | + * BigInteger whose value is numerically equal to this BigInteger. | |
| 2538 | + */ | |
| 2539 | + public boolean equals(Object x) { | |
| 2540 | + // This test is just an optimization, which may or may not help | |
| 2541 | + if (x == this) | |
| 2542 | + return true; | |
| 2543 | + | |
| 2544 | + if (!(x instanceof BigInteger)) | |
| 2545 | + return false; | |
| 2546 | + | |
| 2547 | + BigInteger xInt = (BigInteger) x; | |
| 2548 | + if (xInt.signum != signum) | |
| 2549 | + return false; | |
| 2550 | + | |
| 2551 | + int[] m = mag; | |
| 2552 | + int len = m.length; | |
| 2553 | + int[] xm = xInt.mag; | |
| 2554 | + if (len != xm.length) | |
| 2555 | + return false; | |
| 2556 | + | |
| 2557 | + for (int i = 0; i < len; i++) | |
| 2558 | + if (xm[i] != m[i]) | |
| 2559 | + return false; | |
| 2560 | + | |
| 2561 | + return true; | |
| 2562 | + } | |
| 2563 | + | |
| 2564 | + /** | |
| 2565 | + * Returns the minimum of this BigInteger and {@code val}. | |
| 2566 | + * | |
| 2567 | + * @param val value with which the minimum is to be computed. | |
| 2568 | + * @return the BigInteger whose value is the lesser of this BigInteger and | |
| 2569 | + * {@code val}. If they are equal, either may be returned. | |
| 2570 | + */ | |
| 2571 | + public BigInteger min(BigInteger val) { | |
| 2572 | + return (compareTo(val)<0 ? this : val); | |
| 2573 | + } | |
| 2574 | + | |
| 2575 | + /** | |
| 2576 | + * Returns the maximum of this BigInteger and {@code val}. | |
| 2577 | + * | |
| 2578 | + * @param val value with which the maximum is to be computed. | |
| 2579 | + * @return the BigInteger whose value is the greater of this and | |
| 2580 | + * {@code val}. If they are equal, either may be returned. | |
| 2581 | + */ | |
| 2582 | + public BigInteger max(BigInteger val) { | |
| 2583 | + return (compareTo(val)>0 ? this : val); | |
| 2584 | + } | |
| 2585 | + | |
| 2586 | + | |
| 2587 | + // Hash Function | |
| 2588 | + | |
| 2589 | + /** | |
| 2590 | + * Returns the hash code for this BigInteger. | |
| 2591 | + * | |
| 2592 | + * @return hash code for this BigInteger. | |
| 2593 | + */ | |
| 2594 | + public int hashCode() { | |
| 2595 | + int hashCode = 0; | |
| 2596 | + | |
| 2597 | + for (int i=0; i<mag.length; i++) | |
| 2598 | + hashCode = (int)(31*hashCode + (mag[i] & LONG_MASK)); | |
| 2599 | + | |
| 2600 | + return hashCode * signum; | |
| 2601 | + } | |
| 2602 | + | |
| 2603 | + /** | |
| 2604 | + * Returns the String representation of this BigInteger in the | |
| 2605 | + * given radix. If the radix is outside the range from {@link | |
| 2606 | + * Character#MIN_RADIX} to {@link Character#MAX_RADIX} inclusive, | |
| 2607 | + * it will default to 10 (as is the case for | |
| 2608 | + * {@code Integer.toString}). The digit-to-character mapping | |
| 2609 | + * provided by {@code Character.forDigit} is used, and a minus | |
| 2610 | + * sign is prepended if appropriate. (This representation is | |
| 2611 | + * compatible with the {@link #BigInteger(String, int) (String, | |
| 2612 | + * int)} constructor.) | |
| 2613 | + * | |
| 2614 | + * @param radix radix of the String representation. | |
| 2615 | + * @return String representation of this BigInteger in the given radix. | |
| 2616 | + * @see Integer#toString | |
| 2617 | + * @see Character#forDigit | |
| 2618 | + * @see #BigInteger(java.lang.String, int) | |
| 2619 | + */ | |
| 2620 | + public String toString(int radix) { | |
| 2621 | + if (signum == 0) | |
| 2622 | + return "0"; | |
| 2623 | + if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX) | |
| 2624 | + radix = 10; | |
| 2625 | + | |
| 2626 | + // Compute upper bound on number of digit groups and allocate space | |
| 2627 | + int maxNumDigitGroups = (4*mag.length + 6)/7; | |
| 2628 | + String digitGroup[] = new String[maxNumDigitGroups]; | |
| 2629 | + | |
| 2630 | + // Translate number to string, a digit group at a time | |
| 2631 | + BigInteger tmp = this.abs(); | |
| 2632 | + int numGroups = 0; | |
| 2633 | + while (tmp.signum != 0) { | |
| 2634 | + BigInteger d = longRadix[radix]; | |
| 2635 | + | |
| 2636 | + MutableBigInteger q = new MutableBigInteger(), | |
| 2637 | + a = new MutableBigInteger(tmp.mag), | |
| 2638 | + b = new MutableBigInteger(d.mag); | |
| 2639 | + MutableBigInteger r = a.divide(b, q); | |
| 2640 | + BigInteger q2 = q.toBigInteger(tmp.signum * d.signum); | |
| 2641 | + BigInteger r2 = r.toBigInteger(tmp.signum * d.signum); | |
| 2642 | + | |
| 2643 | + digitGroup[numGroups++] = Long.toString(r2.longValue(), radix); | |
| 2644 | + tmp = q2; | |
| 2645 | + } | |
| 2646 | + | |
| 2647 | + // Put sign (if any) and first digit group into result buffer | |
| 2648 | + StringBuilder buf = new StringBuilder(numGroups*digitsPerLong[radix]+1); | |
| 2649 | + if (signum<0) | |
| 2650 | + buf.append('-'); | |
| 2651 | + buf.append(digitGroup[numGroups-1]); | |
| 2652 | + | |
| 2653 | + // Append remaining digit groups padded with leading zeros | |
| 2654 | + for (int i=numGroups-2; i>=0; i--) { | |
| 2655 | + // Prepend (any) leading zeros for this digit group | |
| 2656 | + int numLeadingZeros = digitsPerLong[radix]-digitGroup[i].length(); | |
| 2657 | + if (numLeadingZeros != 0) | |
| 2658 | + buf.append(zeros[numLeadingZeros]); | |
| 2659 | + buf.append(digitGroup[i]); | |
| 2660 | + } | |
| 2661 | + return buf.toString(); | |
| 2662 | + } | |
| 2663 | + | |
| 2664 | + /* zero[i] is a string of i consecutive zeros. */ | |
| 2665 | + private static String zeros[] = new String[64]; | |
| 2666 | + static { | |
| 2667 | + zeros[63] = | |
| 2668 | + "000000000000000000000000000000000000000000000000000000000000000"; | |
| 2669 | + for (int i=0; i<63; i++) | |
| 2670 | + zeros[i] = zeros[63].substring(0, i); | |
| 2671 | + } | |
| 2672 | + | |
| 2673 | + /** | |
| 2674 | + * Returns the decimal String representation of this BigInteger. | |
| 2675 | + * The digit-to-character mapping provided by | |
| 2676 | + * {@code Character.forDigit} is used, and a minus sign is | |
| 2677 | + * prepended if appropriate. (This representation is compatible | |
| 2678 | + * with the {@link #BigInteger(String) (String)} constructor, and | |
| 2679 | + * allows for String concatenation with Java's + operator.) | |
| 2680 | + * | |
| 2681 | + * @return decimal String representation of this BigInteger. | |
| 2682 | + * @see Character#forDigit | |
| 2683 | + * @see #BigInteger(java.lang.String) | |
| 2684 | + */ | |
| 2685 | + public String toString() { | |
| 2686 | + return toString(10); | |
| 2687 | + } | |
| 2688 | + | |
| 2689 | + /** | |
| 2690 | + * Returns a byte array containing the two's-complement | |
| 2691 | + * representation of this BigInteger. The byte array will be in | |
| 2692 | + * <i>big-endian</i> byte-order: the most significant byte is in | |
| 2693 | + * the zeroth element. The array will contain the minimum number | |
| 2694 | + * of bytes required to represent this BigInteger, including at | |
| 2695 | + * least one sign bit, which is {@code (ceil((this.bitLength() + | |
| 2696 | + * 1)/8))}. (This representation is compatible with the | |
| 2697 | + * {@link #BigInteger(byte[]) (byte[])} constructor.) | |
| 2698 | + * | |
| 2699 | + * @return a byte array containing the two's-complement representation of | |
| 2700 | + * this BigInteger. | |
| 2701 | + * @see #BigInteger(byte[]) | |
| 2702 | + */ | |
| 2703 | + public byte[] toByteArray() { | |
| 2704 | + int byteLen = bitLength()/8 + 1; | |
| 2705 | + byte[] byteArray = new byte[byteLen]; | |
| 2706 | + | |
| 2707 | + for (int i=byteLen-1, bytesCopied=4, nextInt=0, intIndex=0; i>=0; i--) { | |
| 2708 | + if (bytesCopied == 4) { | |
| 2709 | + nextInt = getInt(intIndex++); | |
| 2710 | + bytesCopied = 1; | |
| 2711 | + } else { | |
| 2712 | + nextInt >>>= 8; | |
| 2713 | + bytesCopied++; | |
| 2714 | + } | |
| 2715 | + byteArray[i] = (byte)nextInt; | |
| 2716 | + } | |
| 2717 | + return byteArray; | |
| 2718 | + } | |
| 2719 | + | |
| 2720 | + /** | |
| 2721 | + * Converts this BigInteger to an {@code int}. This | |
| 2722 | + * conversion is analogous to a | |
| 2723 | + * <i>narrowing primitive conversion</i> from {@code long} to | |
| 2724 | + * {@code int} as defined in section 5.1.3 of | |
| 2725 | + * <cite>The Java™ Language Specification</cite>: | |
| 2726 | + * if this BigInteger is too big to fit in an | |
| 2727 | + * {@code int}, only the low-order 32 bits are returned. | |
| 2728 | + * Note that this conversion can lose information about the | |
| 2729 | + * overall magnitude of the BigInteger value as well as return a | |
| 2730 | + * result with the opposite sign. | |
| 2731 | + * | |
| 2732 | + * @return this BigInteger converted to an {@code int}. | |
| 2733 | + */ | |
| 2734 | + public int intValue() { | |
| 2735 | + int result = 0; | |
| 2736 | + result = getInt(0); | |
| 2737 | + return result; | |
| 2738 | + } | |
| 2739 | + | |
| 2740 | + /** | |
| 2741 | + * Converts this BigInteger to a {@code long}. This | |
| 2742 | + * conversion is analogous to a | |
| 2743 | + * <i>narrowing primitive conversion</i> from {@code long} to | |
| 2744 | + * {@code int} as defined in section 5.1.3 of | |
| 2745 | + * <cite>The Java™ Language Specification</cite>: | |
| 2746 | + * if this BigInteger is too big to fit in a | |
| 2747 | + * {@code long}, only the low-order 64 bits are returned. | |
| 2748 | + * Note that this conversion can lose information about the | |
| 2749 | + * overall magnitude of the BigInteger value as well as return a | |
| 2750 | + * result with the opposite sign. | |
| 2751 | + * | |
| 2752 | + * @return this BigInteger converted to a {@code long}. | |
| 2753 | + */ | |
| 2754 | + public long longValue() { | |
| 2755 | + long result = 0; | |
| 2756 | + | |
| 2757 | + for (int i=1; i>=0; i--) | |
| 2758 | + result = (result << 32) + (getInt(i) & LONG_MASK); | |
| 2759 | + return result; | |
| 2760 | + } | |
| 2761 | + | |
| 2762 | + /** | |
| 2763 | + * Converts this BigInteger to a {@code float}. This | |
| 2764 | + * conversion is similar to the | |
| 2765 | + * <i>narrowing primitive conversion</i> from {@code double} to | |
| 2766 | + * {@code float} as defined in section 5.1.3 of | |
| 2767 | + * <cite>The Java™ Language Specification</cite>: | |
| 2768 | + * if this BigInteger has too great a magnitude | |
| 2769 | + * to represent as a {@code float}, it will be converted to | |
| 2770 | + * {@link Float#NEGATIVE_INFINITY} or {@link | |
| 2771 | + * Float#POSITIVE_INFINITY} as appropriate. Note that even when | |
| 2772 | + * the return value is finite, this conversion can lose | |
| 2773 | + * information about the precision of the BigInteger value. | |
| 2774 | + * | |
| 2775 | + * @return this BigInteger converted to a {@code float}. | |
| 2776 | + */ | |
| 2777 | + public float floatValue() { | |
| 2778 | + // Somewhat inefficient, but guaranteed to work. | |
| 2779 | + return Float.parseFloat(this.toString()); | |
| 2780 | + } | |
| 2781 | + | |
| 2782 | + /** | |
| 2783 | + * Converts this BigInteger to a {@code double}. This | |
| 2784 | + * conversion is similar to the | |
| 2785 | + * <i>narrowing primitive conversion</i> from {@code double} to | |
| 2786 | + * {@code float} as defined in section 5.1.3 of | |
| 2787 | + * <cite>The Java™ Language Specification</cite>: | |
| 2788 | + * if this BigInteger has too great a magnitude | |
| 2789 | + * to represent as a {@code double}, it will be converted to | |
| 2790 | + * {@link Double#NEGATIVE_INFINITY} or {@link | |
| 2791 | + * Double#POSITIVE_INFINITY} as appropriate. Note that even when | |
| 2792 | + * the return value is finite, this conversion can lose | |
| 2793 | + * information about the precision of the BigInteger value. | |
| 2794 | + * | |
| 2795 | + * @return this BigInteger converted to a {@code double}. | |
| 2796 | + */ | |
| 2797 | + public double doubleValue() { | |
| 2798 | + // Somewhat inefficient, but guaranteed to work. | |
| 2799 | + return Double.parseDouble(this.toString()); | |
| 2800 | + } | |
| 2801 | + | |
| 2802 | + /** | |
| 2803 | + * Returns a copy of the input array stripped of any leading zero bytes. | |
| 2804 | + */ | |
| 2805 | + private static int[] stripLeadingZeroInts(int val[]) { | |
| 2806 | + int vlen = val.length; | |
| 2807 | + int keep; | |
| 2808 | + | |
| 2809 | + // Find first nonzero byte | |
| 2810 | + for (keep = 0; keep < vlen && val[keep] == 0; keep++) | |
| 2811 | + ; | |
| 2812 | + return java.util.Arrays.copyOfRange(val, keep, vlen); | |
| 2813 | + } | |
| 2814 | + | |
| 2815 | + /** | |
| 2816 | + * Returns the input array stripped of any leading zero bytes. | |
| 2817 | + * Since the source is trusted the copying may be skipped. | |
| 2818 | + */ | |
| 2819 | + private static int[] trustedStripLeadingZeroInts(int val[]) { | |
| 2820 | + int vlen = val.length; | |
| 2821 | + int keep; | |
| 2822 | + | |
| 2823 | + // Find first nonzero byte | |
| 2824 | + for (keep = 0; keep < vlen && val[keep] == 0; keep++) | |
| 2825 | + ; | |
| 2826 | + return keep == 0 ? val : java.util.Arrays.copyOfRange(val, keep, vlen); | |
| 2827 | + } | |
| 2828 | + | |
| 2829 | + /** | |
| 2830 | + * Returns a copy of the input array stripped of any leading zero bytes. | |
| 2831 | + */ | |
| 2832 | + private static int[] stripLeadingZeroBytes(byte a[]) { | |
| 2833 | + int byteLength = a.length; | |
| 2834 | + int keep; | |
| 2835 | + | |
| 2836 | + // Find first nonzero byte | |
| 2837 | + for (keep = 0; keep < byteLength && a[keep]==0; keep++) | |
| 2838 | + ; | |
| 2839 | + | |
| 2840 | + // Allocate new array and copy relevant part of input array | |
| 2841 | + int intLength = ((byteLength - keep) + 3) >>> 2; | |
| 2842 | + int[] result = new int[intLength]; | |
| 2843 | + int b = byteLength - 1; | |
| 2844 | + for (int i = intLength-1; i >= 0; i--) { | |
| 2845 | + result[i] = a[b--] & 0xff; | |
| 2846 | + int bytesRemaining = b - keep + 1; | |
| 2847 | + int bytesToTransfer = Math.min(3, bytesRemaining); | |
| 2848 | + for (int j=8; j <= (bytesToTransfer << 3); j += 8) | |
| 2849 | + result[i] |= ((a[b--] & 0xff) << j); | |
| 2850 | + } | |
| 2851 | + return result; | |
| 2852 | + } | |
| 2853 | + | |
| 2854 | + /** | |
| 2855 | + * Takes an array a representing a negative 2's-complement number and | |
| 2856 | + * returns the minimal (no leading zero bytes) unsigned whose value is -a. | |
| 2857 | + */ | |
| 2858 | + private static int[] makePositive(byte a[]) { | |
| 2859 | + int keep, k; | |
| 2860 | + int byteLength = a.length; | |
| 2861 | + | |
| 2862 | + // Find first non-sign (0xff) byte of input | |
| 2863 | + for (keep=0; keep<byteLength && a[keep]==-1; keep++) | |
| 2864 | + ; | |
| 2865 | + | |
| 2866 | + | |
| 2867 | + /* Allocate output array. If all non-sign bytes are 0x00, we must | |
| 2868 | + * allocate space for one extra output byte. */ | |
| 2869 | + for (k=keep; k<byteLength && a[k]==0; k++) | |
| 2870 | + ; | |
| 2871 | + | |
| 2872 | + int extraByte = (k==byteLength) ? 1 : 0; | |
| 2873 | + int intLength = ((byteLength - keep + extraByte) + 3)/4; | |
| 2874 | + int result[] = new int[intLength]; | |
| 2875 | + | |
| 2876 | + /* Copy one's complement of input into output, leaving extra | |
| 2877 | + * byte (if it exists) == 0x00 */ | |
| 2878 | + int b = byteLength - 1; | |
| 2879 | + for (int i = intLength-1; i >= 0; i--) { | |
| 2880 | + result[i] = a[b--] & 0xff; | |
| 2881 | + int numBytesToTransfer = Math.min(3, b-keep+1); | |
| 2882 | + if (numBytesToTransfer < 0) | |
| 2883 | + numBytesToTransfer = 0; | |
| 2884 | + for (int j=8; j <= 8*numBytesToTransfer; j += 8) | |
| 2885 | + result[i] |= ((a[b--] & 0xff) << j); | |
| 2886 | + | |
| 2887 | + // Mask indicates which bits must be complemented | |
| 2888 | + int mask = -1 >>> (8*(3-numBytesToTransfer)); | |
| 2889 | + result[i] = ~result[i] & mask; | |
| 2890 | + } | |
| 2891 | + | |
| 2892 | + // Add one to one's complement to generate two's complement | |
| 2893 | + for (int i=result.length-1; i>=0; i--) { | |
| 2894 | + result[i] = (int)((result[i] & LONG_MASK) + 1); | |
| 2895 | + if (result[i] != 0) | |
| 2896 | + break; | |
| 2897 | + } | |
| 2898 | + | |
| 2899 | + return result; | |
| 2900 | + } | |
| 2901 | + | |
| 2902 | + /** | |
| 2903 | + * Takes an array a representing a negative 2's-complement number and | |
| 2904 | + * returns the minimal (no leading zero ints) unsigned whose value is -a. | |
| 2905 | + */ | |
| 2906 | + private static int[] makePositive(int a[]) { | |
| 2907 | + int keep, j; | |
| 2908 | + | |
| 2909 | + // Find first non-sign (0xffffffff) int of input | |
| 2910 | + for (keep=0; keep<a.length && a[keep]==-1; keep++) | |
| 2911 | + ; | |
| 2912 | + | |
| 2913 | + /* Allocate output array. If all non-sign ints are 0x00, we must | |
| 2914 | + * allocate space for one extra output int. */ | |
| 2915 | + for (j=keep; j<a.length && a[j]==0; j++) | |
| 2916 | + ; | |
| 2917 | + int extraInt = (j==a.length ? 1 : 0); | |
| 2918 | + int result[] = new int[a.length - keep + extraInt]; | |
| 2919 | + | |
| 2920 | + /* Copy one's complement of input into output, leaving extra | |
| 2921 | + * int (if it exists) == 0x00 */ | |
| 2922 | + for (int i = keep; i<a.length; i++) | |
| 2923 | + result[i - keep + extraInt] = ~a[i]; | |
| 2924 | + | |
| 2925 | + // Add one to one's complement to generate two's complement | |
| 2926 | + for (int i=result.length-1; ++result[i]==0; i--) | |
| 2927 | + ; | |
| 2928 | + | |
| 2929 | + return result; | |
| 2930 | + } | |
| 2931 | + | |
| 2932 | + /* | |
| 2933 | + * The following two arrays are used for fast String conversions. Both | |
| 2934 | + * are indexed by radix. The first is the number of digits of the given | |
| 2935 | + * radix that can fit in a Java long without "going negative", i.e., the | |
| 2936 | + * highest integer n such that radix**n < 2**63. The second is the | |
| 2937 | + * "long radix" that tears each number into "long digits", each of which | |
| 2938 | + * consists of the number of digits in the corresponding element in | |
| 2939 | + * digitsPerLong (longRadix[i] = i**digitPerLong[i]). Both arrays have | |
| 2940 | + * nonsense values in their 0 and 1 elements, as radixes 0 and 1 are not | |
| 2941 | + * used. | |
| 2942 | + */ | |
| 2943 | + private static int digitsPerLong[] = {0, 0, | |
| 2944 | + 62, 39, 31, 27, 24, 22, 20, 19, 18, 18, 17, 17, 16, 16, 15, 15, 15, 14, | |
| 2945 | + 14, 14, 14, 13, 13, 13, 13, 13, 13, 12, 12, 12, 12, 12, 12, 12, 12}; | |
| 2946 | + | |
| 2947 | + private static BigInteger longRadix[] = {null, null, | |
| 2948 | + valueOf(0x4000000000000000L), valueOf(0x383d9170b85ff80bL), | |
| 2949 | + valueOf(0x4000000000000000L), valueOf(0x6765c793fa10079dL), | |
| 2950 | + valueOf(0x41c21cb8e1000000L), valueOf(0x3642798750226111L), | |
| 2951 | + valueOf(0x1000000000000000L), valueOf(0x12bf307ae81ffd59L), | |
| 2952 | + valueOf( 0xde0b6b3a7640000L), valueOf(0x4d28cb56c33fa539L), | |
| 2953 | + valueOf(0x1eca170c00000000L), valueOf(0x780c7372621bd74dL), | |
| 2954 | + valueOf(0x1e39a5057d810000L), valueOf(0x5b27ac993df97701L), | |
| 2955 | + valueOf(0x1000000000000000L), valueOf(0x27b95e997e21d9f1L), | |
| 2956 | + valueOf(0x5da0e1e53c5c8000L), valueOf( 0xb16a458ef403f19L), | |
| 2957 | + valueOf(0x16bcc41e90000000L), valueOf(0x2d04b7fdd9c0ef49L), | |
| 2958 | + valueOf(0x5658597bcaa24000L), valueOf( 0x6feb266931a75b7L), | |
| 2959 | + valueOf( 0xc29e98000000000L), valueOf(0x14adf4b7320334b9L), | |
| 2960 | + valueOf(0x226ed36478bfa000L), valueOf(0x383d9170b85ff80bL), | |
| 2961 | + valueOf(0x5a3c23e39c000000L), valueOf( 0x4e900abb53e6b71L), | |
| 2962 | + valueOf( 0x7600ec618141000L), valueOf( 0xaee5720ee830681L), | |
| 2963 | + valueOf(0x1000000000000000L), valueOf(0x172588ad4f5f0981L), | |
| 2964 | + valueOf(0x211e44f7d02c1000L), valueOf(0x2ee56725f06e5c71L), | |
| 2965 | + valueOf(0x41c21cb8e1000000L)}; | |
| 2966 | + | |
| 2967 | + /* | |
| 2968 | + * These two arrays are the integer analogue of above. | |
| 2969 | + */ | |
| 2970 | + private static int digitsPerInt[] = {0, 0, 30, 19, 15, 13, 11, | |
| 2971 | + 11, 10, 9, 9, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6, | |
| 2972 | + 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 5}; | |
| 2973 | + | |
| 2974 | + private static int intRadix[] = {0, 0, | |
| 2975 | + 0x40000000, 0x4546b3db, 0x40000000, 0x48c27395, 0x159fd800, | |
| 2976 | + 0x75db9c97, 0x40000000, 0x17179149, 0x3b9aca00, 0xcc6db61, | |
| 2977 | + 0x19a10000, 0x309f1021, 0x57f6c100, 0xa2f1b6f, 0x10000000, | |
| 2978 | + 0x18754571, 0x247dbc80, 0x3547667b, 0x4c4b4000, 0x6b5a6e1d, | |
| 2979 | + 0x6c20a40, 0x8d2d931, 0xb640000, 0xe8d4a51, 0x1269ae40, | |
| 2980 | + 0x17179149, 0x1cb91000, 0x23744899, 0x2b73a840, 0x34e63b41, | |
| 2981 | + 0x40000000, 0x4cfa3cc1, 0x5c13d840, 0x6d91b519, 0x39aa400 | |
| 2982 | + }; | |
| 2983 | + | |
| 2984 | + /** | |
| 2985 | + * These routines provide access to the two's complement representation | |
| 2986 | + * of BigIntegers. | |
| 2987 | + */ | |
| 2988 | + | |
| 2989 | + /** | |
| 2990 | + * Returns the length of the two's complement representation in ints, | |
| 2991 | + * including space for at least one sign bit. | |
| 2992 | + */ | |
| 2993 | + private int intLength() { | |
| 2994 | + return (bitLength() >>> 5) + 1; | |
| 2995 | + } | |
| 2996 | + | |
| 2997 | + /* Returns sign bit */ | |
| 2998 | + private int signBit() { | |
| 2999 | + return signum < 0 ? 1 : 0; | |
| 3000 | + } | |
| 3001 | + | |
| 3002 | + /* Returns an int of sign bits */ | |
| 3003 | + private int signInt() { | |
| 3004 | + return signum < 0 ? -1 : 0; | |
| 3005 | + } | |
| 3006 | + | |
| 3007 | + /** | |
| 3008 | + * Returns the specified int of the little-endian two's complement | |
| 3009 | + * representation (int 0 is the least significant). The int number can | |
| 3010 | + * be arbitrarily high (values are logically preceded by infinitely many | |
| 3011 | + * sign ints). | |
| 3012 | + */ | |
| 3013 | + private int getInt(int n) { | |
| 3014 | + if (n < 0) | |
| 3015 | + return 0; | |
| 3016 | + if (n >= mag.length) | |
| 3017 | + return signInt(); | |
| 3018 | + | |
| 3019 | + int magInt = mag[mag.length-n-1]; | |
| 3020 | + | |
| 3021 | + return (signum >= 0 ? magInt : | |
| 3022 | + (n <= firstNonzeroIntNum() ? -magInt : ~magInt)); | |
| 3023 | + } | |
| 3024 | + | |
| 3025 | + /** | |
| 3026 | + * Returns the index of the int that contains the first nonzero int in the | |
| 3027 | + * little-endian binary representation of the magnitude (int 0 is the | |
| 3028 | + * least significant). If the magnitude is zero, return value is undefined. | |
| 3029 | + */ | |
| 3030 | + private int firstNonzeroIntNum() { | |
| 3031 | + int fn = firstNonzeroIntNum - 2; | |
| 3032 | + if (fn == -2) { // firstNonzeroIntNum not initialized yet | |
| 3033 | + fn = 0; | |
| 3034 | + | |
| 3035 | + // Search for the first nonzero int | |
| 3036 | + int i; | |
| 3037 | + int mlen = mag.length; | |
| 3038 | + for (i = mlen - 1; i >= 0 && mag[i] == 0; i--) | |
| 3039 | + ; | |
| 3040 | + fn = mlen - i - 1; | |
| 3041 | + firstNonzeroIntNum = fn + 2; // offset by two to initialize | |
| 3042 | + } | |
| 3043 | + return fn; | |
| 3044 | + } | |
| 3045 | + | |
| 3046 | + /** use serialVersionUID from JDK 1.1. for interoperability */ | |
| 3047 | + private static final long serialVersionUID = -8287574255936472291L; | |
| 3048 | + | |
| 3049 | + /** | |
| 3050 | + * Serializable fields for BigInteger. | |
| 3051 | + * | |
| 3052 | + * @serialField signum int | |
| 3053 | + * signum of this BigInteger. | |
| 3054 | + * @serialField magnitude int[] | |
| 3055 | + * magnitude array of this BigInteger. | |
| 3056 | + * @serialField bitCount int | |
| 3057 | + * number of bits in this BigInteger | |
| 3058 | + * @serialField bitLength int | |
| 3059 | + * the number of bits in the minimal two's-complement | |
| 3060 | + * representation of this BigInteger | |
| 3061 | + * @serialField lowestSetBit int | |
| 3062 | + * lowest set bit in the twos complement representation | |
| 3063 | + */ | |
| 3064 | + private static final ObjectStreamField[] serialPersistentFields = { | |
| 3065 | + new ObjectStreamField("signum", Integer.TYPE), | |
| 3066 | + new ObjectStreamField("magnitude", byte[].class), | |
| 3067 | + new ObjectStreamField("bitCount", Integer.TYPE), | |
| 3068 | + new ObjectStreamField("bitLength", Integer.TYPE), | |
| 3069 | + new ObjectStreamField("firstNonzeroByteNum", Integer.TYPE), | |
| 3070 | + new ObjectStreamField("lowestSetBit", Integer.TYPE) | |
| 3071 | + }; | |
| 3072 | + | |
| 3073 | + /** | |
| 3074 | + * Reconstitute the {@code BigInteger} instance from a stream (that is, | |
| 3075 | + * deserialize it). The magnitude is read in as an array of bytes | |
| 3076 | + * for historical reasons, but it is converted to an array of ints | |
| 3077 | + * and the byte array is discarded. | |
| 3078 | + * Note: | |
| 3079 | + * The current convention is to initialize the cache fields, bitCount, | |
| 3080 | + * bitLength and lowestSetBit, to 0 rather than some other marker value. | |
| 3081 | + * Therefore, no explicit action to set these fields needs to be taken in | |
| 3082 | + * readObject because those fields already have a 0 value be default since | |
| 3083 | + * defaultReadObject is not being used. | |
| 3084 | + */ | |
| 3085 | + private void readObject(java.io.ObjectInputStream s) | |
| 3086 | + throws java.io.IOException, ClassNotFoundException { | |
| 3087 | + /* | |
| 3088 | + * In order to maintain compatibility with previous serialized forms, | |
| 3089 | + * the magnitude of a BigInteger is serialized as an array of bytes. | |
| 3090 | + * The magnitude field is used as a temporary store for the byte array | |
| 3091 | + * that is deserialized. The cached computation fields should be | |
| 3092 | + * transient but are serialized for compatibility reasons. | |
| 3093 | + */ | |
| 3094 | + | |
| 3095 | + // prepare to read the alternate persistent fields | |
| 3096 | + ObjectInputStream.GetField fields = s.readFields(); | |
| 3097 | + | |
| 3098 | + // Read the alternate persistent fields that we care about | |
| 3099 | + int sign = fields.get("signum", -2); | |
| 3100 | + byte[] magnitude = (byte[])fields.get("magnitude", null); | |
| 3101 | + | |
| 3102 | + // Validate signum | |
| 3103 | + if (sign < -1 || sign > 1) { | |
| 3104 | + String message = "BigInteger: Invalid signum value"; | |
| 3105 | + if (fields.defaulted("signum")) | |
| 3106 | + message = "BigInteger: Signum not present in stream"; | |
| 3107 | + throw new java.io.StreamCorruptedException(message); | |
| 3108 | + } | |
| 3109 | + if ((magnitude.length == 0) != (sign == 0)) { | |
| 3110 | + String message = "BigInteger: signum-magnitude mismatch"; | |
| 3111 | + if (fields.defaulted("magnitude")) | |
| 3112 | + message = "BigInteger: Magnitude not present in stream"; | |
| 3113 | + throw new java.io.StreamCorruptedException(message); | |
| 3114 | + } | |
| 3115 | + | |
| 3116 | + // Commit final fields via Unsafe | |
| 3117 | + unsafe.putIntVolatile(this, signumOffset, sign); | |
| 3118 | + | |
| 3119 | + // Calculate mag field from magnitude and discard magnitude | |
| 3120 | + unsafe.putObjectVolatile(this, magOffset, | |
| 3121 | + stripLeadingZeroBytes(magnitude)); | |
| 3122 | + } | |
| 3123 | + | |
| 3124 | + // Support for resetting final fields while deserializing | |
| 3125 | + private static final sun.misc.Unsafe unsafe = sun.misc.Unsafe.getUnsafe(); | |
| 3126 | + private static final long signumOffset; | |
| 3127 | + private static final long magOffset; | |
| 3128 | + static { | |
| 3129 | + try { | |
| 3130 | + signumOffset = unsafe.objectFieldOffset | |
| 3131 | + (BigInteger.class.getDeclaredField("signum")); | |
| 3132 | + magOffset = unsafe.objectFieldOffset | |
| 3133 | + (BigInteger.class.getDeclaredField("mag")); | |
| 3134 | + } catch (Exception ex) { | |
| 3135 | + throw new Error(ex); | |
| 3136 | + } | |
| 3137 | + } | |
| 3138 | + | |
| 3139 | + /** | |
| 3140 | + * Save the {@code BigInteger} instance to a stream. | |
| 3141 | + * The magnitude of a BigInteger is serialized as a byte array for | |
| 3142 | + * historical reasons. | |
| 3143 | + * | |
| 3144 | + * @serialData two necessary fields are written as well as obsolete | |
| 3145 | + * fields for compatibility with older versions. | |
| 3146 | + */ | |
| 3147 | + private void writeObject(ObjectOutputStream s) throws IOException { | |
| 3148 | + // set the values of the Serializable fields | |
| 3149 | + ObjectOutputStream.PutField fields = s.putFields(); | |
| 3150 | + fields.put("signum", signum); | |
| 3151 | + fields.put("magnitude", magSerializedForm()); | |
| 3152 | + // The values written for cached fields are compatible with older | |
| 3153 | + // versions, but are ignored in readObject so don't otherwise matter. | |
| 3154 | + fields.put("bitCount", -1); | |
| 3155 | + fields.put("bitLength", -1); | |
| 3156 | + fields.put("lowestSetBit", -2); | |
| 3157 | + fields.put("firstNonzeroByteNum", -2); | |
| 3158 | + | |
| 3159 | + // save them | |
| 3160 | + s.writeFields(); | |
| 3161 | +} | |
| 3162 | + | |
| 3163 | + /** | |
| 3164 | + * Returns the mag array as an array of bytes. | |
| 3165 | + */ | |
| 3166 | + private byte[] magSerializedForm() { | |
| 3167 | + int len = mag.length; | |
| 3168 | + | |
| 3169 | + int bitLen = (len == 0 ? 0 : ((len - 1) << 5) + bitLengthForInt(mag[0])); | |
| 3170 | + int byteLen = (bitLen + 7) >>> 3; | |
| 3171 | + byte[] result = new byte[byteLen]; | |
| 3172 | + | |
| 3173 | + for (int i = byteLen - 1, bytesCopied = 4, intIndex = len - 1, nextInt = 0; | |
| 3174 | + i>=0; i--) { | |
| 3175 | + if (bytesCopied == 4) { | |
| 3176 | + nextInt = mag[intIndex--]; | |
| 3177 | + bytesCopied = 1; | |
| 3178 | + } else { | |
| 3179 | + nextInt >>>= 8; | |
| 3180 | + bytesCopied++; | |
| 3181 | + } | |
| 3182 | + result[i] = (byte)nextInt; | |
| 3183 | + } | |
| 3184 | + return result; | |
| 3185 | + } | |
| 3186 | +} | |
Binary file not shown.
| @@ -0,0 +1,212 @@ | ||
| 1 | +/* | |
| 2 | + * Copyright (c) 1999, 2007, Oracle and/or its affiliates. All rights reserved. | |
| 3 | + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. | |
| 4 | + * | |
| 5 | + * This code is free software; you can redistribute it and/or modify it | |
| 6 | + * under the terms of the GNU General Public License version 2 only, as | |
| 7 | + * published by the Free Software Foundation. Oracle designates this | |
| 8 | + * particular file as subject to the "Classpath" exception as provided | |
| 9 | + * by Oracle in the LICENSE file that accompanied this code. | |
| 10 | + * | |
| 11 | + * This code is distributed in the hope that it will be useful, but WITHOUT | |
| 12 | + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or | |
| 13 | + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License | |
| 14 | + * version 2 for more details (a copy is included in the LICENSE file that | |
| 15 | + * accompanied this code). | |
| 16 | + * | |
| 17 | + * You should have received a copy of the GNU General Public License version | |
| 18 | + * 2 along with this work; if not, write to the Free Software Foundation, | |
| 19 | + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. | |
| 20 | + * | |
| 21 | + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA | |
| 22 | + * or visit www.oracle.com if you need additional information or have any | |
| 23 | + * questions. | |
| 24 | + */ | |
| 25 | + | |
| 26 | +package java.math; | |
| 27 | + | |
| 28 | +/** | |
| 29 | + * A simple bit sieve used for finding prime number candidates. Allows setting | |
| 30 | + * and clearing of bits in a storage array. The size of the sieve is assumed to | |
| 31 | + * be constant to reduce overhead. All the bits of a new bitSieve are zero, and | |
| 32 | + * bits are removed from it by setting them. | |
| 33 | + * | |
| 34 | + * To reduce storage space and increase efficiency, no even numbers are | |
| 35 | + * represented in the sieve (each bit in the sieve represents an odd number). | |
| 36 | + * The relationship between the index of a bit and the number it represents is | |
| 37 | + * given by | |
| 38 | + * N = offset + (2*index + 1); | |
| 39 | + * Where N is the integer represented by a bit in the sieve, offset is some | |
| 40 | + * even integer offset indicating where the sieve begins, and index is the | |
| 41 | + * index of a bit in the sieve array. | |
| 42 | + * | |
| 43 | + * @see BigInteger | |
| 44 | + * @author Michael McCloskey | |
| 45 | + * @since 1.3 | |
| 46 | + */ | |
| 47 | +class BitSieve { | |
| 48 | + /** | |
| 49 | + * Stores the bits in this bitSieve. | |
| 50 | + */ | |
| 51 | + private long bits[]; | |
| 52 | + | |
| 53 | + /** | |
| 54 | + * Length is how many bits this sieve holds. | |
| 55 | + */ | |
| 56 | + private int length; | |
| 57 | + | |
| 58 | + /** | |
| 59 | + * A small sieve used to filter out multiples of small primes in a search | |
| 60 | + * sieve. | |
| 61 | + */ | |
| 62 | + private static BitSieve smallSieve = new BitSieve(); | |
| 63 | + | |
| 64 | + /** | |
| 65 | + * Construct a "small sieve" with a base of 0. This constructor is | |
| 66 | + * used internally to generate the set of "small primes" whose multiples | |
| 67 | + * are excluded from sieves generated by the main (package private) | |
| 68 | + * constructor, BitSieve(BigInteger base, int searchLen). The length | |
| 69 | + * of the sieve generated by this constructor was chosen for performance; | |
| 70 | + * it controls a tradeoff between how much time is spent constructing | |
| 71 | + * other sieves, and how much time is wasted testing composite candidates | |
| 72 | + * for primality. The length was chosen experimentally to yield good | |
| 73 | + * performance. | |
| 74 | + */ | |
| 75 | + private BitSieve() { | |
| 76 | + length = 150 * 64; | |
| 77 | + bits = new long[(unitIndex(length - 1) + 1)]; | |
| 78 | + | |
| 79 | + // Mark 1 as composite | |
| 80 | + set(0); | |
| 81 | + int nextIndex = 1; | |
| 82 | + int nextPrime = 3; | |
| 83 | + | |
| 84 | + // Find primes and remove their multiples from sieve | |
| 85 | + do { | |
| 86 | + sieveSingle(length, nextIndex + nextPrime, nextPrime); | |
| 87 | + nextIndex = sieveSearch(length, nextIndex + 1); | |
| 88 | + nextPrime = 2*nextIndex + 1; | |
| 89 | + } while((nextIndex > 0) && (nextPrime < length)); | |
| 90 | + } | |
| 91 | + | |
| 92 | + /** | |
| 93 | + * Construct a bit sieve of searchLen bits used for finding prime number | |
| 94 | + * candidates. The new sieve begins at the specified base, which must | |
| 95 | + * be even. | |
| 96 | + */ | |
| 97 | + BitSieve(BigInteger base, int searchLen) { | |
| 98 | + /* | |
| 99 | + * Candidates are indicated by clear bits in the sieve. As a candidates | |
| 100 | + * nonprimality is calculated, a bit is set in the sieve to eliminate | |
| 101 | + * it. To reduce storage space and increase efficiency, no even numbers | |
| 102 | + * are represented in the sieve (each bit in the sieve represents an | |
| 103 | + * odd number). | |
| 104 | + */ | |
| 105 | + bits = new long[(unitIndex(searchLen-1) + 1)]; | |
| 106 | + length = searchLen; | |
| 107 | + int start = 0; | |
| 108 | + | |
| 109 | + int step = smallSieve.sieveSearch(smallSieve.length, start); | |
| 110 | + int convertedStep = (step *2) + 1; | |
| 111 | + | |
| 112 | + // Construct the large sieve at an even offset specified by base | |
| 113 | + MutableBigInteger b = new MutableBigInteger(base); | |
| 114 | + MutableBigInteger q = new MutableBigInteger(); | |
| 115 | + do { | |
| 116 | + // Calculate base mod convertedStep | |
| 117 | + start = b.divideOneWord(convertedStep, q); | |
| 118 | + | |
| 119 | + // Take each multiple of step out of sieve | |
| 120 | + start = convertedStep - start; | |
| 121 | + if (start%2 == 0) | |
| 122 | + start += convertedStep; | |
| 123 | + sieveSingle(searchLen, (start-1)/2, convertedStep); | |
| 124 | + | |
| 125 | + // Find next prime from small sieve | |
| 126 | + step = smallSieve.sieveSearch(smallSieve.length, step+1); | |
| 127 | + convertedStep = (step *2) + 1; | |
| 128 | + } while (step > 0); | |
| 129 | + } | |
| 130 | + | |
| 131 | + /** | |
| 132 | + * Given a bit index return unit index containing it. | |
| 133 | + */ | |
| 134 | + private static int unitIndex(int bitIndex) { | |
| 135 | + return bitIndex >>> 6; | |
| 136 | + } | |
| 137 | + | |
| 138 | + /** | |
| 139 | + * Return a unit that masks the specified bit in its unit. | |
| 140 | + */ | |
| 141 | + private static long bit(int bitIndex) { | |
| 142 | + return 1L << (bitIndex & ((1<<6) - 1)); | |
| 143 | + } | |
| 144 | + | |
| 145 | + /** | |
| 146 | + * Get the value of the bit at the specified index. | |
| 147 | + */ | |
| 148 | + private boolean get(int bitIndex) { | |
| 149 | + int unitIndex = unitIndex(bitIndex); | |
| 150 | + return ((bits[unitIndex] & bit(bitIndex)) != 0); | |
| 151 | + } | |
| 152 | + | |
| 153 | + /** | |
| 154 | + * Set the bit at the specified index. | |
| 155 | + */ | |
| 156 | + private void set(int bitIndex) { | |
| 157 | + int unitIndex = unitIndex(bitIndex); | |
| 158 | + bits[unitIndex] |= bit(bitIndex); | |
| 159 | + } | |
| 160 | + | |
| 161 | + /** | |
| 162 | + * This method returns the index of the first clear bit in the search | |
| 163 | + * array that occurs at or after start. It will not search past the | |
| 164 | + * specified limit. It returns -1 if there is no such clear bit. | |
| 165 | + */ | |
| 166 | + private int sieveSearch(int limit, int start) { | |
| 167 | + if (start >= limit) | |
| 168 | + return -1; | |
| 169 | + | |
| 170 | + int index = start; | |
| 171 | + do { | |
| 172 | + if (!get(index)) | |
| 173 | + return index; | |
| 174 | + index++; | |
| 175 | + } while(index < limit-1); | |
| 176 | + return -1; | |
| 177 | + } | |
| 178 | + | |
| 179 | + /** | |
| 180 | + * Sieve a single set of multiples out of the sieve. Begin to remove | |
| 181 | + * multiples of the specified step starting at the specified start index, | |
| 182 | + * up to the specified limit. | |
| 183 | + */ | |
| 184 | + private void sieveSingle(int limit, int start, int step) { | |
| 185 | + while(start < limit) { | |
| 186 | + set(start); | |
| 187 | + start += step; | |
| 188 | + } | |
| 189 | + } | |
| 190 | + | |
| 191 | + /** | |
| 192 | + * Test probable primes in the sieve and return successful candidates. | |
| 193 | + */ | |
| 194 | + BigInteger retrieve(BigInteger initValue, int certainty, java.util.Random random) { | |
| 195 | + // Examine the sieve one long at a time to find possible primes | |
| 196 | + int offset = 1; | |
| 197 | + for (int i=0; i<bits.length; i++) { | |
| 198 | + long nextLong = ~bits[i]; | |
| 199 | + for (int j=0; j<64; j++) { | |
| 200 | + if ((nextLong & 1) == 1) { | |
| 201 | + BigInteger candidate = initValue.add( | |
| 202 | + BigInteger.valueOf(offset)); | |
| 203 | + if (candidate.primeToCertainty(certainty, random)) | |
| 204 | + return candidate; | |
| 205 | + } | |
| 206 | + nextLong >>>= 1; | |
| 207 | + offset+=2; | |
| 208 | + } | |
| 209 | + } | |
| 210 | + return null; | |
| 211 | + } | |
| 212 | +} | |
Binary file not shown.
| @@ -0,0 +1,326 @@ | ||
| 1 | +/* | |
| 2 | + * Copyright (c) 2003, 2007, Oracle and/or its affiliates. All rights reserved. | |
| 3 | + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. | |
| 4 | + * | |
| 5 | + * This code is free software; you can redistribute it and/or modify it | |
| 6 | + * under the terms of the GNU General Public License version 2 only, as | |
| 7 | + * published by the Free Software Foundation. Oracle designates this | |
| 8 | + * particular file as subject to the "Classpath" exception as provided | |
| 9 | + * by Oracle in the LICENSE file that accompanied this code. | |
| 10 | + * | |
| 11 | + * This code is distributed in the hope that it will be useful, but WITHOUT | |
| 12 | + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or | |
| 13 | + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License | |
| 14 | + * version 2 for more details (a copy is included in the LICENSE file that | |
| 15 | + * accompanied this code). | |
| 16 | + * | |
| 17 | + * You should have received a copy of the GNU General Public License version | |
| 18 | + * 2 along with this work; if not, write to the Free Software Foundation, | |
| 19 | + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. | |
| 20 | + * | |
| 21 | + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA | |
| 22 | + * or visit www.oracle.com if you need additional information or have any | |
| 23 | + * questions. | |
| 24 | + */ | |
| 25 | + | |
| 26 | +/* | |
| 27 | + * Portions Copyright IBM Corporation, 1997, 2001. All Rights Reserved. | |
| 28 | + */ | |
| 29 | + | |
| 30 | +package java.math; | |
| 31 | +import java.io.*; | |
| 32 | + | |
| 33 | +/** | |
| 34 | + * Immutable objects which encapsulate the context settings which | |
| 35 | + * describe certain rules for numerical operators, such as those | |
| 36 | + * implemented by the {@link BigDecimal} class. | |
| 37 | + * | |
| 38 | + * <p>The base-independent settings are: | |
| 39 | + * <ol> | |
| 40 | + * <li>{@code precision}: | |
| 41 | + * the number of digits to be used for an operation; results are | |
| 42 | + * rounded to this precision | |
| 43 | + * | |
| 44 | + * <li>{@code roundingMode}: | |
| 45 | + * a {@link RoundingMode} object which specifies the algorithm to be | |
| 46 | + * used for rounding. | |
| 47 | + * </ol> | |
| 48 | + * | |
| 49 | + * @see BigDecimal | |
| 50 | + * @see RoundingMode | |
| 51 | + * @author Mike Cowlishaw | |
| 52 | + * @author Joseph D. Darcy | |
| 53 | + * @since 1.5 | |
| 54 | + */ | |
| 55 | + | |
| 56 | +public final class MathContext implements Serializable { | |
| 57 | + | |
| 58 | + /* ----- Constants ----- */ | |
| 59 | + | |
| 60 | + // defaults for constructors | |
| 61 | + private static final int DEFAULT_DIGITS = 9; | |
| 62 | + private static final RoundingMode DEFAULT_ROUNDINGMODE = RoundingMode.HALF_UP; | |
| 63 | + // Smallest values for digits (Maximum is Integer.MAX_VALUE) | |
| 64 | + private static final int MIN_DIGITS = 0; | |
| 65 | + | |
| 66 | + // Serialization version | |
| 67 | + private static final long serialVersionUID = 5579720004786848255L; | |
| 68 | + | |
| 69 | + /* ----- Public Properties ----- */ | |
| 70 | + /** | |
| 71 | + * A {@code MathContext} object whose settings have the values | |
| 72 | + * required for unlimited precision arithmetic. | |
| 73 | + * The values of the settings are: | |
| 74 | + * <code> | |
| 75 | + * precision=0 roundingMode=HALF_UP | |
| 76 | + * </code> | |
| 77 | + */ | |
| 78 | + public static final MathContext UNLIMITED = | |
| 79 | + new MathContext(0, RoundingMode.HALF_UP); | |
| 80 | + | |
| 81 | + /** | |
| 82 | + * A {@code MathContext} object with a precision setting | |
| 83 | + * matching the IEEE 754R Decimal32 format, 7 digits, and a | |
| 84 | + * rounding mode of {@link RoundingMode#HALF_EVEN HALF_EVEN}, the | |
| 85 | + * IEEE 754R default. | |
| 86 | + */ | |
| 87 | + public static final MathContext DECIMAL32 = | |
| 88 | + new MathContext(7, RoundingMode.HALF_EVEN); | |
| 89 | + | |
| 90 | + /** | |
| 91 | + * A {@code MathContext} object with a precision setting | |
| 92 | + * matching the IEEE 754R Decimal64 format, 16 digits, and a | |
| 93 | + * rounding mode of {@link RoundingMode#HALF_EVEN HALF_EVEN}, the | |
| 94 | + * IEEE 754R default. | |
| 95 | + */ | |
| 96 | + public static final MathContext DECIMAL64 = | |
| 97 | + new MathContext(16, RoundingMode.HALF_EVEN); | |
| 98 | + | |
| 99 | + /** | |
| 100 | + * A {@code MathContext} object with a precision setting | |
| 101 | + * matching the IEEE 754R Decimal128 format, 34 digits, and a | |
| 102 | + * rounding mode of {@link RoundingMode#HALF_EVEN HALF_EVEN}, the | |
| 103 | + * IEEE 754R default. | |
| 104 | + */ | |
| 105 | + public static final MathContext DECIMAL128 = | |
| 106 | + new MathContext(34, RoundingMode.HALF_EVEN); | |
| 107 | + | |
| 108 | + /* ----- Shared Properties ----- */ | |
| 109 | + /** | |
| 110 | + * The number of digits to be used for an operation. A value of 0 | |
| 111 | + * indicates that unlimited precision (as many digits as are | |
| 112 | + * required) will be used. Note that leading zeros (in the | |
| 113 | + * coefficient of a number) are never significant. | |
| 114 | + * | |
| 115 | + * <p>{@code precision} will always be non-negative. | |
| 116 | + * | |
| 117 | + * @serial | |
| 118 | + */ | |
| 119 | + final int precision; | |
| 120 | + | |
| 121 | + /** | |
| 122 | + * The rounding algorithm to be used for an operation. | |
| 123 | + * | |
| 124 | + * @see RoundingMode | |
| 125 | + * @serial | |
| 126 | + */ | |
| 127 | + final RoundingMode roundingMode; | |
| 128 | + | |
| 129 | + /* ----- Constructors ----- */ | |
| 130 | + | |
| 131 | + /** | |
| 132 | + * Constructs a new {@code MathContext} with the specified | |
| 133 | + * precision and the {@link RoundingMode#HALF_UP HALF_UP} rounding | |
| 134 | + * mode. | |
| 135 | + * | |
| 136 | + * @param setPrecision The non-negative {@code int} precision setting. | |
| 137 | + * @throws IllegalArgumentException if the {@code setPrecision} parameter is less | |
| 138 | + * than zero. | |
| 139 | + */ | |
| 140 | + public MathContext(int setPrecision) { | |
| 141 | + this(setPrecision, DEFAULT_ROUNDINGMODE); | |
| 142 | + return; | |
| 143 | + } | |
| 144 | + | |
| 145 | + /** | |
| 146 | + * Constructs a new {@code MathContext} with a specified | |
| 147 | + * precision and rounding mode. | |
| 148 | + * | |
| 149 | + * @param setPrecision The non-negative {@code int} precision setting. | |
| 150 | + * @param setRoundingMode The rounding mode to use. | |
| 151 | + * @throws IllegalArgumentException if the {@code setPrecision} parameter is less | |
| 152 | + * than zero. | |
| 153 | + * @throws NullPointerException if the rounding mode argument is {@code null} | |
| 154 | + */ | |
| 155 | + public MathContext(int setPrecision, | |
| 156 | + RoundingMode setRoundingMode) { | |
| 157 | + if (setPrecision < MIN_DIGITS) | |
| 158 | + throw new IllegalArgumentException("Digits < 0"); | |
| 159 | + if (setRoundingMode == null) | |
| 160 | + throw new NullPointerException("null RoundingMode"); | |
| 161 | + | |
| 162 | + precision = setPrecision; | |
| 163 | + roundingMode = setRoundingMode; | |
| 164 | + return; | |
| 165 | + } | |
| 166 | + | |
| 167 | + /** | |
| 168 | + * Constructs a new {@code MathContext} from a string. | |
| 169 | + * | |
| 170 | + * The string must be in the same format as that produced by the | |
| 171 | + * {@link #toString} method. | |
| 172 | + * | |
| 173 | + * <p>An {@code IllegalArgumentException} is thrown if the precision | |
| 174 | + * section of the string is out of range ({@code < 0}) or the string is | |
| 175 | + * not in the format created by the {@link #toString} method. | |
| 176 | + * | |
| 177 | + * @param val The string to be parsed | |
| 178 | + * @throws IllegalArgumentException if the precision section is out of range | |
| 179 | + * or of incorrect format | |
| 180 | + * @throws NullPointerException if the argument is {@code null} | |
| 181 | + */ | |
| 182 | + public MathContext(String val) { | |
| 183 | + boolean bad = false; | |
| 184 | + int setPrecision; | |
| 185 | + if (val == null) | |
| 186 | + throw new NullPointerException("null String"); | |
| 187 | + try { // any error here is a string format problem | |
| 188 | + if (!val.startsWith("precision=")) throw new RuntimeException(); | |
| 189 | + int fence = val.indexOf(' '); // could be -1 | |
| 190 | + int off = 10; // where value starts | |
| 191 | + setPrecision = Integer.parseInt(val.substring(10, fence)); | |
| 192 | + | |
| 193 | + if (!val.startsWith("roundingMode=", fence+1)) | |
| 194 | + throw new RuntimeException(); | |
| 195 | + off = fence + 1 + 13; | |
| 196 | + String str = val.substring(off, val.length()); | |
| 197 | + roundingMode = RoundingMode.valueOf(str); | |
| 198 | + } catch (RuntimeException re) { | |
| 199 | + throw new IllegalArgumentException("bad string format"); | |
| 200 | + } | |
| 201 | + | |
| 202 | + if (setPrecision < MIN_DIGITS) | |
| 203 | + throw new IllegalArgumentException("Digits < 0"); | |
| 204 | + // the other parameters cannot be invalid if we got here | |
| 205 | + precision = setPrecision; | |
| 206 | + } | |
| 207 | + | |
| 208 | + /** | |
| 209 | + * Returns the {@code precision} setting. | |
| 210 | + * This value is always non-negative. | |
| 211 | + * | |
| 212 | + * @return an {@code int} which is the value of the {@code precision} | |
| 213 | + * setting | |
| 214 | + */ | |
| 215 | + public int getPrecision() { | |
| 216 | + return precision; | |
| 217 | + } | |
| 218 | + | |
| 219 | + /** | |
| 220 | + * Returns the roundingMode setting. | |
| 221 | + * This will be one of | |
| 222 | + * {@link RoundingMode#CEILING}, | |
| 223 | + * {@link RoundingMode#DOWN}, | |
| 224 | + * {@link RoundingMode#FLOOR}, | |
| 225 | + * {@link RoundingMode#HALF_DOWN}, | |
| 226 | + * {@link RoundingMode#HALF_EVEN}, | |
| 227 | + * {@link RoundingMode#HALF_UP}, | |
| 228 | + * {@link RoundingMode#UNNECESSARY}, or | |
| 229 | + * {@link RoundingMode#UP}. | |
| 230 | + * | |
| 231 | + * @return a {@code RoundingMode} object which is the value of the | |
| 232 | + * {@code roundingMode} setting | |
| 233 | + */ | |
| 234 | + | |
| 235 | + public RoundingMode getRoundingMode() { | |
| 236 | + return roundingMode; | |
| 237 | + } | |
| 238 | + | |
| 239 | + /** | |
| 240 | + * Compares this {@code MathContext} with the specified | |
| 241 | + * {@code Object} for equality. | |
| 242 | + * | |
| 243 | + * @param x {@code Object} to which this {@code MathContext} is to | |
| 244 | + * be compared. | |
| 245 | + * @return {@code true} if and only if the specified {@code Object} is | |
| 246 | + * a {@code MathContext} object which has exactly the same | |
| 247 | + * settings as this object | |
| 248 | + */ | |
| 249 | + public boolean equals(Object x){ | |
| 250 | + MathContext mc; | |
| 251 | + if (!(x instanceof MathContext)) | |
| 252 | + return false; | |
| 253 | + mc = (MathContext) x; | |
| 254 | + return mc.precision == this.precision | |
| 255 | + && mc.roundingMode == this.roundingMode; // no need for .equals() | |
| 256 | + } | |
| 257 | + | |
| 258 | + /** | |
| 259 | + * Returns the hash code for this {@code MathContext}. | |
| 260 | + * | |
| 261 | + * @return hash code for this {@code MathContext} | |
| 262 | + */ | |
| 263 | + public int hashCode() { | |
| 264 | + return this.precision + roundingMode.hashCode() * 59; | |
| 265 | + } | |
| 266 | + | |
| 267 | + /** | |
| 268 | + * Returns the string representation of this {@code MathContext}. | |
| 269 | + * The {@code String} returned represents the settings of the | |
| 270 | + * {@code MathContext} object as two space-delimited words | |
| 271 | + * (separated by a single space character, <tt>'\u0020'</tt>, | |
| 272 | + * and with no leading or trailing white space), as follows: | |
| 273 | + * <ol> | |
| 274 | + * <li> | |
| 275 | + * The string {@code "precision="}, immediately followed | |
| 276 | + * by the value of the precision setting as a numeric string as if | |
| 277 | + * generated by the {@link Integer#toString(int) Integer.toString} | |
| 278 | + * method. | |
| 279 | + * | |
| 280 | + * <li> | |
| 281 | + * The string {@code "roundingMode="}, immediately | |
| 282 | + * followed by the value of the {@code roundingMode} setting as a | |
| 283 | + * word. This word will be the same as the name of the | |
| 284 | + * corresponding public constant in the {@link RoundingMode} | |
| 285 | + * enum. | |
| 286 | + * </ol> | |
| 287 | + * <p> | |
| 288 | + * For example: | |
| 289 | + * <pre> | |
| 290 | + * precision=9 roundingMode=HALF_UP | |
| 291 | + * </pre> | |
| 292 | + * | |
| 293 | + * Additional words may be appended to the result of | |
| 294 | + * {@code toString} in the future if more properties are added to | |
| 295 | + * this class. | |
| 296 | + * | |
| 297 | + * @return a {@code String} representing the context settings | |
| 298 | + */ | |
| 299 | + public java.lang.String toString() { | |
| 300 | + return "precision=" + precision + " " + | |
| 301 | + "roundingMode=" + roundingMode.toString(); | |
| 302 | + } | |
| 303 | + | |
| 304 | + // Private methods | |
| 305 | + | |
| 306 | + /** | |
| 307 | + * Reconstitute the {@code MathContext} instance from a stream (that is, | |
| 308 | + * deserialize it). | |
| 309 | + * | |
| 310 | + * @param s the stream being read. | |
| 311 | + */ | |
| 312 | + private void readObject(java.io.ObjectInputStream s) | |
| 313 | + throws java.io.IOException, ClassNotFoundException { | |
| 314 | + s.defaultReadObject(); // read in all fields | |
| 315 | + // validate possibly bad fields | |
| 316 | + if (precision < MIN_DIGITS) { | |
| 317 | + String message = "MathContext: invalid digits in stream"; | |
| 318 | + throw new java.io.StreamCorruptedException(message); | |
| 319 | + } | |
| 320 | + if (roundingMode == null) { | |
| 321 | + String message = "MathContext: null roundingMode in stream"; | |
| 322 | + throw new java.io.StreamCorruptedException(message); | |
| 323 | + } | |
| 324 | + } | |
| 325 | + | |
| 326 | +} | |
Binary file not shown.
| @@ -0,0 +1,1477 @@ | ||
| 1 | +/* | |
| 2 | + * Copyright (c) 1999, 2007, Oracle and/or its affiliates. All rights reserved. | |
| 3 | + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. | |
| 4 | + * | |
| 5 | + * This code is free software; you can redistribute it and/or modify it | |
| 6 | + * under the terms of the GNU General Public License version 2 only, as | |
| 7 | + * published by the Free Software Foundation. Oracle designates this | |
| 8 | + * particular file as subject to the "Classpath" exception as provided | |
| 9 | + * by Oracle in the LICENSE file that accompanied this code. | |
| 10 | + * | |
| 11 | + * This code is distributed in the hope that it will be useful, but WITHOUT | |
| 12 | + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or | |
| 13 | + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License | |
| 14 | + * version 2 for more details (a copy is included in the LICENSE file that | |
| 15 | + * accompanied this code). | |
| 16 | + * | |
| 17 | + * You should have received a copy of the GNU General Public License version | |
| 18 | + * 2 along with this work; if not, write to the Free Software Foundation, | |
| 19 | + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. | |
| 20 | + * | |
| 21 | + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA | |
| 22 | + * or visit www.oracle.com if you need additional information or have any | |
| 23 | + * questions. | |
| 24 | + */ | |
| 25 | + | |
| 26 | +package java.math; | |
| 27 | + | |
| 28 | +/** | |
| 29 | + * A class used to represent multiprecision integers that makes efficient | |
| 30 | + * use of allocated space by allowing a number to occupy only part of | |
| 31 | + * an array so that the arrays do not have to be reallocated as often. | |
| 32 | + * When performing an operation with many iterations the array used to | |
| 33 | + * hold a number is only reallocated when necessary and does not have to | |
| 34 | + * be the same size as the number it represents. A mutable number allows | |
| 35 | + * calculations to occur on the same number without having to create | |
| 36 | + * a new number for every step of the calculation as occurs with | |
| 37 | + * BigIntegers. | |
| 38 | + * | |
| 39 | + * @see BigInteger | |
| 40 | + * @author Michael McCloskey | |
| 41 | + * @since 1.3 | |
| 42 | + */ | |
| 43 | + | |
| 44 | +import java.util.Arrays; | |
| 45 | + | |
| 46 | +import static java.math.BigInteger.LONG_MASK; | |
| 47 | +import static java.math.BigDecimal.INFLATED; | |
| 48 | + | |
| 49 | +class MutableBigInteger { | |
| 50 | + /** | |
| 51 | + * Holds the magnitude of this MutableBigInteger in big endian order. | |
| 52 | + * The magnitude may start at an offset into the value array, and it may | |
| 53 | + * end before the length of the value array. | |
| 54 | + */ | |
| 55 | + int[] value; | |
| 56 | + | |
| 57 | + /** | |
| 58 | + * The number of ints of the value array that are currently used | |
| 59 | + * to hold the magnitude of this MutableBigInteger. The magnitude starts | |
| 60 | + * at an offset and offset + intLen may be less than value.length. | |
| 61 | + */ | |
| 62 | + int intLen; | |
| 63 | + | |
| 64 | + /** | |
| 65 | + * The offset into the value array where the magnitude of this | |
| 66 | + * MutableBigInteger begins. | |
| 67 | + */ | |
| 68 | + int offset = 0; | |
| 69 | + | |
| 70 | + // Constants | |
| 71 | + /** | |
| 72 | + * MutableBigInteger with one element value array with the value 1. Used by | |
| 73 | + * BigDecimal divideAndRound to increment the quotient. Use this constant | |
| 74 | + * only when the method is not going to modify this object. | |
| 75 | + */ | |
| 76 | + static final MutableBigInteger ONE = new MutableBigInteger(1); | |
| 77 | + | |
| 78 | + // Constructors | |
| 79 | + | |
| 80 | + /** | |
| 81 | + * The default constructor. An empty MutableBigInteger is created with | |
| 82 | + * a one word capacity. | |
| 83 | + */ | |
| 84 | + MutableBigInteger() { | |
| 85 | + value = new int[1]; | |
| 86 | + intLen = 0; | |
| 87 | + } | |
| 88 | + | |
| 89 | + /** | |
| 90 | + * Construct a new MutableBigInteger with a magnitude specified by | |
| 91 | + * the int val. | |
| 92 | + */ | |
| 93 | + MutableBigInteger(int val) { | |
| 94 | + value = new int[1]; | |
| 95 | + intLen = 1; | |
| 96 | + value[0] = val; | |
| 97 | + } | |
| 98 | + | |
| 99 | + /** | |
| 100 | + * Construct a new MutableBigInteger with the specified value array | |
| 101 | + * up to the length of the array supplied. | |
| 102 | + */ | |
| 103 | + MutableBigInteger(int[] val) { | |
| 104 | + value = val; | |
| 105 | + intLen = val.length; | |
| 106 | + } | |
| 107 | + | |
| 108 | + /** | |
| 109 | + * Construct a new MutableBigInteger with a magnitude equal to the | |
| 110 | + * specified BigInteger. | |
| 111 | + */ | |
| 112 | + MutableBigInteger(BigInteger b) { | |
| 113 | + intLen = b.mag.length; | |
| 114 | + value = Arrays.copyOf(b.mag, intLen); | |
| 115 | + } | |
| 116 | + | |
| 117 | + /** | |
| 118 | + * Construct a new MutableBigInteger with a magnitude equal to the | |
| 119 | + * specified MutableBigInteger. | |
| 120 | + */ | |
| 121 | + MutableBigInteger(MutableBigInteger val) { | |
| 122 | + intLen = val.intLen; | |
| 123 | + value = Arrays.copyOfRange(val.value, val.offset, val.offset + intLen); | |
| 124 | + } | |
| 125 | + | |
| 126 | + /** | |
| 127 | + * Internal helper method to return the magnitude array. The caller is not | |
| 128 | + * supposed to modify the returned array. | |
| 129 | + */ | |
| 130 | + private int[] getMagnitudeArray() { | |
| 131 | + if (offset > 0 || value.length != intLen) | |
| 132 | + return Arrays.copyOfRange(value, offset, offset + intLen); | |
| 133 | + return value; | |
| 134 | + } | |
| 135 | + | |
| 136 | + /** | |
| 137 | + * Convert this MutableBigInteger to a long value. The caller has to make | |
| 138 | + * sure this MutableBigInteger can be fit into long. | |
| 139 | + */ | |
| 140 | + private long toLong() { | |
| 141 | + assert (intLen <= 2) : "this MutableBigInteger exceeds the range of long"; | |
| 142 | + if (intLen == 0) | |
| 143 | + return 0; | |
| 144 | + long d = value[offset] & LONG_MASK; | |
| 145 | + return (intLen == 2) ? d << 32 | (value[offset + 1] & LONG_MASK) : d; | |
| 146 | + } | |
| 147 | + | |
| 148 | + /** | |
| 149 | + * Convert this MutableBigInteger to a BigInteger object. | |
| 150 | + */ | |
| 151 | + BigInteger toBigInteger(int sign) { | |
| 152 | + if (intLen == 0 || sign == 0) | |
| 153 | + return BigInteger.ZERO; | |
| 154 | + return new BigInteger(getMagnitudeArray(), sign); | |
| 155 | + } | |
| 156 | + | |
| 157 | + /** | |
| 158 | + * Convert this MutableBigInteger to BigDecimal object with the specified sign | |
| 159 | + * and scale. | |
| 160 | + */ | |
| 161 | + BigDecimal toBigDecimal(int sign, int scale) { | |
| 162 | + if (intLen == 0 || sign == 0) | |
| 163 | + return BigDecimal.valueOf(0, scale); | |
| 164 | + int[] mag = getMagnitudeArray(); | |
| 165 | + int len = mag.length; | |
| 166 | + int d = mag[0]; | |
| 167 | + // If this MutableBigInteger can't be fit into long, we need to | |
| 168 | + // make a BigInteger object for the resultant BigDecimal object. | |
| 169 | + if (len > 2 || (d < 0 && len == 2)) | |
| 170 | + return new BigDecimal(new BigInteger(mag, sign), INFLATED, scale, 0); | |
| 171 | + long v = (len == 2) ? | |
| 172 | + ((mag[1] & LONG_MASK) | (d & LONG_MASK) << 32) : | |
| 173 | + d & LONG_MASK; | |
| 174 | + return new BigDecimal(null, sign == -1 ? -v : v, scale, 0); | |
| 175 | + } | |
| 176 | + | |
| 177 | + /** | |
| 178 | + * Clear out a MutableBigInteger for reuse. | |
| 179 | + */ | |
| 180 | + void clear() { | |
| 181 | + offset = intLen = 0; | |
| 182 | + for (int index=0, n=value.length; index < n; index++) | |
| 183 | + value[index] = 0; | |
| 184 | + } | |
| 185 | + | |
| 186 | + /** | |
| 187 | + * Set a MutableBigInteger to zero, removing its offset. | |
| 188 | + */ | |
| 189 | + void reset() { | |
| 190 | + offset = intLen = 0; | |
| 191 | + } | |
| 192 | + | |
| 193 | + /** | |
| 194 | + * Compare the magnitude of two MutableBigIntegers. Returns -1, 0 or 1 | |
| 195 | + * as this MutableBigInteger is numerically less than, equal to, or | |
| 196 | + * greater than <tt>b</tt>. | |
| 197 | + */ | |
| 198 | + final int compare(MutableBigInteger b) { | |
| 199 | + int blen = b.intLen; | |
| 200 | + if (intLen < blen) | |
| 201 | + return -1; | |
| 202 | + if (intLen > blen) | |
| 203 | + return 1; | |
| 204 | + | |
| 205 | + // Add Integer.MIN_VALUE to make the comparison act as unsigned integer | |
| 206 | + // comparison. | |
| 207 | + int[] bval = b.value; | |
| 208 | + for (int i = offset, j = b.offset; i < intLen + offset; i++, j++) { | |
| 209 | + int b1 = value[i] + 0x80000000; | |
| 210 | + int b2 = bval[j] + 0x80000000; | |
| 211 | + if (b1 < b2) | |
| 212 | + return -1; | |
| 213 | + if (b1 > b2) | |
| 214 | + return 1; | |
| 215 | + } | |
| 216 | + return 0; | |
| 217 | + } | |
| 218 | + | |
| 219 | + /** | |
| 220 | + * Compare this against half of a MutableBigInteger object (Needed for | |
| 221 | + * remainder tests). | |
| 222 | + * Assumes no leading unnecessary zeros, which holds for results | |
| 223 | + * from divide(). | |
| 224 | + */ | |
| 225 | + final int compareHalf(MutableBigInteger b) { | |
| 226 | + int blen = b.intLen; | |
| 227 | + int len = intLen; | |
| 228 | + if (len <= 0) | |
| 229 | + return blen <=0 ? 0 : -1; | |
| 230 | + if (len > blen) | |
| 231 | + return 1; | |
| 232 | + if (len < blen - 1) | |
| 233 | + return -1; | |
| 234 | + int[] bval = b.value; | |
| 235 | + int bstart = 0; | |
| 236 | + int carry = 0; | |
| 237 | + // Only 2 cases left:len == blen or len == blen - 1 | |
| 238 | + if (len != blen) { // len == blen - 1 | |
| 239 | + if (bval[bstart] == 1) { | |
| 240 | + ++bstart; | |
| 241 | + carry = 0x80000000; | |
| 242 | + } else | |
| 243 | + return -1; | |
| 244 | + } | |
| 245 | + // compare values with right-shifted values of b, | |
| 246 | + // carrying shifted-out bits across words | |
| 247 | + int[] val = value; | |
| 248 | + for (int i = offset, j = bstart; i < len + offset;) { | |
| 249 | + int bv = bval[j++]; | |
| 250 | + long hb = ((bv >>> 1) + carry) & LONG_MASK; | |
| 251 | + long v = val[i++] & LONG_MASK; | |
| 252 | + if (v != hb) | |
| 253 | + return v < hb ? -1 : 1; | |
| 254 | + carry = (bv & 1) << 31; // carray will be either 0x80000000 or 0 | |
| 255 | + } | |
| 256 | + return carry == 0? 0 : -1; | |
| 257 | + } | |
| 258 | + | |
| 259 | + /** | |
| 260 | + * Return the index of the lowest set bit in this MutableBigInteger. If the | |
| 261 | + * magnitude of this MutableBigInteger is zero, -1 is returned. | |
| 262 | + */ | |
| 263 | + private final int getLowestSetBit() { | |
| 264 | + if (intLen == 0) | |
| 265 | + return -1; | |
| 266 | + int j, b; | |
| 267 | + for (j=intLen-1; (j>0) && (value[j+offset]==0); j--) | |
| 268 | + ; | |
| 269 | + b = value[j+offset]; | |
| 270 | + if (b==0) | |
| 271 | + return -1; | |
| 272 | + return ((intLen-1-j)<<5) + Integer.numberOfTrailingZeros(b); | |
| 273 | + } | |
| 274 | + | |
| 275 | + /** | |
| 276 | + * Return the int in use in this MutableBigInteger at the specified | |
| 277 | + * index. This method is not used because it is not inlined on all | |
| 278 | + * platforms. | |
| 279 | + */ | |
| 280 | + private final int getInt(int index) { | |
| 281 | + return value[offset+index]; | |
| 282 | + } | |
| 283 | + | |
| 284 | + /** | |
| 285 | + * Return a long which is equal to the unsigned value of the int in | |
| 286 | + * use in this MutableBigInteger at the specified index. This method is | |
| 287 | + * not used because it is not inlined on all platforms. | |
| 288 | + */ | |
| 289 | + private final long getLong(int index) { | |
| 290 | + return value[offset+index] & LONG_MASK; | |
| 291 | + } | |
| 292 | + | |
| 293 | + /** | |
| 294 | + * Ensure that the MutableBigInteger is in normal form, specifically | |
| 295 | + * making sure that there are no leading zeros, and that if the | |
| 296 | + * magnitude is zero, then intLen is zero. | |
| 297 | + */ | |
| 298 | + final void normalize() { | |
| 299 | + if (intLen == 0) { | |
| 300 | + offset = 0; | |
| 301 | + return; | |
| 302 | + } | |
| 303 | + | |
| 304 | + int index = offset; | |
| 305 | + if (value[index] != 0) | |
| 306 | + return; | |
| 307 | + | |
| 308 | + int indexBound = index+intLen; | |
| 309 | + do { | |
| 310 | + index++; | |
| 311 | + } while(index < indexBound && value[index]==0); | |
| 312 | + | |
| 313 | + int numZeros = index - offset; | |
| 314 | + intLen -= numZeros; | |
| 315 | + offset = (intLen==0 ? 0 : offset+numZeros); | |
| 316 | + } | |
| 317 | + | |
| 318 | + /** | |
| 319 | + * If this MutableBigInteger cannot hold len words, increase the size | |
| 320 | + * of the value array to len words. | |
| 321 | + */ | |
| 322 | + private final void ensureCapacity(int len) { | |
| 323 | + if (value.length < len) { | |
| 324 | + value = new int[len]; | |
| 325 | + offset = 0; | |
| 326 | + intLen = len; | |
| 327 | + } | |
| 328 | + } | |
| 329 | + | |
| 330 | + /** | |
| 331 | + * Convert this MutableBigInteger into an int array with no leading | |
| 332 | + * zeros, of a length that is equal to this MutableBigInteger's intLen. | |
| 333 | + */ | |
| 334 | + int[] toIntArray() { | |
| 335 | + int[] result = new int[intLen]; | |
| 336 | + for(int i=0; i<intLen; i++) | |
| 337 | + result[i] = value[offset+i]; | |
| 338 | + return result; | |
| 339 | + } | |
| 340 | + | |
| 341 | + /** | |
| 342 | + * Sets the int at index+offset in this MutableBigInteger to val. | |
| 343 | + * This does not get inlined on all platforms so it is not used | |
| 344 | + * as often as originally intended. | |
| 345 | + */ | |
| 346 | + void setInt(int index, int val) { | |
| 347 | + value[offset + index] = val; | |
| 348 | + } | |
| 349 | + | |
| 350 | + /** | |
| 351 | + * Sets this MutableBigInteger's value array to the specified array. | |
| 352 | + * The intLen is set to the specified length. | |
| 353 | + */ | |
| 354 | + void setValue(int[] val, int length) { | |
| 355 | + value = val; | |
| 356 | + intLen = length; | |
| 357 | + offset = 0; | |
| 358 | + } | |
| 359 | + | |
| 360 | + /** | |
| 361 | + * Sets this MutableBigInteger's value array to a copy of the specified | |
| 362 | + * array. The intLen is set to the length of the new array. | |
| 363 | + */ | |
| 364 | + void copyValue(MutableBigInteger src) { | |
| 365 | + int len = src.intLen; | |
| 366 | + if (value.length < len) | |
| 367 | + value = new int[len]; | |
| 368 | + System.arraycopy(src.value, src.offset, value, 0, len); | |
| 369 | + intLen = len; | |
| 370 | + offset = 0; | |
| 371 | + } | |
| 372 | + | |
| 373 | + /** | |
| 374 | + * Sets this MutableBigInteger's value array to a copy of the specified | |
| 375 | + * array. The intLen is set to the length of the specified array. | |
| 376 | + */ | |
| 377 | + void copyValue(int[] val) { | |
| 378 | + int len = val.length; | |
| 379 | + if (value.length < len) | |
| 380 | + value = new int[len]; | |
| 381 | + System.arraycopy(val, 0, value, 0, len); | |
| 382 | + intLen = len; | |
| 383 | + offset = 0; | |
| 384 | + } | |
| 385 | + | |
| 386 | + /** | |
| 387 | + * Returns true iff this MutableBigInteger has a value of one. | |
| 388 | + */ | |
| 389 | + boolean isOne() { | |
| 390 | + return (intLen == 1) && (value[offset] == 1); | |
| 391 | + } | |
| 392 | + | |
| 393 | + /** | |
| 394 | + * Returns true iff this MutableBigInteger has a value of zero. | |
| 395 | + */ | |
| 396 | + boolean isZero() { | |
| 397 | + return (intLen == 0); | |
| 398 | + } | |
| 399 | + | |
| 400 | + /** | |
| 401 | + * Returns true iff this MutableBigInteger is even. | |
| 402 | + */ | |
| 403 | + boolean isEven() { | |
| 404 | + return (intLen == 0) || ((value[offset + intLen - 1] & 1) == 0); | |
| 405 | + } | |
| 406 | + | |
| 407 | + /** | |
| 408 | + * Returns true iff this MutableBigInteger is odd. | |
| 409 | + */ | |
| 410 | + boolean isOdd() { | |
| 411 | + return isZero() ? false : ((value[offset + intLen - 1] & 1) == 1); | |
| 412 | + } | |
| 413 | + | |
| 414 | + /** | |
| 415 | + * Returns true iff this MutableBigInteger is in normal form. A | |
| 416 | + * MutableBigInteger is in normal form if it has no leading zeros | |
| 417 | + * after the offset, and intLen + offset <= value.length. | |
| 418 | + */ | |
| 419 | + boolean isNormal() { | |
| 420 | + if (intLen + offset > value.length) | |
| 421 | + return false; | |
| 422 | + if (intLen ==0) | |
| 423 | + return true; | |
| 424 | + return (value[offset] != 0); | |
| 425 | + } | |
| 426 | + | |
| 427 | + /** | |
| 428 | + * Returns a String representation of this MutableBigInteger in radix 10. | |
| 429 | + */ | |
| 430 | + public String toString() { | |
| 431 | + BigInteger b = toBigInteger(1); | |
| 432 | + return b.toString(); | |
| 433 | + } | |
| 434 | + | |
| 435 | + /** | |
| 436 | + * Right shift this MutableBigInteger n bits. The MutableBigInteger is left | |
| 437 | + * in normal form. | |
| 438 | + */ | |
| 439 | + void rightShift(int n) { | |
| 440 | + if (intLen == 0) | |
| 441 | + return; | |
| 442 | + int nInts = n >>> 5; | |
| 443 | + int nBits = n & 0x1F; | |
| 444 | + this.intLen -= nInts; | |
| 445 | + if (nBits == 0) | |
| 446 | + return; | |
| 447 | + int bitsInHighWord = BigInteger.bitLengthForInt(value[offset]); | |
| 448 | + if (nBits >= bitsInHighWord) { | |
| 449 | + this.primitiveLeftShift(32 - nBits); | |
| 450 | + this.intLen--; | |
| 451 | + } else { | |
| 452 | + primitiveRightShift(nBits); | |
| 453 | + } | |
| 454 | + } | |
| 455 | + | |
| 456 | + /** | |
| 457 | + * Left shift this MutableBigInteger n bits. | |
| 458 | + */ | |
| 459 | + void leftShift(int n) { | |
| 460 | + /* | |
| 461 | + * If there is enough storage space in this MutableBigInteger already | |
| 462 | + * the available space will be used. Space to the right of the used | |
| 463 | + * ints in the value array is faster to utilize, so the extra space | |
| 464 | + * will be taken from the right if possible. | |
| 465 | + */ | |
| 466 | + if (intLen == 0) | |
| 467 | + return; | |
| 468 | + int nInts = n >>> 5; | |
| 469 | + int nBits = n&0x1F; | |
| 470 | + int bitsInHighWord = BigInteger.bitLengthForInt(value[offset]); | |
| 471 | + | |
| 472 | + // If shift can be done without moving words, do so | |
| 473 | + if (n <= (32-bitsInHighWord)) { | |
| 474 | + primitiveLeftShift(nBits); | |
| 475 | + return; | |
| 476 | + } | |
| 477 | + | |
| 478 | + int newLen = intLen + nInts +1; | |
| 479 | + if (nBits <= (32-bitsInHighWord)) | |
| 480 | + newLen--; | |
| 481 | + if (value.length < newLen) { | |
| 482 | + // The array must grow | |
| 483 | + int[] result = new int[newLen]; | |
| 484 | + for (int i=0; i<intLen; i++) | |
| 485 | + result[i] = value[offset+i]; | |
| 486 | + setValue(result, newLen); | |
| 487 | + } else if (value.length - offset >= newLen) { | |
| 488 | + // Use space on right | |
| 489 | + for(int i=0; i<newLen - intLen; i++) | |
| 490 | + value[offset+intLen+i] = 0; | |
| 491 | + } else { | |
| 492 | + // Must use space on left | |
| 493 | + for (int i=0; i<intLen; i++) | |
| 494 | + value[i] = value[offset+i]; | |
| 495 | + for (int i=intLen; i<newLen; i++) | |
| 496 | + value[i] = 0; | |
| 497 | + offset = 0; | |
| 498 | + } | |
| 499 | + intLen = newLen; | |
| 500 | + if (nBits == 0) | |
| 501 | + return; | |
| 502 | + if (nBits <= (32-bitsInHighWord)) | |
| 503 | + primitiveLeftShift(nBits); | |
| 504 | + else | |
| 505 | + primitiveRightShift(32 -nBits); | |
| 506 | + } | |
| 507 | + | |
| 508 | + /** | |
| 509 | + * A primitive used for division. This method adds in one multiple of the | |
| 510 | + * divisor a back to the dividend result at a specified offset. It is used | |
| 511 | + * when qhat was estimated too large, and must be adjusted. | |
| 512 | + */ | |
| 513 | + private int divadd(int[] a, int[] result, int offset) { | |
| 514 | + long carry = 0; | |
| 515 | + | |
| 516 | + for (int j=a.length-1; j >= 0; j--) { | |
| 517 | + long sum = (a[j] & LONG_MASK) + | |
| 518 | + (result[j+offset] & LONG_MASK) + carry; | |
| 519 | + result[j+offset] = (int)sum; | |
| 520 | + carry = sum >>> 32; | |
| 521 | + } | |
| 522 | + return (int)carry; | |
| 523 | + } | |
| 524 | + | |
| 525 | + /** | |
| 526 | + * This method is used for division. It multiplies an n word input a by one | |
| 527 | + * word input x, and subtracts the n word product from q. This is needed | |
| 528 | + * when subtracting qhat*divisor from dividend. | |
| 529 | + */ | |
| 530 | + private int mulsub(int[] q, int[] a, int x, int len, int offset) { | |
| 531 | + long xLong = x & LONG_MASK; | |
| 532 | + long carry = 0; | |
| 533 | + offset += len; | |
| 534 | + | |
| 535 | + for (int j=len-1; j >= 0; j--) { | |
| 536 | + long product = (a[j] & LONG_MASK) * xLong + carry; | |
| 537 | + long difference = q[offset] - product; | |
| 538 | + q[offset--] = (int)difference; | |
| 539 | + carry = (product >>> 32) | |
| 540 | + + (((difference & LONG_MASK) > | |
| 541 | + (((~(int)product) & LONG_MASK))) ? 1:0); | |
| 542 | + } | |
| 543 | + return (int)carry; | |
| 544 | + } | |
| 545 | + | |
| 546 | + /** | |
| 547 | + * Right shift this MutableBigInteger n bits, where n is | |
| 548 | + * less than 32. | |
| 549 | + * Assumes that intLen > 0, n > 0 for speed | |
| 550 | + */ | |
| 551 | + private final void primitiveRightShift(int n) { | |
| 552 | + int[] val = value; | |
| 553 | + int n2 = 32 - n; | |
| 554 | + for (int i=offset+intLen-1, c=val[i]; i>offset; i--) { | |
| 555 | + int b = c; | |
| 556 | + c = val[i-1]; | |
| 557 | + val[i] = (c << n2) | (b >>> n); | |
| 558 | + } | |
| 559 | + val[offset] >>>= n; | |
| 560 | + } | |
| 561 | + | |
| 562 | + /** | |
| 563 | + * Left shift this MutableBigInteger n bits, where n is | |
| 564 | + * less than 32. | |
| 565 | + * Assumes that intLen > 0, n > 0 for speed | |
| 566 | + */ | |
| 567 | + private final void primitiveLeftShift(int n) { | |
| 568 | + int[] val = value; | |
| 569 | + int n2 = 32 - n; | |
| 570 | + for (int i=offset, c=val[i], m=i+intLen-1; i<m; i++) { | |
| 571 | + int b = c; | |
| 572 | + c = val[i+1]; | |
| 573 | + val[i] = (b << n) | (c >>> n2); | |
| 574 | + } | |
| 575 | + val[offset+intLen-1] <<= n; | |
| 576 | + } | |
| 577 | + | |
| 578 | + /** | |
| 579 | + * Adds the contents of two MutableBigInteger objects.The result | |
| 580 | + * is placed within this MutableBigInteger. | |
| 581 | + * The contents of the addend are not changed. | |
| 582 | + */ | |
| 583 | + void add(MutableBigInteger addend) { | |
| 584 | + int x = intLen; | |
| 585 | + int y = addend.intLen; | |
| 586 | + int resultLen = (intLen > addend.intLen ? intLen : addend.intLen); | |
| 587 | + int[] result = (value.length < resultLen ? new int[resultLen] : value); | |
| 588 | + | |
| 589 | + int rstart = result.length-1; | |
| 590 | + long sum; | |
| 591 | + long carry = 0; | |
| 592 | + | |
| 593 | + // Add common parts of both numbers | |
| 594 | + while(x>0 && y>0) { | |
| 595 | + x--; y--; | |
| 596 | + sum = (value[x+offset] & LONG_MASK) + | |
| 597 | + (addend.value[y+addend.offset] & LONG_MASK) + carry; | |
| 598 | + result[rstart--] = (int)sum; | |
| 599 | + carry = sum >>> 32; | |
| 600 | + } | |
| 601 | + | |
| 602 | + // Add remainder of the longer number | |
| 603 | + while(x>0) { | |
| 604 | + x--; | |
| 605 | + if (carry == 0 && result == value && rstart == (x + offset)) | |
| 606 | + return; | |
| 607 | + sum = (value[x+offset] & LONG_MASK) + carry; | |
| 608 | + result[rstart--] = (int)sum; | |
| 609 | + carry = sum >>> 32; | |
| 610 | + } | |
| 611 | + while(y>0) { | |
| 612 | + y--; | |
| 613 | + sum = (addend.value[y+addend.offset] & LONG_MASK) + carry; | |
| 614 | + result[rstart--] = (int)sum; | |
| 615 | + carry = sum >>> 32; | |
| 616 | + } | |
| 617 | + | |
| 618 | + if (carry > 0) { // Result must grow in length | |
| 619 | + resultLen++; | |
| 620 | + if (result.length < resultLen) { | |
| 621 | + int temp[] = new int[resultLen]; | |
| 622 | + // Result one word longer from carry-out; copy low-order | |
| 623 | + // bits into new result. | |
| 624 | + System.arraycopy(result, 0, temp, 1, result.length); | |
| 625 | + temp[0] = 1; | |
| 626 | + result = temp; | |
| 627 | + } else { | |
| 628 | + result[rstart--] = 1; | |
| 629 | + } | |
| 630 | + } | |
| 631 | + | |
| 632 | + value = result; | |
| 633 | + intLen = resultLen; | |
| 634 | + offset = result.length - resultLen; | |
| 635 | + } | |
| 636 | + | |
| 637 | + | |
| 638 | + /** | |
| 639 | + * Subtracts the smaller of this and b from the larger and places the | |
| 640 | + * result into this MutableBigInteger. | |
| 641 | + */ | |
| 642 | + int subtract(MutableBigInteger b) { | |
| 643 | + MutableBigInteger a = this; | |
| 644 | + | |
| 645 | + int[] result = value; | |
| 646 | + int sign = a.compare(b); | |
| 647 | + | |
| 648 | + if (sign == 0) { | |
| 649 | + reset(); | |
| 650 | + return 0; | |
| 651 | + } | |
| 652 | + if (sign < 0) { | |
| 653 | + MutableBigInteger tmp = a; | |
| 654 | + a = b; | |
| 655 | + b = tmp; | |
| 656 | + } | |
| 657 | + | |
| 658 | + int resultLen = a.intLen; | |
| 659 | + if (result.length < resultLen) | |
| 660 | + result = new int[resultLen]; | |
| 661 | + | |
| 662 | + long diff = 0; | |
| 663 | + int x = a.intLen; | |
| 664 | + int y = b.intLen; | |
| 665 | + int rstart = result.length - 1; | |
| 666 | + | |
| 667 | + // Subtract common parts of both numbers | |
| 668 | + while (y>0) { | |
| 669 | + x--; y--; | |
| 670 | + | |
| 671 | + diff = (a.value[x+a.offset] & LONG_MASK) - | |
| 672 | + (b.value[y+b.offset] & LONG_MASK) - ((int)-(diff>>32)); | |
| 673 | + result[rstart--] = (int)diff; | |
| 674 | + } | |
| 675 | + // Subtract remainder of longer number | |
| 676 | + while (x>0) { | |
| 677 | + x--; | |
| 678 | + diff = (a.value[x+a.offset] & LONG_MASK) - ((int)-(diff>>32)); | |
| 679 | + result[rstart--] = (int)diff; | |
| 680 | + } | |
| 681 | + | |
| 682 | + value = result; | |
| 683 | + intLen = resultLen; | |
| 684 | + offset = value.length - resultLen; | |
| 685 | + normalize(); | |
| 686 | + return sign; | |
| 687 | + } | |
| 688 | + | |
| 689 | + /** | |
| 690 | + * Subtracts the smaller of a and b from the larger and places the result | |
| 691 | + * into the larger. Returns 1 if the answer is in a, -1 if in b, 0 if no | |
| 692 | + * operation was performed. | |
| 693 | + */ | |
| 694 | + private int difference(MutableBigInteger b) { | |
| 695 | + MutableBigInteger a = this; | |
| 696 | + int sign = a.compare(b); | |
| 697 | + if (sign ==0) | |
| 698 | + return 0; | |
| 699 | + if (sign < 0) { | |
| 700 | + MutableBigInteger tmp = a; | |
| 701 | + a = b; | |
| 702 | + b = tmp; | |
| 703 | + } | |
| 704 | + | |
| 705 | + long diff = 0; | |
| 706 | + int x = a.intLen; | |
| 707 | + int y = b.intLen; | |
| 708 | + | |
| 709 | + // Subtract common parts of both numbers | |
| 710 | + while (y>0) { | |
| 711 | + x--; y--; | |
| 712 | + diff = (a.value[a.offset+ x] & LONG_MASK) - | |
| 713 | + (b.value[b.offset+ y] & LONG_MASK) - ((int)-(diff>>32)); | |
| 714 | + a.value[a.offset+x] = (int)diff; | |
| 715 | + } | |
| 716 | + // Subtract remainder of longer number | |
| 717 | + while (x>0) { | |
| 718 | + x--; | |
| 719 | + diff = (a.value[a.offset+ x] & LONG_MASK) - ((int)-(diff>>32)); | |
| 720 | + a.value[a.offset+x] = (int)diff; | |
| 721 | + } | |
| 722 | + | |
| 723 | + a.normalize(); | |
| 724 | + return sign; | |
| 725 | + } | |
| 726 | + | |
| 727 | + /** | |
| 728 | + * Multiply the contents of two MutableBigInteger objects. The result is | |
| 729 | + * placed into MutableBigInteger z. The contents of y are not changed. | |
| 730 | + */ | |
| 731 | + void multiply(MutableBigInteger y, MutableBigInteger z) { | |
| 732 | + int xLen = intLen; | |
| 733 | + int yLen = y.intLen; | |
| 734 | + int newLen = xLen + yLen; | |
| 735 | + | |
| 736 | + // Put z into an appropriate state to receive product | |
| 737 | + if (z.value.length < newLen) | |
| 738 | + z.value = new int[newLen]; | |
| 739 | + z.offset = 0; | |
| 740 | + z.intLen = newLen; | |
| 741 | + | |
| 742 | + // The first iteration is hoisted out of the loop to avoid extra add | |
| 743 | + long carry = 0; | |
| 744 | + for (int j=yLen-1, k=yLen+xLen-1; j >= 0; j--, k--) { | |
| 745 | + long product = (y.value[j+y.offset] & LONG_MASK) * | |
| 746 | + (value[xLen-1+offset] & LONG_MASK) + carry; | |
| 747 | + z.value[k] = (int)product; | |
| 748 | + carry = product >>> 32; | |
| 749 | + } | |
| 750 | + z.value[xLen-1] = (int)carry; | |
| 751 | + | |
| 752 | + // Perform the multiplication word by word | |
| 753 | + for (int i = xLen-2; i >= 0; i--) { | |
| 754 | + carry = 0; | |
| 755 | + for (int j=yLen-1, k=yLen+i; j >= 0; j--, k--) { | |
| 756 | + long product = (y.value[j+y.offset] & LONG_MASK) * | |
| 757 | + (value[i+offset] & LONG_MASK) + | |
| 758 | + (z.value[k] & LONG_MASK) + carry; | |
| 759 | + z.value[k] = (int)product; | |
| 760 | + carry = product >>> 32; | |
| 761 | + } | |
| 762 | + z.value[i] = (int)carry; | |
| 763 | + } | |
| 764 | + | |
| 765 | + // Remove leading zeros from product | |
| 766 | + z.normalize(); | |
| 767 | + } | |
| 768 | + | |
| 769 | + /** | |
| 770 | + * Multiply the contents of this MutableBigInteger by the word y. The | |
| 771 | + * result is placed into z. | |
| 772 | + */ | |
| 773 | + void mul(int y, MutableBigInteger z) { | |
| 774 | + if (y == 1) { | |
| 775 | + z.copyValue(this); | |
| 776 | + return; | |
| 777 | + } | |
| 778 | + | |
| 779 | + if (y == 0) { | |
| 780 | + z.clear(); | |
| 781 | + return; | |
| 782 | + } | |
| 783 | + | |
| 784 | + // Perform the multiplication word by word | |
| 785 | + long ylong = y & LONG_MASK; | |
| 786 | + int[] zval = (z.value.length<intLen+1 ? new int[intLen + 1] | |
| 787 | + : z.value); | |
| 788 | + long carry = 0; | |
| 789 | + for (int i = intLen-1; i >= 0; i--) { | |
| 790 | + long product = ylong * (value[i+offset] & LONG_MASK) + carry; | |
| 791 | + zval[i+1] = (int)product; | |
| 792 | + carry = product >>> 32; | |
| 793 | + } | |
| 794 | + | |
| 795 | + if (carry == 0) { | |
| 796 | + z.offset = 1; | |
| 797 | + z.intLen = intLen; | |
| 798 | + } else { | |
| 799 | + z.offset = 0; | |
| 800 | + z.intLen = intLen + 1; | |
| 801 | + zval[0] = (int)carry; | |
| 802 | + } | |
| 803 | + z.value = zval; | |
| 804 | + } | |
| 805 | + | |
| 806 | + /** | |
| 807 | + * This method is used for division of an n word dividend by a one word | |
| 808 | + * divisor. The quotient is placed into quotient. The one word divisor is | |
| 809 | + * specified by divisor. | |
| 810 | + * | |
| 811 | + * @return the remainder of the division is returned. | |
| 812 | + * | |
| 813 | + */ | |
| 814 | + int divideOneWord(int divisor, MutableBigInteger quotient) { | |
| 815 | + long divisorLong = divisor & LONG_MASK; | |
| 816 | + | |
| 817 | + // Special case of one word dividend | |
| 818 | + if (intLen == 1) { | |
| 819 | + long dividendValue = value[offset] & LONG_MASK; | |
| 820 | + int q = (int) (dividendValue / divisorLong); | |
| 821 | + int r = (int) (dividendValue - q * divisorLong); | |
| 822 | + quotient.value[0] = q; | |
| 823 | + quotient.intLen = (q == 0) ? 0 : 1; | |
| 824 | + quotient.offset = 0; | |
| 825 | + return r; | |
| 826 | + } | |
| 827 | + | |
| 828 | + if (quotient.value.length < intLen) | |
| 829 | + quotient.value = new int[intLen]; | |
| 830 | + quotient.offset = 0; | |
| 831 | + quotient.intLen = intLen; | |
| 832 | + | |
| 833 | + // Normalize the divisor | |
| 834 | + int shift = Integer.numberOfLeadingZeros(divisor); | |
| 835 | + | |
| 836 | + int rem = value[offset]; | |
| 837 | + long remLong = rem & LONG_MASK; | |
| 838 | + if (remLong < divisorLong) { | |
| 839 | + quotient.value[0] = 0; | |
| 840 | + } else { | |
| 841 | + quotient.value[0] = (int)(remLong / divisorLong); | |
| 842 | + rem = (int) (remLong - (quotient.value[0] * divisorLong)); | |
| 843 | + remLong = rem & LONG_MASK; | |
| 844 | + } | |
| 845 | + | |
| 846 | + int xlen = intLen; | |
| 847 | + int[] qWord = new int[2]; | |
| 848 | + while (--xlen > 0) { | |
| 849 | + long dividendEstimate = (remLong<<32) | | |
| 850 | + (value[offset + intLen - xlen] & LONG_MASK); | |
| 851 | + if (dividendEstimate >= 0) { | |
| 852 | + qWord[0] = (int) (dividendEstimate / divisorLong); | |
| 853 | + qWord[1] = (int) (dividendEstimate - qWord[0] * divisorLong); | |
| 854 | + } else { | |
| 855 | + divWord(qWord, dividendEstimate, divisor); | |
| 856 | + } | |
| 857 | + quotient.value[intLen - xlen] = qWord[0]; | |
| 858 | + rem = qWord[1]; | |
| 859 | + remLong = rem & LONG_MASK; | |
| 860 | + } | |
| 861 | + | |
| 862 | + quotient.normalize(); | |
| 863 | + // Unnormalize | |
| 864 | + if (shift > 0) | |
| 865 | + return rem % divisor; | |
| 866 | + else | |
| 867 | + return rem; | |
| 868 | + } | |
| 869 | + | |
| 870 | + /** | |
| 871 | + * Calculates the quotient of this div b and places the quotient in the | |
| 872 | + * provided MutableBigInteger objects and the remainder object is returned. | |
| 873 | + * | |
| 874 | + * Uses Algorithm D in Knuth section 4.3.1. | |
| 875 | + * Many optimizations to that algorithm have been adapted from the Colin | |
| 876 | + * Plumb C library. | |
| 877 | + * It special cases one word divisors for speed. The content of b is not | |
| 878 | + * changed. | |
| 879 | + * | |
| 880 | + */ | |
| 881 | + MutableBigInteger divide(MutableBigInteger b, MutableBigInteger quotient) { | |
| 882 | + if (b.intLen == 0) | |
| 883 | + throw new ArithmeticException("BigInteger divide by zero"); | |
| 884 | + | |
| 885 | + // Dividend is zero | |
| 886 | + if (intLen == 0) { | |
| 887 | + quotient.intLen = quotient.offset; | |
| 888 | + return new MutableBigInteger(); | |
| 889 | + } | |
| 890 | + | |
| 891 | + int cmp = compare(b); | |
| 892 | + // Dividend less than divisor | |
| 893 | + if (cmp < 0) { | |
| 894 | + quotient.intLen = quotient.offset = 0; | |
| 895 | + return new MutableBigInteger(this); | |
| 896 | + } | |
| 897 | + // Dividend equal to divisor | |
| 898 | + if (cmp == 0) { | |
| 899 | + quotient.value[0] = quotient.intLen = 1; | |
| 900 | + quotient.offset = 0; | |
| 901 | + return new MutableBigInteger(); | |
| 902 | + } | |
| 903 | + | |
| 904 | + quotient.clear(); | |
| 905 | + // Special case one word divisor | |
| 906 | + if (b.intLen == 1) { | |
| 907 | + int r = divideOneWord(b.value[b.offset], quotient); | |
| 908 | + if (r == 0) | |
| 909 | + return new MutableBigInteger(); | |
| 910 | + return new MutableBigInteger(r); | |
| 911 | + } | |
| 912 | + | |
| 913 | + // Copy divisor value to protect divisor | |
| 914 | + int[] div = Arrays.copyOfRange(b.value, b.offset, b.offset + b.intLen); | |
| 915 | + return divideMagnitude(div, quotient); | |
| 916 | + } | |
| 917 | + | |
| 918 | + /** | |
| 919 | + * Internally used to calculate the quotient of this div v and places the | |
| 920 | + * quotient in the provided MutableBigInteger object and the remainder is | |
| 921 | + * returned. | |
| 922 | + * | |
| 923 | + * @return the remainder of the division will be returned. | |
| 924 | + */ | |
| 925 | + long divide(long v, MutableBigInteger quotient) { | |
| 926 | + if (v == 0) | |
| 927 | + throw new ArithmeticException("BigInteger divide by zero"); | |
| 928 | + | |
| 929 | + // Dividend is zero | |
| 930 | + if (intLen == 0) { | |
| 931 | + quotient.intLen = quotient.offset = 0; | |
| 932 | + return 0; | |
| 933 | + } | |
| 934 | + if (v < 0) | |
| 935 | + v = -v; | |
| 936 | + | |
| 937 | + int d = (int)(v >>> 32); | |
| 938 | + quotient.clear(); | |
| 939 | + // Special case on word divisor | |
| 940 | + if (d == 0) | |
| 941 | + return divideOneWord((int)v, quotient) & LONG_MASK; | |
| 942 | + else { | |
| 943 | + int[] div = new int[]{ d, (int)(v & LONG_MASK) }; | |
| 944 | + return divideMagnitude(div, quotient).toLong(); | |
| 945 | + } | |
| 946 | + } | |
| 947 | + | |
| 948 | + /** | |
| 949 | + * Divide this MutableBigInteger by the divisor represented by its magnitude | |
| 950 | + * array. The quotient will be placed into the provided quotient object & | |
| 951 | + * the remainder object is returned. | |
| 952 | + */ | |
| 953 | + private MutableBigInteger divideMagnitude(int[] divisor, | |
| 954 | + MutableBigInteger quotient) { | |
| 955 | + | |
| 956 | + // Remainder starts as dividend with space for a leading zero | |
| 957 | + MutableBigInteger rem = new MutableBigInteger(new int[intLen + 1]); | |
| 958 | + System.arraycopy(value, offset, rem.value, 1, intLen); | |
| 959 | + rem.intLen = intLen; | |
| 960 | + rem.offset = 1; | |
| 961 | + | |
| 962 | + int nlen = rem.intLen; | |
| 963 | + | |
| 964 | + // Set the quotient size | |
| 965 | + int dlen = divisor.length; | |
| 966 | + int limit = nlen - dlen + 1; | |
| 967 | + if (quotient.value.length < limit) { | |
| 968 | + quotient.value = new int[limit]; | |
| 969 | + quotient.offset = 0; | |
| 970 | + } | |
| 971 | + quotient.intLen = limit; | |
| 972 | + int[] q = quotient.value; | |
| 973 | + | |
| 974 | + // D1 normalize the divisor | |
| 975 | + int shift = Integer.numberOfLeadingZeros(divisor[0]); | |
| 976 | + if (shift > 0) { | |
| 977 | + // First shift will not grow array | |
| 978 | + BigInteger.primitiveLeftShift(divisor, dlen, shift); | |
| 979 | + // But this one might | |
| 980 | + rem.leftShift(shift); | |
| 981 | + } | |
| 982 | + | |
| 983 | + // Must insert leading 0 in rem if its length did not change | |
| 984 | + if (rem.intLen == nlen) { | |
| 985 | + rem.offset = 0; | |
| 986 | + rem.value[0] = 0; | |
| 987 | + rem.intLen++; | |
| 988 | + } | |
| 989 | + | |
| 990 | + int dh = divisor[0]; | |
| 991 | + long dhLong = dh & LONG_MASK; | |
| 992 | + int dl = divisor[1]; | |
| 993 | + int[] qWord = new int[2]; | |
| 994 | + | |
| 995 | + // D2 Initialize j | |
| 996 | + for(int j=0; j<limit; j++) { | |
| 997 | + // D3 Calculate qhat | |
| 998 | + // estimate qhat | |
| 999 | + int qhat = 0; | |
| 1000 | + int qrem = 0; | |
| 1001 | + boolean skipCorrection = false; | |
| 1002 | + int nh = rem.value[j+rem.offset]; | |
| 1003 | + int nh2 = nh + 0x80000000; | |
| 1004 | + int nm = rem.value[j+1+rem.offset]; | |
| 1005 | + | |
| 1006 | + if (nh == dh) { | |
| 1007 | + qhat = ~0; | |
| 1008 | + qrem = nh + nm; | |
| 1009 | + skipCorrection = qrem + 0x80000000 < nh2; | |
| 1010 | + } else { | |
| 1011 | + long nChunk = (((long)nh) << 32) | (nm & LONG_MASK); | |
| 1012 | + if (nChunk >= 0) { | |
| 1013 | + qhat = (int) (nChunk / dhLong); | |
| 1014 | + qrem = (int) (nChunk - (qhat * dhLong)); | |
| 1015 | + } else { | |
| 1016 | + divWord(qWord, nChunk, dh); | |
| 1017 | + qhat = qWord[0]; | |
| 1018 | + qrem = qWord[1]; | |
| 1019 | + } | |
| 1020 | + } | |
| 1021 | + | |
| 1022 | + if (qhat == 0) | |
| 1023 | + continue; | |
| 1024 | + | |
| 1025 | + if (!skipCorrection) { // Correct qhat | |
| 1026 | + long nl = rem.value[j+2+rem.offset] & LONG_MASK; | |
| 1027 | + long rs = ((qrem & LONG_MASK) << 32) | nl; | |
| 1028 | + long estProduct = (dl & LONG_MASK) * (qhat & LONG_MASK); | |
| 1029 | + | |
| 1030 | + if (unsignedLongCompare(estProduct, rs)) { | |
| 1031 | + qhat--; | |
| 1032 | + qrem = (int)((qrem & LONG_MASK) + dhLong); | |
| 1033 | + if ((qrem & LONG_MASK) >= dhLong) { | |
| 1034 | + estProduct -= (dl & LONG_MASK); | |
| 1035 | + rs = ((qrem & LONG_MASK) << 32) | nl; | |
| 1036 | + if (unsignedLongCompare(estProduct, rs)) | |
| 1037 | + qhat--; | |
| 1038 | + } | |
| 1039 | + } | |
| 1040 | + } | |
| 1041 | + | |
| 1042 | + // D4 Multiply and subtract | |
| 1043 | + rem.value[j+rem.offset] = 0; | |
| 1044 | + int borrow = mulsub(rem.value, divisor, qhat, dlen, j+rem.offset); | |
| 1045 | + | |
| 1046 | + // D5 Test remainder | |
| 1047 | + if (borrow + 0x80000000 > nh2) { | |
| 1048 | + // D6 Add back | |
| 1049 | + divadd(divisor, rem.value, j+1+rem.offset); | |
| 1050 | + qhat--; | |
| 1051 | + } | |
| 1052 | + | |
| 1053 | + // Store the quotient digit | |
| 1054 | + q[j] = qhat; | |
| 1055 | + } // D7 loop on j | |
| 1056 | + | |
| 1057 | + // D8 Unnormalize | |
| 1058 | + if (shift > 0) | |
| 1059 | + rem.rightShift(shift); | |
| 1060 | + | |
| 1061 | + quotient.normalize(); | |
| 1062 | + rem.normalize(); | |
| 1063 | + return rem; | |
| 1064 | + } | |
| 1065 | + | |
| 1066 | + /** | |
| 1067 | + * Compare two longs as if they were unsigned. | |
| 1068 | + * Returns true iff one is bigger than two. | |
| 1069 | + */ | |
| 1070 | + private boolean unsignedLongCompare(long one, long two) { | |
| 1071 | + return (one+Long.MIN_VALUE) > (two+Long.MIN_VALUE); | |
| 1072 | + } | |
| 1073 | + | |
| 1074 | + /** | |
| 1075 | + * This method divides a long quantity by an int to estimate | |
| 1076 | + * qhat for two multi precision numbers. It is used when | |
| 1077 | + * the signed value of n is less than zero. | |
| 1078 | + */ | |
| 1079 | + private void divWord(int[] result, long n, int d) { | |
| 1080 | + long dLong = d & LONG_MASK; | |
| 1081 | + | |
| 1082 | + if (dLong == 1) { | |
| 1083 | + result[0] = (int)n; | |
| 1084 | + result[1] = 0; | |
| 1085 | + return; | |
| 1086 | + } | |
| 1087 | + | |
| 1088 | + // Approximate the quotient and remainder | |
| 1089 | + long q = (n >>> 1) / (dLong >>> 1); | |
| 1090 | + long r = n - q*dLong; | |
| 1091 | + | |
| 1092 | + // Correct the approximation | |
| 1093 | + while (r < 0) { | |
| 1094 | + r += dLong; | |
| 1095 | + q--; | |
| 1096 | + } | |
| 1097 | + while (r >= dLong) { | |
| 1098 | + r -= dLong; | |
| 1099 | + q++; | |
| 1100 | + } | |
| 1101 | + | |
| 1102 | + // n - q*dlong == r && 0 <= r <dLong, hence we're done. | |
| 1103 | + result[0] = (int)q; | |
| 1104 | + result[1] = (int)r; | |
| 1105 | + } | |
| 1106 | + | |
| 1107 | + /** | |
| 1108 | + * Calculate GCD of this and b. This and b are changed by the computation. | |
| 1109 | + */ | |
| 1110 | + MutableBigInteger hybridGCD(MutableBigInteger b) { | |
| 1111 | + // Use Euclid's algorithm until the numbers are approximately the | |
| 1112 | + // same length, then use the binary GCD algorithm to find the GCD. | |
| 1113 | + MutableBigInteger a = this; | |
| 1114 | + MutableBigInteger q = new MutableBigInteger(); | |
| 1115 | + | |
| 1116 | + while (b.intLen != 0) { | |
| 1117 | + if (Math.abs(a.intLen - b.intLen) < 2) | |
| 1118 | + return a.binaryGCD(b); | |
| 1119 | + | |
| 1120 | + MutableBigInteger r = a.divide(b, q); | |
| 1121 | + a = b; | |
| 1122 | + b = r; | |
| 1123 | + } | |
| 1124 | + return a; | |
| 1125 | + } | |
| 1126 | + | |
| 1127 | + /** | |
| 1128 | + * Calculate GCD of this and v. | |
| 1129 | + * Assumes that this and v are not zero. | |
| 1130 | + */ | |
| 1131 | + private MutableBigInteger binaryGCD(MutableBigInteger v) { | |
| 1132 | + // Algorithm B from Knuth section 4.5.2 | |
| 1133 | + MutableBigInteger u = this; | |
| 1134 | + MutableBigInteger r = new MutableBigInteger(); | |
| 1135 | + | |
| 1136 | + // step B1 | |
| 1137 | + int s1 = u.getLowestSetBit(); | |
| 1138 | + int s2 = v.getLowestSetBit(); | |
| 1139 | + int k = (s1 < s2) ? s1 : s2; | |
| 1140 | + if (k != 0) { | |
| 1141 | + u.rightShift(k); | |
| 1142 | + v.rightShift(k); | |
| 1143 | + } | |
| 1144 | + | |
| 1145 | + // step B2 | |
| 1146 | + boolean uOdd = (k==s1); | |
| 1147 | + MutableBigInteger t = uOdd ? v: u; | |
| 1148 | + int tsign = uOdd ? -1 : 1; | |
| 1149 | + | |
| 1150 | + int lb; | |
| 1151 | + while ((lb = t.getLowestSetBit()) >= 0) { | |
| 1152 | + // steps B3 and B4 | |
| 1153 | + t.rightShift(lb); | |
| 1154 | + // step B5 | |
| 1155 | + if (tsign > 0) | |
| 1156 | + u = t; | |
| 1157 | + else | |
| 1158 | + v = t; | |
| 1159 | + | |
| 1160 | + // Special case one word numbers | |
| 1161 | + if (u.intLen < 2 && v.intLen < 2) { | |
| 1162 | + int x = u.value[u.offset]; | |
| 1163 | + int y = v.value[v.offset]; | |
| 1164 | + x = binaryGcd(x, y); | |
| 1165 | + r.value[0] = x; | |
| 1166 | + r.intLen = 1; | |
| 1167 | + r.offset = 0; | |
| 1168 | + if (k > 0) | |
| 1169 | + r.leftShift(k); | |
| 1170 | + return r; | |
| 1171 | + } | |
| 1172 | + | |
| 1173 | + // step B6 | |
| 1174 | + if ((tsign = u.difference(v)) == 0) | |
| 1175 | + break; | |
| 1176 | + t = (tsign >= 0) ? u : v; | |
| 1177 | + } | |
| 1178 | + | |
| 1179 | + if (k > 0) | |
| 1180 | + u.leftShift(k); | |
| 1181 | + return u; | |
| 1182 | + } | |
| 1183 | + | |
| 1184 | + /** | |
| 1185 | + * Calculate GCD of a and b interpreted as unsigned integers. | |
| 1186 | + */ | |
| 1187 | + static int binaryGcd(int a, int b) { | |
| 1188 | + if (b==0) | |
| 1189 | + return a; | |
| 1190 | + if (a==0) | |
| 1191 | + return b; | |
| 1192 | + | |
| 1193 | + // Right shift a & b till their last bits equal to 1. | |
| 1194 | + int aZeros = Integer.numberOfTrailingZeros(a); | |
| 1195 | + int bZeros = Integer.numberOfTrailingZeros(b); | |
| 1196 | + a >>>= aZeros; | |
| 1197 | + b >>>= bZeros; | |
| 1198 | + | |
| 1199 | + int t = (aZeros < bZeros ? aZeros : bZeros); | |
| 1200 | + | |
| 1201 | + while (a != b) { | |
| 1202 | + if ((a+0x80000000) > (b+0x80000000)) { // a > b as unsigned | |
| 1203 | + a -= b; | |
| 1204 | + a >>>= Integer.numberOfTrailingZeros(a); | |
| 1205 | + } else { | |
| 1206 | + b -= a; | |
| 1207 | + b >>>= Integer.numberOfTrailingZeros(b); | |
| 1208 | + } | |
| 1209 | + } | |
| 1210 | + return a<<t; | |
| 1211 | + } | |
| 1212 | + | |
| 1213 | + /** | |
| 1214 | + * Returns the modInverse of this mod p. This and p are not affected by | |
| 1215 | + * the operation. | |
| 1216 | + */ | |
| 1217 | + MutableBigInteger mutableModInverse(MutableBigInteger p) { | |
| 1218 | + // Modulus is odd, use Schroeppel's algorithm | |
| 1219 | + if (p.isOdd()) | |
| 1220 | + return modInverse(p); | |
| 1221 | + | |
| 1222 | + // Base and modulus are even, throw exception | |
| 1223 | + if (isEven()) | |
| 1224 | + throw new ArithmeticException("BigInteger not invertible."); | |
| 1225 | + | |
| 1226 | + // Get even part of modulus expressed as a power of 2 | |
| 1227 | + int powersOf2 = p.getLowestSetBit(); | |
| 1228 | + | |
| 1229 | + // Construct odd part of modulus | |
| 1230 | + MutableBigInteger oddMod = new MutableBigInteger(p); | |
| 1231 | + oddMod.rightShift(powersOf2); | |
| 1232 | + | |
| 1233 | + if (oddMod.isOne()) | |
| 1234 | + return modInverseMP2(powersOf2); | |
| 1235 | + | |
| 1236 | + // Calculate 1/a mod oddMod | |
| 1237 | + MutableBigInteger oddPart = modInverse(oddMod); | |
| 1238 | + | |
| 1239 | + // Calculate 1/a mod evenMod | |
| 1240 | + MutableBigInteger evenPart = modInverseMP2(powersOf2); | |
| 1241 | + | |
| 1242 | + // Combine the results using Chinese Remainder Theorem | |
| 1243 | + MutableBigInteger y1 = modInverseBP2(oddMod, powersOf2); | |
| 1244 | + MutableBigInteger y2 = oddMod.modInverseMP2(powersOf2); | |
| 1245 | + | |
| 1246 | + MutableBigInteger temp1 = new MutableBigInteger(); | |
| 1247 | + MutableBigInteger temp2 = new MutableBigInteger(); | |
| 1248 | + MutableBigInteger result = new MutableBigInteger(); | |
| 1249 | + | |
| 1250 | + oddPart.leftShift(powersOf2); | |
| 1251 | + oddPart.multiply(y1, result); | |
| 1252 | + | |
| 1253 | + evenPart.multiply(oddMod, temp1); | |
| 1254 | + temp1.multiply(y2, temp2); | |
| 1255 | + | |
| 1256 | + result.add(temp2); | |
| 1257 | + return result.divide(p, temp1); | |
| 1258 | + } | |
| 1259 | + | |
| 1260 | + /* | |
| 1261 | + * Calculate the multiplicative inverse of this mod 2^k. | |
| 1262 | + */ | |
| 1263 | + MutableBigInteger modInverseMP2(int k) { | |
| 1264 | + if (isEven()) | |
| 1265 | + throw new ArithmeticException("Non-invertible. (GCD != 1)"); | |
| 1266 | + | |
| 1267 | + if (k > 64) | |
| 1268 | + return euclidModInverse(k); | |
| 1269 | + | |
| 1270 | + int t = inverseMod32(value[offset+intLen-1]); | |
| 1271 | + | |
| 1272 | + if (k < 33) { | |
| 1273 | + t = (k == 32 ? t : t & ((1 << k) - 1)); | |
| 1274 | + return new MutableBigInteger(t); | |
| 1275 | + } | |
| 1276 | + | |
| 1277 | + long pLong = (value[offset+intLen-1] & LONG_MASK); | |
| 1278 | + if (intLen > 1) | |
| 1279 | + pLong |= ((long)value[offset+intLen-2] << 32); | |
| 1280 | + long tLong = t & LONG_MASK; | |
| 1281 | + tLong = tLong * (2 - pLong * tLong); // 1 more Newton iter step | |
| 1282 | + tLong = (k == 64 ? tLong : tLong & ((1L << k) - 1)); | |
| 1283 | + | |
| 1284 | + MutableBigInteger result = new MutableBigInteger(new int[2]); | |
| 1285 | + result.value[0] = (int)(tLong >>> 32); | |
| 1286 | + result.value[1] = (int)tLong; | |
| 1287 | + result.intLen = 2; | |
| 1288 | + result.normalize(); | |
| 1289 | + return result; | |
| 1290 | + } | |
| 1291 | + | |
| 1292 | + /* | |
| 1293 | + * Returns the multiplicative inverse of val mod 2^32. Assumes val is odd. | |
| 1294 | + */ | |
| 1295 | + static int inverseMod32(int val) { | |
| 1296 | + // Newton's iteration! | |
| 1297 | + int t = val; | |
| 1298 | + t *= 2 - val*t; | |
| 1299 | + t *= 2 - val*t; | |
| 1300 | + t *= 2 - val*t; | |
| 1301 | + t *= 2 - val*t; | |
| 1302 | + return t; | |
| 1303 | + } | |
| 1304 | + | |
| 1305 | + /* | |
| 1306 | + * Calculate the multiplicative inverse of 2^k mod mod, where mod is odd. | |
| 1307 | + */ | |
| 1308 | + static MutableBigInteger modInverseBP2(MutableBigInteger mod, int k) { | |
| 1309 | + // Copy the mod to protect original | |
| 1310 | + return fixup(new MutableBigInteger(1), new MutableBigInteger(mod), k); | |
| 1311 | + } | |
| 1312 | + | |
| 1313 | + /** | |
| 1314 | + * Calculate the multiplicative inverse of this mod mod, where mod is odd. | |
| 1315 | + * This and mod are not changed by the calculation. | |
| 1316 | + * | |
| 1317 | + * This method implements an algorithm due to Richard Schroeppel, that uses | |
| 1318 | + * the same intermediate representation as Montgomery Reduction | |
| 1319 | + * ("Montgomery Form"). The algorithm is described in an unpublished | |
| 1320 | + * manuscript entitled "Fast Modular Reciprocals." | |
| 1321 | + */ | |
| 1322 | + private MutableBigInteger modInverse(MutableBigInteger mod) { | |
| 1323 | + MutableBigInteger p = new MutableBigInteger(mod); | |
| 1324 | + MutableBigInteger f = new MutableBigInteger(this); | |
| 1325 | + MutableBigInteger g = new MutableBigInteger(p); | |
| 1326 | + SignedMutableBigInteger c = new SignedMutableBigInteger(1); | |
| 1327 | + SignedMutableBigInteger d = new SignedMutableBigInteger(); | |
| 1328 | + MutableBigInteger temp = null; | |
| 1329 | + SignedMutableBigInteger sTemp = null; | |
| 1330 | + | |
| 1331 | + int k = 0; | |
| 1332 | + // Right shift f k times until odd, left shift d k times | |
| 1333 | + if (f.isEven()) { | |
| 1334 | + int trailingZeros = f.getLowestSetBit(); | |
| 1335 | + f.rightShift(trailingZeros); | |
| 1336 | + d.leftShift(trailingZeros); | |
| 1337 | + k = trailingZeros; | |
| 1338 | + } | |
| 1339 | + | |
| 1340 | + // The Almost Inverse Algorithm | |
| 1341 | + while(!f.isOne()) { | |
| 1342 | + // If gcd(f, g) != 1, number is not invertible modulo mod | |
| 1343 | + if (f.isZero()) | |
| 1344 | + throw new ArithmeticException("BigInteger not invertible."); | |
| 1345 | + | |
| 1346 | + // If f < g exchange f, g and c, d | |
| 1347 | + if (f.compare(g) < 0) { | |
| 1348 | + temp = f; f = g; g = temp; | |
| 1349 | + sTemp = d; d = c; c = sTemp; | |
| 1350 | + } | |
| 1351 | + | |
| 1352 | + // If f == g (mod 4) | |
| 1353 | + if (((f.value[f.offset + f.intLen - 1] ^ | |
| 1354 | + g.value[g.offset + g.intLen - 1]) & 3) == 0) { | |
| 1355 | + f.subtract(g); | |
| 1356 | + c.signedSubtract(d); | |
| 1357 | + } else { // If f != g (mod 4) | |
| 1358 | + f.add(g); | |
| 1359 | + c.signedAdd(d); | |
| 1360 | + } | |
| 1361 | + | |
| 1362 | + // Right shift f k times until odd, left shift d k times | |
| 1363 | + int trailingZeros = f.getLowestSetBit(); | |
| 1364 | + f.rightShift(trailingZeros); | |
| 1365 | + d.leftShift(trailingZeros); | |
| 1366 | + k += trailingZeros; | |
| 1367 | + } | |
| 1368 | + | |
| 1369 | + while (c.sign < 0) | |
| 1370 | + c.signedAdd(p); | |
| 1371 | + | |
| 1372 | + return fixup(c, p, k); | |
| 1373 | + } | |
| 1374 | + | |
| 1375 | + /* | |
| 1376 | + * The Fixup Algorithm | |
| 1377 | + * Calculates X such that X = C * 2^(-k) (mod P) | |
| 1378 | + * Assumes C<P and P is odd. | |
| 1379 | + */ | |
| 1380 | + static MutableBigInteger fixup(MutableBigInteger c, MutableBigInteger p, | |
| 1381 | + int k) { | |
| 1382 | + MutableBigInteger temp = new MutableBigInteger(); | |
| 1383 | + // Set r to the multiplicative inverse of p mod 2^32 | |
| 1384 | + int r = -inverseMod32(p.value[p.offset+p.intLen-1]); | |
| 1385 | + | |
| 1386 | + for(int i=0, numWords = k >> 5; i<numWords; i++) { | |
| 1387 | + // V = R * c (mod 2^j) | |
| 1388 | + int v = r * c.value[c.offset + c.intLen-1]; | |
| 1389 | + // c = c + (v * p) | |
| 1390 | + p.mul(v, temp); | |
| 1391 | + c.add(temp); | |
| 1392 | + // c = c / 2^j | |
| 1393 | + c.intLen--; | |
| 1394 | + } | |
| 1395 | + int numBits = k & 0x1f; | |
| 1396 | + if (numBits != 0) { | |
| 1397 | + // V = R * c (mod 2^j) | |
| 1398 | + int v = r * c.value[c.offset + c.intLen-1]; | |
| 1399 | + v &= ((1<<numBits) - 1); | |
| 1400 | + // c = c + (v * p) | |
| 1401 | + p.mul(v, temp); | |
| 1402 | + c.add(temp); | |
| 1403 | + // c = c / 2^j | |
| 1404 | + c.rightShift(numBits); | |
| 1405 | + } | |
| 1406 | + | |
| 1407 | + // In theory, c may be greater than p at this point (Very rare!) | |
| 1408 | + while (c.compare(p) >= 0) | |
| 1409 | + c.subtract(p); | |
| 1410 | + | |
| 1411 | + return c; | |
| 1412 | + } | |
| 1413 | + | |
| 1414 | + /** | |
| 1415 | + * Uses the extended Euclidean algorithm to compute the modInverse of base | |
| 1416 | + * mod a modulus that is a power of 2. The modulus is 2^k. | |
| 1417 | + */ | |
| 1418 | + MutableBigInteger euclidModInverse(int k) { | |
| 1419 | + MutableBigInteger b = new MutableBigInteger(1); | |
| 1420 | + b.leftShift(k); | |
| 1421 | + MutableBigInteger mod = new MutableBigInteger(b); | |
| 1422 | + | |
| 1423 | + MutableBigInteger a = new MutableBigInteger(this); | |
| 1424 | + MutableBigInteger q = new MutableBigInteger(); | |
| 1425 | + MutableBigInteger r = b.divide(a, q); | |
| 1426 | + | |
| 1427 | + MutableBigInteger swapper = b; | |
| 1428 | + // swap b & r | |
| 1429 | + b = r; | |
| 1430 | + r = swapper; | |
| 1431 | + | |
| 1432 | + MutableBigInteger t1 = new MutableBigInteger(q); | |
| 1433 | + MutableBigInteger t0 = new MutableBigInteger(1); | |
| 1434 | + MutableBigInteger temp = new MutableBigInteger(); | |
| 1435 | + | |
| 1436 | + while (!b.isOne()) { | |
| 1437 | + r = a.divide(b, q); | |
| 1438 | + | |
| 1439 | + if (r.intLen == 0) | |
| 1440 | + throw new ArithmeticException("BigInteger not invertible."); | |
| 1441 | + | |
| 1442 | + swapper = r; | |
| 1443 | + a = swapper; | |
| 1444 | + | |
| 1445 | + if (q.intLen == 1) | |
| 1446 | + t1.mul(q.value[q.offset], temp); | |
| 1447 | + else | |
| 1448 | + q.multiply(t1, temp); | |
| 1449 | + swapper = q; | |
| 1450 | + q = temp; | |
| 1451 | + temp = swapper; | |
| 1452 | + t0.add(q); | |
| 1453 | + | |
| 1454 | + if (a.isOne()) | |
| 1455 | + return t0; | |
| 1456 | + | |
| 1457 | + r = b.divide(a, q); | |
| 1458 | + | |
| 1459 | + if (r.intLen == 0) | |
| 1460 | + throw new ArithmeticException("BigInteger not invertible."); | |
| 1461 | + | |
| 1462 | + swapper = b; | |
| 1463 | + b = r; | |
| 1464 | + | |
| 1465 | + if (q.intLen == 1) | |
| 1466 | + t0.mul(q.value[q.offset], temp); | |
| 1467 | + else | |
| 1468 | + q.multiply(t0, temp); | |
| 1469 | + swapper = q; q = temp; temp = swapper; | |
| 1470 | + | |
| 1471 | + t1.add(q); | |
| 1472 | + } | |
| 1473 | + mod.subtract(t1); | |
| 1474 | + return mod; | |
| 1475 | + } | |
| 1476 | + | |
| 1477 | +} | |
Binary file not shown.
| @@ -0,0 +1,349 @@ | ||
| 1 | +/* | |
| 2 | + * Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved. | |
| 3 | + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. | |
| 4 | + * | |
| 5 | + * This code is free software; you can redistribute it and/or modify it | |
| 6 | + * under the terms of the GNU General Public License version 2 only, as | |
| 7 | + * published by the Free Software Foundation. Oracle designates this | |
| 8 | + * particular file as subject to the "Classpath" exception as provided | |
| 9 | + * by Oracle in the LICENSE file that accompanied this code. | |
| 10 | + * | |
| 11 | + * This code is distributed in the hope that it will be useful, but WITHOUT | |
| 12 | + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or | |
| 13 | + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License | |
| 14 | + * version 2 for more details (a copy is included in the LICENSE file that | |
| 15 | + * accompanied this code). | |
| 16 | + * | |
| 17 | + * You should have received a copy of the GNU General Public License version | |
| 18 | + * 2 along with this work; if not, write to the Free Software Foundation, | |
| 19 | + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. | |
| 20 | + * | |
| 21 | + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA | |
| 22 | + * or visit www.oracle.com if you need additional information or have any | |
| 23 | + * questions. | |
| 24 | + */ | |
| 25 | + | |
| 26 | +/* | |
| 27 | + * Portions Copyright IBM Corporation, 2001. All Rights Reserved. | |
| 28 | + */ | |
| 29 | +package java.math; | |
| 30 | + | |
| 31 | +/** | |
| 32 | + * Specifies a <i>rounding behavior</i> for numerical operations | |
| 33 | + * capable of discarding precision. Each rounding mode indicates how | |
| 34 | + * the least significant returned digit of a rounded result is to be | |
| 35 | + * calculated. If fewer digits are returned than the digits needed to | |
| 36 | + * represent the exact numerical result, the discarded digits will be | |
| 37 | + * referred to as the <i>discarded fraction</i> regardless the digits' | |
| 38 | + * contribution to the value of the number. In other words, | |
| 39 | + * considered as a numerical value, the discarded fraction could have | |
| 40 | + * an absolute value greater than one. | |
| 41 | + * | |
| 42 | + * <p>Each rounding mode description includes a table listing how | |
| 43 | + * different two-digit decimal values would round to a one digit | |
| 44 | + * decimal value under the rounding mode in question. The result | |
| 45 | + * column in the tables could be gotten by creating a | |
| 46 | + * {@code BigDecimal} number with the specified value, forming a | |
| 47 | + * {@link MathContext} object with the proper settings | |
| 48 | + * ({@code precision} set to {@code 1}, and the | |
| 49 | + * {@code roundingMode} set to the rounding mode in question), and | |
| 50 | + * calling {@link BigDecimal#round round} on this number with the | |
| 51 | + * proper {@code MathContext}. A summary table showing the results | |
| 52 | + * of these rounding operations for all rounding modes appears below. | |
| 53 | + * | |
| 54 | + *<p> | |
| 55 | + *<table border> | |
| 56 | + * <caption><b>Summary of Rounding Operations Under Different Rounding Modes</b></caption> | |
| 57 | + * <tr><th></th><th colspan=8>Result of rounding input to one digit with the given | |
| 58 | + * rounding mode</th> | |
| 59 | + * <tr valign=top> | |
| 60 | + * <th>Input Number</th> <th>{@code UP}</th> | |
| 61 | + * <th>{@code DOWN}</th> | |
| 62 | + * <th>{@code CEILING}</th> | |
| 63 | + * <th>{@code FLOOR}</th> | |
| 64 | + * <th>{@code HALF_UP}</th> | |
| 65 | + * <th>{@code HALF_DOWN}</th> | |
| 66 | + * <th>{@code HALF_EVEN}</th> | |
| 67 | + * <th>{@code UNNECESSARY}</th> | |
| 68 | + * | |
| 69 | + * <tr align=right><td>5.5</td> <td>6</td> <td>5</td> <td>6</td> <td>5</td> <td>6</td> <td>5</td> <td>6</td> <td>throw {@code ArithmeticException}</td> | |
| 70 | + * <tr align=right><td>2.5</td> <td>3</td> <td>2</td> <td>3</td> <td>2</td> <td>3</td> <td>2</td> <td>2</td> <td>throw {@code ArithmeticException}</td> | |
| 71 | + * <tr align=right><td>1.6</td> <td>2</td> <td>1</td> <td>2</td> <td>1</td> <td>2</td> <td>2</td> <td>2</td> <td>throw {@code ArithmeticException}</td> | |
| 72 | + * <tr align=right><td>1.1</td> <td>2</td> <td>1</td> <td>2</td> <td>1</td> <td>1</td> <td>1</td> <td>1</td> <td>throw {@code ArithmeticException}</td> | |
| 73 | + * <tr align=right><td>1.0</td> <td>1</td> <td>1</td> <td>1</td> <td>1</td> <td>1</td> <td>1</td> <td>1</td> <td>1</td> | |
| 74 | + * <tr align=right><td>-1.0</td> <td>-1</td> <td>-1</td> <td>-1</td> <td>-1</td> <td>-1</td> <td>-1</td> <td>-1</td> <td>-1</td> | |
| 75 | + * <tr align=right><td>-1.1</td> <td>-2</td> <td>-1</td> <td>-1</td> <td>-2</td> <td>-1</td> <td>-1</td> <td>-1</td> <td>throw {@code ArithmeticException}</td> | |
| 76 | + * <tr align=right><td>-1.6</td> <td>-2</td> <td>-1</td> <td>-1</td> <td>-2</td> <td>-2</td> <td>-2</td> <td>-2</td> <td>throw {@code ArithmeticException}</td> | |
| 77 | + * <tr align=right><td>-2.5</td> <td>-3</td> <td>-2</td> <td>-2</td> <td>-3</td> <td>-3</td> <td>-2</td> <td>-2</td> <td>throw {@code ArithmeticException}</td> | |
| 78 | + * <tr align=right><td>-5.5</td> <td>-6</td> <td>-5</td> <td>-5</td> <td>-6</td> <td>-6</td> <td>-5</td> <td>-6</td> <td>throw {@code ArithmeticException}</td> | |
| 79 | + *</table> | |
| 80 | + * | |
| 81 | + * | |
| 82 | + * <p>This {@code enum} is intended to replace the integer-based | |
| 83 | + * enumeration of rounding mode constants in {@link BigDecimal} | |
| 84 | + * ({@link BigDecimal#ROUND_UP}, {@link BigDecimal#ROUND_DOWN}, | |
| 85 | + * etc. ). | |
| 86 | + * | |
| 87 | + * @see BigDecimal | |
| 88 | + * @see MathContext | |
| 89 | + * @author Josh Bloch | |
| 90 | + * @author Mike Cowlishaw | |
| 91 | + * @author Joseph D. Darcy | |
| 92 | + * @since 1.5 | |
| 93 | + */ | |
| 94 | +public enum RoundingMode { | |
| 95 | + | |
| 96 | + /** | |
| 97 | + * Rounding mode to round away from zero. Always increments the | |
| 98 | + * digit prior to a non-zero discarded fraction. Note that this | |
| 99 | + * rounding mode never decreases the magnitude of the calculated | |
| 100 | + * value. | |
| 101 | + * | |
| 102 | + *<p>Example: | |
| 103 | + *<table border> | |
| 104 | + *<tr valign=top><th>Input Number</th> | |
| 105 | + * <th>Input rounded to one digit<br> with {@code UP} rounding | |
| 106 | + *<tr align=right><td>5.5</td> <td>6</td> | |
| 107 | + *<tr align=right><td>2.5</td> <td>3</td> | |
| 108 | + *<tr align=right><td>1.6</td> <td>2</td> | |
| 109 | + *<tr align=right><td>1.1</td> <td>2</td> | |
| 110 | + *<tr align=right><td>1.0</td> <td>1</td> | |
| 111 | + *<tr align=right><td>-1.0</td> <td>-1</td> | |
| 112 | + *<tr align=right><td>-1.1</td> <td>-2</td> | |
| 113 | + *<tr align=right><td>-1.6</td> <td>-2</td> | |
| 114 | + *<tr align=right><td>-2.5</td> <td>-3</td> | |
| 115 | + *<tr align=right><td>-5.5</td> <td>-6</td> | |
| 116 | + *</table> | |
| 117 | + */ | |
| 118 | + UP(BigDecimal.ROUND_UP), | |
| 119 | + | |
| 120 | + /** | |
| 121 | + * Rounding mode to round towards zero. Never increments the digit | |
| 122 | + * prior to a discarded fraction (i.e., truncates). Note that this | |
| 123 | + * rounding mode never increases the magnitude of the calculated value. | |
| 124 | + * | |
| 125 | + *<p>Example: | |
| 126 | + *<table border> | |
| 127 | + *<tr valign=top><th>Input Number</th> | |
| 128 | + * <th>Input rounded to one digit<br> with {@code DOWN} rounding | |
| 129 | + *<tr align=right><td>5.5</td> <td>5</td> | |
| 130 | + *<tr align=right><td>2.5</td> <td>2</td> | |
| 131 | + *<tr align=right><td>1.6</td> <td>1</td> | |
| 132 | + *<tr align=right><td>1.1</td> <td>1</td> | |
| 133 | + *<tr align=right><td>1.0</td> <td>1</td> | |
| 134 | + *<tr align=right><td>-1.0</td> <td>-1</td> | |
| 135 | + *<tr align=right><td>-1.1</td> <td>-1</td> | |
| 136 | + *<tr align=right><td>-1.6</td> <td>-1</td> | |
| 137 | + *<tr align=right><td>-2.5</td> <td>-2</td> | |
| 138 | + *<tr align=right><td>-5.5</td> <td>-5</td> | |
| 139 | + *</table> | |
| 140 | + */ | |
| 141 | + DOWN(BigDecimal.ROUND_DOWN), | |
| 142 | + | |
| 143 | + /** | |
| 144 | + * Rounding mode to round towards positive infinity. If the | |
| 145 | + * result is positive, behaves as for {@code RoundingMode.UP}; | |
| 146 | + * if negative, behaves as for {@code RoundingMode.DOWN}. Note | |
| 147 | + * that this rounding mode never decreases the calculated value. | |
| 148 | + * | |
| 149 | + *<p>Example: | |
| 150 | + *<table border> | |
| 151 | + *<tr valign=top><th>Input Number</th> | |
| 152 | + * <th>Input rounded to one digit<br> with {@code CEILING} rounding | |
| 153 | + *<tr align=right><td>5.5</td> <td>6</td> | |
| 154 | + *<tr align=right><td>2.5</td> <td>3</td> | |
| 155 | + *<tr align=right><td>1.6</td> <td>2</td> | |
| 156 | + *<tr align=right><td>1.1</td> <td>2</td> | |
| 157 | + *<tr align=right><td>1.0</td> <td>1</td> | |
| 158 | + *<tr align=right><td>-1.0</td> <td>-1</td> | |
| 159 | + *<tr align=right><td>-1.1</td> <td>-1</td> | |
| 160 | + *<tr align=right><td>-1.6</td> <td>-1</td> | |
| 161 | + *<tr align=right><td>-2.5</td> <td>-2</td> | |
| 162 | + *<tr align=right><td>-5.5</td> <td>-5</td> | |
| 163 | + *</table> | |
| 164 | + */ | |
| 165 | + CEILING(BigDecimal.ROUND_CEILING), | |
| 166 | + | |
| 167 | + /** | |
| 168 | + * Rounding mode to round towards negative infinity. If the | |
| 169 | + * result is positive, behave as for {@code RoundingMode.DOWN}; | |
| 170 | + * if negative, behave as for {@code RoundingMode.UP}. Note that | |
| 171 | + * this rounding mode never increases the calculated value. | |
| 172 | + * | |
| 173 | + *<p>Example: | |
| 174 | + *<table border> | |
| 175 | + *<tr valign=top><th>Input Number</th> | |
| 176 | + * <th>Input rounded to one digit<br> with {@code FLOOR} rounding | |
| 177 | + *<tr align=right><td>5.5</td> <td>5</td> | |
| 178 | + *<tr align=right><td>2.5</td> <td>2</td> | |
| 179 | + *<tr align=right><td>1.6</td> <td>1</td> | |
| 180 | + *<tr align=right><td>1.1</td> <td>1</td> | |
| 181 | + *<tr align=right><td>1.0</td> <td>1</td> | |
| 182 | + *<tr align=right><td>-1.0</td> <td>-1</td> | |
| 183 | + *<tr align=right><td>-1.1</td> <td>-2</td> | |
| 184 | + *<tr align=right><td>-1.6</td> <td>-2</td> | |
| 185 | + *<tr align=right><td>-2.5</td> <td>-3</td> | |
| 186 | + *<tr align=right><td>-5.5</td> <td>-6</td> | |
| 187 | + *</table> | |
| 188 | + */ | |
| 189 | + FLOOR(BigDecimal.ROUND_FLOOR), | |
| 190 | + | |
| 191 | + /** | |
| 192 | + * Rounding mode to round towards {@literal "nearest neighbor"} | |
| 193 | + * unless both neighbors are equidistant, in which case round up. | |
| 194 | + * Behaves as for {@code RoundingMode.UP} if the discarded | |
| 195 | + * fraction is ≥ 0.5; otherwise, behaves as for | |
| 196 | + * {@code RoundingMode.DOWN}. Note that this is the rounding | |
| 197 | + * mode commonly taught at school. | |
| 198 | + * | |
| 199 | + *<p>Example: | |
| 200 | + *<table border> | |
| 201 | + *<tr valign=top><th>Input Number</th> | |
| 202 | + * <th>Input rounded to one digit<br> with {@code HALF_UP} rounding | |
| 203 | + *<tr align=right><td>5.5</td> <td>6</td> | |
| 204 | + *<tr align=right><td>2.5</td> <td>3</td> | |
| 205 | + *<tr align=right><td>1.6</td> <td>2</td> | |
| 206 | + *<tr align=right><td>1.1</td> <td>1</td> | |
| 207 | + *<tr align=right><td>1.0</td> <td>1</td> | |
| 208 | + *<tr align=right><td>-1.0</td> <td>-1</td> | |
| 209 | + *<tr align=right><td>-1.1</td> <td>-1</td> | |
| 210 | + *<tr align=right><td>-1.6</td> <td>-2</td> | |
| 211 | + *<tr align=right><td>-2.5</td> <td>-3</td> | |
| 212 | + *<tr align=right><td>-5.5</td> <td>-6</td> | |
| 213 | + *</table> | |
| 214 | + */ | |
| 215 | + HALF_UP(BigDecimal.ROUND_HALF_UP), | |
| 216 | + | |
| 217 | + /** | |
| 218 | + * Rounding mode to round towards {@literal "nearest neighbor"} | |
| 219 | + * unless both neighbors are equidistant, in which case round | |
| 220 | + * down. Behaves as for {@code RoundingMode.UP} if the discarded | |
| 221 | + * fraction is > 0.5; otherwise, behaves as for | |
| 222 | + * {@code RoundingMode.DOWN}. | |
| 223 | + * | |
| 224 | + *<p>Example: | |
| 225 | + *<table border> | |
| 226 | + *<tr valign=top><th>Input Number</th> | |
| 227 | + * <th>Input rounded to one digit<br> with {@code HALF_DOWN} rounding | |
| 228 | + *<tr align=right><td>5.5</td> <td>5</td> | |
| 229 | + *<tr align=right><td>2.5</td> <td>2</td> | |
| 230 | + *<tr align=right><td>1.6</td> <td>2</td> | |
| 231 | + *<tr align=right><td>1.1</td> <td>1</td> | |
| 232 | + *<tr align=right><td>1.0</td> <td>1</td> | |
| 233 | + *<tr align=right><td>-1.0</td> <td>-1</td> | |
| 234 | + *<tr align=right><td>-1.1</td> <td>-1</td> | |
| 235 | + *<tr align=right><td>-1.6</td> <td>-2</td> | |
| 236 | + *<tr align=right><td>-2.5</td> <td>-2</td> | |
| 237 | + *<tr align=right><td>-5.5</td> <td>-5</td> | |
| 238 | + *</table> | |
| 239 | + */ | |
| 240 | + HALF_DOWN(BigDecimal.ROUND_HALF_DOWN), | |
| 241 | + | |
| 242 | + /** | |
| 243 | + * Rounding mode to round towards the {@literal "nearest neighbor"} | |
| 244 | + * unless both neighbors are equidistant, in which case, round | |
| 245 | + * towards the even neighbor. Behaves as for | |
| 246 | + * {@code RoundingMode.HALF_UP} if the digit to the left of the | |
| 247 | + * discarded fraction is odd; behaves as for | |
| 248 | + * {@code RoundingMode.HALF_DOWN} if it's even. Note that this | |
| 249 | + * is the rounding mode that statistically minimizes cumulative | |
| 250 | + * error when applied repeatedly over a sequence of calculations. | |
| 251 | + * It is sometimes known as {@literal "Banker's rounding,"} and is | |
| 252 | + * chiefly used in the USA. This rounding mode is analogous to | |
| 253 | + * the rounding policy used for {@code float} and {@code double} | |
| 254 | + * arithmetic in Java. | |
| 255 | + * | |
| 256 | + *<p>Example: | |
| 257 | + *<table border> | |
| 258 | + *<tr valign=top><th>Input Number</th> | |
| 259 | + * <th>Input rounded to one digit<br> with {@code HALF_EVEN} rounding | |
| 260 | + *<tr align=right><td>5.5</td> <td>6</td> | |
| 261 | + *<tr align=right><td>2.5</td> <td>2</td> | |
| 262 | + *<tr align=right><td>1.6</td> <td>2</td> | |
| 263 | + *<tr align=right><td>1.1</td> <td>1</td> | |
| 264 | + *<tr align=right><td>1.0</td> <td>1</td> | |
| 265 | + *<tr align=right><td>-1.0</td> <td>-1</td> | |
| 266 | + *<tr align=right><td>-1.1</td> <td>-1</td> | |
| 267 | + *<tr align=right><td>-1.6</td> <td>-2</td> | |
| 268 | + *<tr align=right><td>-2.5</td> <td>-2</td> | |
| 269 | + *<tr align=right><td>-5.5</td> <td>-6</td> | |
| 270 | + *</table> | |
| 271 | + */ | |
| 272 | + HALF_EVEN(BigDecimal.ROUND_HALF_EVEN), | |
| 273 | + | |
| 274 | + /** | |
| 275 | + * Rounding mode to assert that the requested operation has an exact | |
| 276 | + * result, hence no rounding is necessary. If this rounding mode is | |
| 277 | + * specified on an operation that yields an inexact result, an | |
| 278 | + * {@code ArithmeticException} is thrown. | |
| 279 | + *<p>Example: | |
| 280 | + *<table border> | |
| 281 | + *<tr valign=top><th>Input Number</th> | |
| 282 | + * <th>Input rounded to one digit<br> with {@code UNNECESSARY} rounding | |
| 283 | + *<tr align=right><td>5.5</td> <td>throw {@code ArithmeticException}</td> | |
| 284 | + *<tr align=right><td>2.5</td> <td>throw {@code ArithmeticException}</td> | |
| 285 | + *<tr align=right><td>1.6</td> <td>throw {@code ArithmeticException}</td> | |
| 286 | + *<tr align=right><td>1.1</td> <td>throw {@code ArithmeticException}</td> | |
| 287 | + *<tr align=right><td>1.0</td> <td>1</td> | |
| 288 | + *<tr align=right><td>-1.0</td> <td>-1</td> | |
| 289 | + *<tr align=right><td>-1.1</td> <td>throw {@code ArithmeticException}</td> | |
| 290 | + *<tr align=right><td>-1.6</td> <td>throw {@code ArithmeticException}</td> | |
| 291 | + *<tr align=right><td>-2.5</td> <td>throw {@code ArithmeticException}</td> | |
| 292 | + *<tr align=right><td>-5.5</td> <td>throw {@code ArithmeticException}</td> | |
| 293 | + *</table> | |
| 294 | + */ | |
| 295 | + UNNECESSARY(BigDecimal.ROUND_UNNECESSARY); | |
| 296 | + | |
| 297 | + // Corresponding BigDecimal rounding constant | |
| 298 | + final int oldMode; | |
| 299 | + | |
| 300 | + /** | |
| 301 | + * Constructor | |
| 302 | + * | |
| 303 | + * @param oldMode The {@code BigDecimal} constant corresponding to | |
| 304 | + * this mode | |
| 305 | + */ | |
| 306 | + private RoundingMode(int oldMode) { | |
| 307 | + this.oldMode = oldMode; | |
| 308 | + } | |
| 309 | + | |
| 310 | + /** | |
| 311 | + * Returns the {@code RoundingMode} object corresponding to a | |
| 312 | + * legacy integer rounding mode constant in {@link BigDecimal}. | |
| 313 | + * | |
| 314 | + * @param rm legacy integer rounding mode to convert | |
| 315 | + * @return {@code RoundingMode} corresponding to the given integer. | |
| 316 | + * @throws IllegalArgumentException integer is out of range | |
| 317 | + */ | |
| 318 | + public static RoundingMode valueOf(int rm) { | |
| 319 | + switch(rm) { | |
| 320 | + | |
| 321 | + case BigDecimal.ROUND_UP: | |
| 322 | + return UP; | |
| 323 | + | |
| 324 | + case BigDecimal.ROUND_DOWN: | |
| 325 | + return DOWN; | |
| 326 | + | |
| 327 | + case BigDecimal.ROUND_CEILING: | |
| 328 | + return CEILING; | |
| 329 | + | |
| 330 | + case BigDecimal.ROUND_FLOOR: | |
| 331 | + return FLOOR; | |
| 332 | + | |
| 333 | + case BigDecimal.ROUND_HALF_UP: | |
| 334 | + return HALF_UP; | |
| 335 | + | |
| 336 | + case BigDecimal.ROUND_HALF_DOWN: | |
| 337 | + return HALF_DOWN; | |
| 338 | + | |
| 339 | + case BigDecimal.ROUND_HALF_EVEN: | |
| 340 | + return HALF_EVEN; | |
| 341 | + | |
| 342 | + case BigDecimal.ROUND_UNNECESSARY: | |
| 343 | + return UNNECESSARY; | |
| 344 | + | |
| 345 | + default: | |
| 346 | + throw new IllegalArgumentException("argument out of range"); | |
| 347 | + } | |
| 348 | + } | |
| 349 | +} | |
Binary file not shown.
| @@ -0,0 +1,135 @@ | ||
| 1 | +/* | |
| 2 | + * Copyright (c) 1999, 2007, Oracle and/or its affiliates. All rights reserved. | |
| 3 | + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. | |
| 4 | + * | |
| 5 | + * This code is free software; you can redistribute it and/or modify it | |
| 6 | + * under the terms of the GNU General Public License version 2 only, as | |
| 7 | + * published by the Free Software Foundation. Oracle designates this | |
| 8 | + * particular file as subject to the "Classpath" exception as provided | |
| 9 | + * by Oracle in the LICENSE file that accompanied this code. | |
| 10 | + * | |
| 11 | + * This code is distributed in the hope that it will be useful, but WITHOUT | |
| 12 | + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or | |
| 13 | + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License | |
| 14 | + * version 2 for more details (a copy is included in the LICENSE file that | |
| 15 | + * accompanied this code). | |
| 16 | + * | |
| 17 | + * You should have received a copy of the GNU General Public License version | |
| 18 | + * 2 along with this work; if not, write to the Free Software Foundation, | |
| 19 | + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. | |
| 20 | + * | |
| 21 | + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA | |
| 22 | + * or visit www.oracle.com if you need additional information or have any | |
| 23 | + * questions. | |
| 24 | + */ | |
| 25 | + | |
| 26 | +package java.math; | |
| 27 | + | |
| 28 | +/** | |
| 29 | + * A class used to represent multiprecision integers that makes efficient | |
| 30 | + * use of allocated space by allowing a number to occupy only part of | |
| 31 | + * an array so that the arrays do not have to be reallocated as often. | |
| 32 | + * When performing an operation with many iterations the array used to | |
| 33 | + * hold a number is only increased when necessary and does not have to | |
| 34 | + * be the same size as the number it represents. A mutable number allows | |
| 35 | + * calculations to occur on the same number without having to create | |
| 36 | + * a new number for every step of the calculation as occurs with | |
| 37 | + * BigIntegers. | |
| 38 | + * | |
| 39 | + * Note that SignedMutableBigIntegers only support signed addition and | |
| 40 | + * subtraction. All other operations occur as with MutableBigIntegers. | |
| 41 | + * | |
| 42 | + * @see BigInteger | |
| 43 | + * @author Michael McCloskey | |
| 44 | + * @since 1.3 | |
| 45 | + */ | |
| 46 | + | |
| 47 | +class SignedMutableBigInteger extends MutableBigInteger { | |
| 48 | + | |
| 49 | + /** | |
| 50 | + * The sign of this MutableBigInteger. | |
| 51 | + */ | |
| 52 | + int sign = 1; | |
| 53 | + | |
| 54 | + // Constructors | |
| 55 | + | |
| 56 | + /** | |
| 57 | + * The default constructor. An empty MutableBigInteger is created with | |
| 58 | + * a one word capacity. | |
| 59 | + */ | |
| 60 | + SignedMutableBigInteger() { | |
| 61 | + super(); | |
| 62 | + } | |
| 63 | + | |
| 64 | + /** | |
| 65 | + * Construct a new MutableBigInteger with a magnitude specified by | |
| 66 | + * the int val. | |
| 67 | + */ | |
| 68 | + SignedMutableBigInteger(int val) { | |
| 69 | + super(val); | |
| 70 | + } | |
| 71 | + | |
| 72 | + /** | |
| 73 | + * Construct a new MutableBigInteger with a magnitude equal to the | |
| 74 | + * specified MutableBigInteger. | |
| 75 | + */ | |
| 76 | + SignedMutableBigInteger(MutableBigInteger val) { | |
| 77 | + super(val); | |
| 78 | + } | |
| 79 | + | |
| 80 | + // Arithmetic Operations | |
| 81 | + | |
| 82 | + /** | |
| 83 | + * Signed addition built upon unsigned add and subtract. | |
| 84 | + */ | |
| 85 | + void signedAdd(SignedMutableBigInteger addend) { | |
| 86 | + if (sign == addend.sign) | |
| 87 | + add(addend); | |
| 88 | + else | |
| 89 | + sign = sign * subtract(addend); | |
| 90 | + | |
| 91 | + } | |
| 92 | + | |
| 93 | + /** | |
| 94 | + * Signed addition built upon unsigned add and subtract. | |
| 95 | + */ | |
| 96 | + void signedAdd(MutableBigInteger addend) { | |
| 97 | + if (sign == 1) | |
| 98 | + add(addend); | |
| 99 | + else | |
| 100 | + sign = sign * subtract(addend); | |
| 101 | + | |
| 102 | + } | |
| 103 | + | |
| 104 | + /** | |
| 105 | + * Signed subtraction built upon unsigned add and subtract. | |
| 106 | + */ | |
| 107 | + void signedSubtract(SignedMutableBigInteger addend) { | |
| 108 | + if (sign == addend.sign) | |
| 109 | + sign = sign * subtract(addend); | |
| 110 | + else | |
| 111 | + add(addend); | |
| 112 | + | |
| 113 | + } | |
| 114 | + | |
| 115 | + /** | |
| 116 | + * Signed subtraction built upon unsigned add and subtract. | |
| 117 | + */ | |
| 118 | + void signedSubtract(MutableBigInteger addend) { | |
| 119 | + if (sign == 1) | |
| 120 | + sign = sign * subtract(addend); | |
| 121 | + else | |
| 122 | + add(addend); | |
| 123 | + if (intLen == 0) | |
| 124 | + sign = 1; | |
| 125 | + } | |
| 126 | + | |
| 127 | + /** | |
| 128 | + * Print out the first intLen ints of this MutableBigInteger's value | |
| 129 | + * array starting at offset. | |
| 130 | + */ | |
| 131 | + public String toString() { | |
| 132 | + return this.toBigInteger(sign).toString(); | |
| 133 | + } | |
| 134 | + | |
| 135 | +} | |
| @@ -0,0 +1,15 @@ | ||
| 1 | +<../../../../mkconfig | |
| 2 | + | |
| 3 | +TARG=\ | |
| 4 | + BigDecimal.dis\ | |
| 5 | + BigInteger.dis\ | |
| 6 | + BitSieve.dis\ | |
| 7 | + MathContext.dis\ | |
| 8 | + MutableBigInteger.dis\ | |
| 9 | + package-info.dis\ | |
| 10 | + RoundingMode.dis\ | |
| 11 | + SignedMutableBigInteger.dis\ | |
| 12 | + | |
| 13 | +DISBIN=$ROOT/java/dis/java/java/java/math | |
| 14 | + | |
| 15 | +<$ROOT/mkfiles/mkjava | |
| @@ -0,0 +1,45 @@ | ||
| 1 | +/* | |
| 2 | + * Copyright (c) 1998, 2006, Oracle and/or its affiliates. All rights reserved. | |
| 3 | + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. | |
| 4 | + * | |
| 5 | + * This code is free software; you can redistribute it and/or modify it | |
| 6 | + * under the terms of the GNU General Public License version 2 only, as | |
| 7 | + * published by the Free Software Foundation. Oracle designates this | |
| 8 | + * particular file as subject to the "Classpath" exception as provided | |
| 9 | + * by Oracle in the LICENSE file that accompanied this code. | |
| 10 | + * | |
| 11 | + * This code is distributed in the hope that it will be useful, but WITHOUT | |
| 12 | + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or | |
| 13 | + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License | |
| 14 | + * version 2 for more details (a copy is included in the LICENSE file that | |
| 15 | + * accompanied this code). | |
| 16 | + * | |
| 17 | + * You should have received a copy of the GNU General Public License version | |
| 18 | + * 2 along with this work; if not, write to the Free Software Foundation, | |
| 19 | + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. | |
| 20 | + * | |
| 21 | + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA | |
| 22 | + * or visit www.oracle.com if you need additional information or have any | |
| 23 | + * questions. | |
| 24 | + */ | |
| 25 | + | |
| 26 | +/** | |
| 27 | + * Provides classes for performing arbitrary-precision integer | |
| 28 | + * arithmetic ({@code BigInteger}) and arbitrary-precision decimal | |
| 29 | + * arithmetic ({@code BigDecimal}). {@code BigInteger} is analogous | |
| 30 | + * to the primitive integer types except that it provides arbitrary | |
| 31 | + * precision, hence operations on {@code BigInteger}s do not overflow | |
| 32 | + * or lose precision. In addition to standard arithmetic operations, | |
| 33 | + * {@code BigInteger} provides modular arithmetic, GCD calculation, | |
| 34 | + * primality testing, prime generation, bit manipulation, and a few | |
| 35 | + * other miscellaneous operations. | |
| 36 | + * | |
| 37 | + * {@code BigDecimal} provides arbitrary-precision signed decimal | |
| 38 | + * numbers suitable for currency calculations and the like. {@code | |
| 39 | + * BigDecimal} gives the user complete control over rounding behavior, | |
| 40 | + * allowing the user to choose from a comprehensive set of eight | |
| 41 | + * rounding modes. | |
| 42 | + * | |
| 43 | + * @since JDK1.1 | |
| 44 | + */ | |
| 45 | +package java.math; | |