1 /*
   2  * Copyright (c) 1996, 2016, 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 static java.math.BigInteger.LONG_MASK;
  33 import java.util.Arrays;
  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 <code>(unscaledValue &times; 10<sup>-scale</sup>)</code>.
  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&times;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  * @author  Sergey V. Kuksenko
 219  */
 220 public class BigDecimal extends Number implements Comparable<BigDecimal> {
 221     /**
 222      * The unscaled value of this BigDecimal, as returned by {@link
 223      * #unscaledValue}.
 224      *
 225      * @serial
 226      * @see #unscaledValue
 227      */
 228     private final BigInteger intVal;
 229 
 230     /**
 231      * The scale of this BigDecimal, as returned by {@link #scale}.
 232      *
 233      * @serial
 234      * @see #scale
 235      */
 236     private final int scale;  // Note: this may have any value, so
 237                               // calculations must be done in longs
 238 
 239     /**
 240      * The number of decimal digits in this BigDecimal, or 0 if the
 241      * number of digits are not known (lookaside information).  If
 242      * nonzero, the value is guaranteed correct.  Use the precision()
 243      * method to obtain and set the value if it might be 0.  This
 244      * field is mutable until set nonzero.
 245      *
 246      * @since  1.5
 247      */
 248     private transient int precision;
 249 
 250     /**
 251      * Used to store the canonical string representation, if computed.
 252      */
 253     private transient String stringCache;
 254 
 255     /**
 256      * Sentinel value for {@link #intCompact} indicating the
 257      * significand information is only available from {@code intVal}.
 258      */
 259     static final long INFLATED = Long.MIN_VALUE;
 260 
 261     private static final BigInteger INFLATED_BIGINT = BigInteger.valueOf(INFLATED);
 262 
 263     /**
 264      * If the absolute value of the significand of this BigDecimal is
 265      * less than or equal to {@code Long.MAX_VALUE}, the value can be
 266      * compactly stored in this field and used in computations.
 267      */
 268     private final transient long intCompact;
 269 
 270     // All 18-digit base ten strings fit into a long; not all 19-digit
 271     // strings will
 272     private static final int MAX_COMPACT_DIGITS = 18;
 273 
 274     /* Appease the serialization gods */
 275     private static final long serialVersionUID = 6108874887143696463L;
 276 
 277     private static final ThreadLocal<StringBuilderHelper>
 278         threadLocalStringBuilderHelper = new ThreadLocal<StringBuilderHelper>() {
 279         @Override
 280         protected StringBuilderHelper initialValue() {
 281             return new StringBuilderHelper();
 282         }
 283     };
 284 
 285     // Cache of common small BigDecimal values.
 286     private static final BigDecimal ZERO_THROUGH_TEN[] = {
 287         new BigDecimal(BigInteger.ZERO,       0,  0, 1),
 288         new BigDecimal(BigInteger.ONE,        1,  0, 1),
 289         new BigDecimal(BigInteger.TWO,        2,  0, 1),
 290         new BigDecimal(BigInteger.valueOf(3), 3,  0, 1),
 291         new BigDecimal(BigInteger.valueOf(4), 4,  0, 1),
 292         new BigDecimal(BigInteger.valueOf(5), 5,  0, 1),
 293         new BigDecimal(BigInteger.valueOf(6), 6,  0, 1),
 294         new BigDecimal(BigInteger.valueOf(7), 7,  0, 1),
 295         new BigDecimal(BigInteger.valueOf(8), 8,  0, 1),
 296         new BigDecimal(BigInteger.valueOf(9), 9,  0, 1),
 297         new BigDecimal(BigInteger.TEN,        10, 0, 2),
 298     };
 299 
 300     // Cache of zero scaled by 0 - 15
 301     private static final BigDecimal[] ZERO_SCALED_BY = {
 302         ZERO_THROUGH_TEN[0],
 303         new BigDecimal(BigInteger.ZERO, 0, 1, 1),
 304         new BigDecimal(BigInteger.ZERO, 0, 2, 1),
 305         new BigDecimal(BigInteger.ZERO, 0, 3, 1),
 306         new BigDecimal(BigInteger.ZERO, 0, 4, 1),
 307         new BigDecimal(BigInteger.ZERO, 0, 5, 1),
 308         new BigDecimal(BigInteger.ZERO, 0, 6, 1),
 309         new BigDecimal(BigInteger.ZERO, 0, 7, 1),
 310         new BigDecimal(BigInteger.ZERO, 0, 8, 1),
 311         new BigDecimal(BigInteger.ZERO, 0, 9, 1),
 312         new BigDecimal(BigInteger.ZERO, 0, 10, 1),
 313         new BigDecimal(BigInteger.ZERO, 0, 11, 1),
 314         new BigDecimal(BigInteger.ZERO, 0, 12, 1),
 315         new BigDecimal(BigInteger.ZERO, 0, 13, 1),
 316         new BigDecimal(BigInteger.ZERO, 0, 14, 1),
 317         new BigDecimal(BigInteger.ZERO, 0, 15, 1),
 318     };
 319 
 320     // Half of Long.MIN_VALUE & Long.MAX_VALUE.
 321     private static final long HALF_LONG_MAX_VALUE = Long.MAX_VALUE / 2;
 322     private static final long HALF_LONG_MIN_VALUE = Long.MIN_VALUE / 2;
 323 
 324     // Constants
 325     /**
 326      * The value 0, with a scale of 0.
 327      *
 328      * @since  1.5
 329      */
 330     public static final BigDecimal ZERO =
 331         ZERO_THROUGH_TEN[0];
 332 
 333     /**
 334      * The value 1, with a scale of 0.
 335      *
 336      * @since  1.5
 337      */
 338     public static final BigDecimal ONE =
 339         ZERO_THROUGH_TEN[1];
 340 
 341     /**
 342      * The value 10, with a scale of 0.
 343      *
 344      * @since  1.5
 345      */
 346     public static final BigDecimal TEN =
 347         ZERO_THROUGH_TEN[10];
 348 
 349     // Constructors
 350 
 351     /**
 352      * Trusted package private constructor.
 353      * Trusted simply means if val is INFLATED, intVal could not be null and
 354      * if intVal is null, val could not be INFLATED.
 355      */
 356     BigDecimal(BigInteger intVal, long val, int scale, int prec) {
 357         this.scale = scale;
 358         this.precision = prec;
 359         this.intCompact = val;
 360         this.intVal = intVal;
 361     }
 362 
 363     /**
 364      * Translates a character array representation of a
 365      * {@code BigDecimal} into a {@code BigDecimal}, accepting the
 366      * same sequence of characters as the {@link #BigDecimal(String)}
 367      * constructor, while allowing a sub-array to be specified.
 368      *
 369      * <p>Note that if the sequence of characters is already available
 370      * within a character array, using this constructor is faster than
 371      * converting the {@code char} array to string and using the
 372      * {@code BigDecimal(String)} constructor .
 373      *
 374      * @param  in {@code char} array that is the source of characters.
 375      * @param  offset first character in the array to inspect.
 376      * @param  len number of characters to consider.
 377      * @throws NumberFormatException if {@code in} is not a valid
 378      *         representation of a {@code BigDecimal} or the defined subarray
 379      *         is not wholly within {@code in}.
 380      * @since  1.5
 381      */
 382     public BigDecimal(char[] in, int offset, int len) {
 383         this(in,offset,len,MathContext.UNLIMITED);
 384     }
 385 
 386     /**
 387      * Translates a character array representation of a
 388      * {@code BigDecimal} into a {@code BigDecimal}, accepting the
 389      * same sequence of characters as the {@link #BigDecimal(String)}
 390      * constructor, while allowing a sub-array to be specified and
 391      * with rounding according to the context settings.
 392      *
 393      * <p>Note that if the sequence of characters is already available
 394      * within a character array, using this constructor is faster than
 395      * converting the {@code char} array to string and using the
 396      * {@code BigDecimal(String)} constructor.
 397      *
 398      * @param  in {@code char} array that is the source of characters.
 399      * @param  offset first character in the array to inspect.
 400      * @param  len number of characters to consider..
 401      * @param  mc the context to use.
 402      * @throws ArithmeticException if the result is inexact but the
 403      *         rounding mode is {@code UNNECESSARY}.
 404      * @throws NumberFormatException if {@code in} is not a valid
 405      *         representation of a {@code BigDecimal} or the defined subarray
 406      *         is not wholly within {@code in}.
 407      * @since  1.5
 408      */
 409     public BigDecimal(char[] in, int offset, int len, MathContext mc) {
 410         // protect against huge length.
 411         if (offset + len > in.length || offset < 0)
 412             throw new NumberFormatException("Bad offset or len arguments for char[] input.");
 413         // This is the primary string to BigDecimal constructor; all
 414         // incoming strings end up here; it uses explicit (inline)
 415         // parsing for speed and generates at most one intermediate
 416         // (temporary) object (a char[] array) for non-compact case.
 417 
 418         // Use locals for all fields values until completion
 419         int prec = 0;                 // record precision value
 420         int scl = 0;                  // record scale value
 421         long rs = 0;                  // the compact value in long
 422         BigInteger rb = null;         // the inflated value in BigInteger
 423         // use array bounds checking to handle too-long, len == 0,
 424         // bad offset, etc.
 425         try {
 426             // handle the sign
 427             boolean isneg = false;          // assume positive
 428             if (in[offset] == '-') {
 429                 isneg = true;               // leading minus means negative
 430                 offset++;
 431                 len--;
 432             } else if (in[offset] == '+') { // leading + allowed
 433                 offset++;
 434                 len--;
 435             }
 436 
 437             // should now be at numeric part of the significand
 438             boolean dot = false;             // true when there is a '.'
 439             long exp = 0;                    // exponent
 440             char c;                          // current character
 441             boolean isCompact = (len <= MAX_COMPACT_DIGITS);
 442             // integer significand array & idx is the index to it. The array
 443             // is ONLY used when we can't use a compact representation.
 444             int idx = 0;
 445             if (isCompact) {
 446                 // First compact case, we need not to preserve the character
 447                 // and we can just compute the value in place.
 448                 for (; len > 0; offset++, len--) {
 449                     c = in[offset];
 450                     if ((c == '0')) { // have zero
 451                         if (prec == 0)
 452                             prec = 1;
 453                         else if (rs != 0) {
 454                             rs *= 10;
 455                             ++prec;
 456                         } // else digit is a redundant leading zero
 457                         if (dot)
 458                             ++scl;
 459                     } else if ((c >= '1' && c <= '9')) { // have digit
 460                         int digit = c - '0';
 461                         if (prec != 1 || rs != 0)
 462                             ++prec; // prec unchanged if preceded by 0s
 463                         rs = rs * 10 + digit;
 464                         if (dot)
 465                             ++scl;
 466                     } else if (c == '.') {   // have dot
 467                         // have dot
 468                         if (dot) // two dots
 469                             throw new NumberFormatException("Character array"
 470                                 + " contains more than one decimal point.");
 471                         dot = true;
 472                     } else if (Character.isDigit(c)) { // slow path
 473                         int digit = Character.digit(c, 10);
 474                         if (digit == 0) {
 475                             if (prec == 0)
 476                                 prec = 1;
 477                             else if (rs != 0) {
 478                                 rs *= 10;
 479                                 ++prec;
 480                             } // else digit is a redundant leading zero
 481                         } else {
 482                             if (prec != 1 || rs != 0)
 483                                 ++prec; // prec unchanged if preceded by 0s
 484                             rs = rs * 10 + digit;
 485                         }
 486                         if (dot)
 487                             ++scl;
 488                     } else if ((c == 'e') || (c == 'E')) {
 489                         exp = parseExp(in, offset, len);
 490                         // Next test is required for backwards compatibility
 491                         if ((int) exp != exp) // overflow
 492                             throw new NumberFormatException("Exponent overflow.");
 493                         break; // [saves a test]
 494                     } else {
 495                         throw new NumberFormatException("Character " + c
 496                             + " is neither a decimal digit number, decimal point, nor"
 497                             + " \"e\" notation exponential mark.");
 498                     }
 499                 }
 500                 if (prec == 0) // no digits found
 501                     throw new NumberFormatException("No digits found.");
 502                 // Adjust scale if exp is not zero.
 503                 if (exp != 0) { // had significant exponent
 504                     scl = adjustScale(scl, exp);
 505                 }
 506                 rs = isneg ? -rs : rs;
 507                 int mcp = mc.precision;
 508                 int drop = prec - mcp; // prec has range [1, MAX_INT], mcp has range [0, MAX_INT];
 509                                        // therefore, this subtract cannot overflow
 510                 if (mcp > 0 && drop > 0) {  // do rounding
 511                     while (drop > 0) {
 512                         scl = checkScaleNonZero((long) scl - drop);
 513                         rs = divideAndRound(rs, LONG_TEN_POWERS_TABLE[drop], mc.roundingMode.oldMode);
 514                         prec = longDigitLength(rs);
 515                         drop = prec - mcp;
 516                     }
 517                 }
 518             } else {
 519                 char coeff[] = new char[len];
 520                 for (; len > 0; offset++, len--) {
 521                     c = in[offset];
 522                     // have digit
 523                     if ((c >= '0' && c <= '9') || Character.isDigit(c)) {
 524                         // First compact case, we need not to preserve the character
 525                         // and we can just compute the value in place.
 526                         if (c == '0' || Character.digit(c, 10) == 0) {
 527                             if (prec == 0) {
 528                                 coeff[idx] = c;
 529                                 prec = 1;
 530                             } else if (idx != 0) {
 531                                 coeff[idx++] = c;
 532                                 ++prec;
 533                             } // else c must be a redundant leading zero
 534                         } else {
 535                             if (prec != 1 || idx != 0)
 536                                 ++prec; // prec unchanged if preceded by 0s
 537                             coeff[idx++] = c;
 538                         }
 539                         if (dot)
 540                             ++scl;
 541                         continue;
 542                     }
 543                     // have dot
 544                     if (c == '.') {
 545                         // have dot
 546                         if (dot) // two dots
 547                             throw new NumberFormatException("Character array"
 548                                 + " contains more than one decimal point.");
 549                         dot = true;
 550                         continue;
 551                     }
 552                     // exponent expected
 553                     if ((c != 'e') && (c != 'E'))
 554                         throw new NumberFormatException("Character array"
 555                             + " is missing \"e\" notation exponential mark.");
 556                     exp = parseExp(in, offset, len);
 557                     // Next test is required for backwards compatibility
 558                     if ((int) exp != exp) // overflow
 559                         throw new NumberFormatException("Exponent overflow.");
 560                     break; // [saves a test]
 561                 }
 562                 // here when no characters left
 563                 if (prec == 0) // no digits found
 564                     throw new NumberFormatException("No digits found.");
 565                 // Adjust scale if exp is not zero.
 566                 if (exp != 0) { // had significant exponent
 567                     scl = adjustScale(scl, exp);
 568                 }
 569                 // Remove leading zeros from precision (digits count)
 570                 rb = new BigInteger(coeff, isneg ? -1 : 1, prec);
 571                 rs = compactValFor(rb);
 572                 int mcp = mc.precision;
 573                 if (mcp > 0 && (prec > mcp)) {
 574                     if (rs == INFLATED) {
 575                         int drop = prec - mcp;
 576                         while (drop > 0) {
 577                             scl = checkScaleNonZero((long) scl - drop);
 578                             rb = divideAndRoundByTenPow(rb, drop, mc.roundingMode.oldMode);
 579                             rs = compactValFor(rb);
 580                             if (rs != INFLATED) {
 581                                 prec = longDigitLength(rs);
 582                                 break;
 583                             }
 584                             prec = bigDigitLength(rb);
 585                             drop = prec - mcp;
 586                         }
 587                     }
 588                     if (rs != INFLATED) {
 589                         int drop = prec - mcp;
 590                         while (drop > 0) {
 591                             scl = checkScaleNonZero((long) scl - drop);
 592                             rs = divideAndRound(rs, LONG_TEN_POWERS_TABLE[drop], mc.roundingMode.oldMode);
 593                             prec = longDigitLength(rs);
 594                             drop = prec - mcp;
 595                         }
 596                         rb = null;
 597                     }
 598                 }
 599             }
 600         } catch (ArrayIndexOutOfBoundsException | NegativeArraySizeException e) {
 601             NumberFormatException nfe = new NumberFormatException();
 602             nfe.initCause(e);
 603             throw nfe;
 604         }
 605         this.scale = scl;
 606         this.precision = prec;
 607         this.intCompact = rs;
 608         this.intVal = rb;
 609     }
 610 
 611     private int adjustScale(int scl, long exp) {
 612         long adjustedScale = scl - exp;
 613         if (adjustedScale > Integer.MAX_VALUE || adjustedScale < Integer.MIN_VALUE)
 614             throw new NumberFormatException("Scale out of range.");
 615         scl = (int) adjustedScale;
 616         return scl;
 617     }
 618 
 619     /*
 620      * parse exponent
 621      */
 622     private static long parseExp(char[] in, int offset, int len){
 623         long exp = 0;
 624         offset++;
 625         char c = in[offset];
 626         len--;
 627         boolean negexp = (c == '-');
 628         // optional sign
 629         if (negexp || c == '+') {
 630             offset++;
 631             c = in[offset];
 632             len--;
 633         }
 634         if (len <= 0) // no exponent digits
 635             throw new NumberFormatException("No exponent digits.");
 636         // skip leading zeros in the exponent
 637         while (len > 10 && (c=='0' || (Character.digit(c, 10) == 0))) {
 638             offset++;
 639             c = in[offset];
 640             len--;
 641         }
 642         if (len > 10) // too many nonzero exponent digits
 643             throw new NumberFormatException("Too many nonzero exponent digits.");
 644         // c now holds first digit of exponent
 645         for (;; len--) {
 646             int v;
 647             if (c >= '0' && c <= '9') {
 648                 v = c - '0';
 649             } else {
 650                 v = Character.digit(c, 10);
 651                 if (v < 0) // not a digit
 652                     throw new NumberFormatException("Not a digit.");
 653             }
 654             exp = exp * 10 + v;
 655             if (len == 1)
 656                 break; // that was final character
 657             offset++;
 658             c = in[offset];
 659         }
 660         if (negexp) // apply sign
 661             exp = -exp;
 662         return exp;
 663     }
 664 
 665     /**
 666      * Translates a character array representation of a
 667      * {@code BigDecimal} into a {@code BigDecimal}, accepting the
 668      * same sequence of characters as the {@link #BigDecimal(String)}
 669      * constructor.
 670      *
 671      * <p>Note that if the sequence of characters is already available
 672      * as a character array, using this constructor is faster than
 673      * converting the {@code char} array to string and using the
 674      * {@code BigDecimal(String)} constructor .
 675      *
 676      * @param in {@code char} array that is the source of characters.
 677      * @throws NumberFormatException if {@code in} is not a valid
 678      *         representation of a {@code BigDecimal}.
 679      * @since  1.5
 680      */
 681     public BigDecimal(char[] in) {
 682         this(in, 0, in.length);
 683     }
 684 
 685     /**
 686      * Translates a character array representation of a
 687      * {@code BigDecimal} into a {@code BigDecimal}, accepting the
 688      * same sequence of characters as the {@link #BigDecimal(String)}
 689      * constructor and with rounding according to the context
 690      * settings.
 691      *
 692      * <p>Note that if the sequence of characters is already available
 693      * as a character array, using this constructor is faster than
 694      * converting the {@code char} array to string and using the
 695      * {@code BigDecimal(String)} constructor .
 696      *
 697      * @param  in {@code char} array that is the source of characters.
 698      * @param  mc the context to use.
 699      * @throws ArithmeticException if the result is inexact but the
 700      *         rounding mode is {@code UNNECESSARY}.
 701      * @throws NumberFormatException if {@code in} is not a valid
 702      *         representation of a {@code BigDecimal}.
 703      * @since  1.5
 704      */
 705     public BigDecimal(char[] in, MathContext mc) {
 706         this(in, 0, in.length, mc);
 707     }
 708 
 709     /**
 710      * Translates the string representation of a {@code BigDecimal}
 711      * into a {@code BigDecimal}.  The string representation consists
 712      * of an optional sign, {@code '+'} (<code> '\u002B'</code>) or
 713      * {@code '-'} (<code>'\u002D'</code>), followed by a sequence of
 714      * zero or more decimal digits ("the integer"), optionally
 715      * followed by a fraction, optionally followed by an exponent.
 716      *
 717      * <p>The fraction consists of a decimal point followed by zero
 718      * or more decimal digits.  The string must contain at least one
 719      * digit in either the integer or the fraction.  The number formed
 720      * by the sign, the integer and the fraction is referred to as the
 721      * <i>significand</i>.
 722      *
 723      * <p>The exponent consists of the character {@code 'e'}
 724      * (<code>'\u0065'</code>) or {@code 'E'} (<code>'\u0045'</code>)
 725      * followed by one or more decimal digits.  The value of the
 726      * exponent must lie between -{@link Integer#MAX_VALUE} ({@link
 727      * Integer#MIN_VALUE}+1) and {@link Integer#MAX_VALUE}, inclusive.
 728      *
 729      * <p>More formally, the strings this constructor accepts are
 730      * described by the following grammar:
 731      * <blockquote>
 732      * <dl>
 733      * <dt><i>BigDecimalString:</i>
 734      * <dd><i>Sign<sub>opt</sub> Significand Exponent<sub>opt</sub></i>
 735      * <dt><i>Sign:</i>
 736      * <dd>{@code +}
 737      * <dd>{@code -}
 738      * <dt><i>Significand:</i>
 739      * <dd><i>IntegerPart</i> {@code .} <i>FractionPart<sub>opt</sub></i>
 740      * <dd>{@code .} <i>FractionPart</i>
 741      * <dd><i>IntegerPart</i>
 742      * <dt><i>IntegerPart:</i>
 743      * <dd><i>Digits</i>
 744      * <dt><i>FractionPart:</i>
 745      * <dd><i>Digits</i>
 746      * <dt><i>Exponent:</i>
 747      * <dd><i>ExponentIndicator SignedInteger</i>
 748      * <dt><i>ExponentIndicator:</i>
 749      * <dd>{@code e}
 750      * <dd>{@code E}
 751      * <dt><i>SignedInteger:</i>
 752      * <dd><i>Sign<sub>opt</sub> Digits</i>
 753      * <dt><i>Digits:</i>
 754      * <dd><i>Digit</i>
 755      * <dd><i>Digits Digit</i>
 756      * <dt><i>Digit:</i>
 757      * <dd>any character for which {@link Character#isDigit}
 758      * returns {@code true}, including 0, 1, 2 ...
 759      * </dl>
 760      * </blockquote>
 761      *
 762      * <p>The scale of the returned {@code BigDecimal} will be the
 763      * number of digits in the fraction, or zero if the string
 764      * contains no decimal point, subject to adjustment for any
 765      * exponent; if the string contains an exponent, the exponent is
 766      * subtracted from the scale.  The value of the resulting scale
 767      * must lie between {@code Integer.MIN_VALUE} and
 768      * {@code Integer.MAX_VALUE}, inclusive.
 769      *
 770      * <p>The character-to-digit mapping is provided by {@link
 771      * java.lang.Character#digit} set to convert to radix 10.  The
 772      * String may not contain any extraneous characters (whitespace,
 773      * for example).
 774      *
 775      * <p><b>Examples:</b><br>
 776      * The value of the returned {@code BigDecimal} is equal to
 777      * <i>significand</i> &times; 10<sup>&nbsp;<i>exponent</i></sup>.
 778      * For each string on the left, the resulting representation
 779      * [{@code BigInteger}, {@code scale}] is shown on the right.
 780      * <pre>
 781      * "0"            [0,0]
 782      * "0.00"         [0,2]
 783      * "123"          [123,0]
 784      * "-123"         [-123,0]
 785      * "1.23E3"       [123,-1]
 786      * "1.23E+3"      [123,-1]
 787      * "12.3E+7"      [123,-6]
 788      * "12.0"         [120,1]
 789      * "12.3"         [123,1]
 790      * "0.00123"      [123,5]
 791      * "-1.23E-12"    [-123,14]
 792      * "1234.5E-4"    [12345,5]
 793      * "0E+7"         [0,-7]
 794      * "-0"           [0,0]
 795      * </pre>
 796      *
 797      * <p>Note: For values other than {@code float} and
 798      * {@code double} NaN and &plusmn;Infinity, this constructor is
 799      * compatible with the values returned by {@link Float#toString}
 800      * and {@link Double#toString}.  This is generally the preferred
 801      * way to convert a {@code float} or {@code double} into a
 802      * BigDecimal, as it doesn't suffer from the unpredictability of
 803      * the {@link #BigDecimal(double)} constructor.
 804      *
 805      * @param val String representation of {@code BigDecimal}.
 806      *
 807      * @throws NumberFormatException if {@code val} is not a valid
 808      *         representation of a {@code BigDecimal}.
 809      */
 810     public BigDecimal(String val) {
 811         this(val.toCharArray(), 0, val.length());
 812     }
 813 
 814     /**
 815      * Translates the string representation of a {@code BigDecimal}
 816      * into a {@code BigDecimal}, accepting the same strings as the
 817      * {@link #BigDecimal(String)} constructor, with rounding
 818      * according to the context settings.
 819      *
 820      * @param  val string representation of a {@code BigDecimal}.
 821      * @param  mc the context to use.
 822      * @throws ArithmeticException if the result is inexact but the
 823      *         rounding mode is {@code UNNECESSARY}.
 824      * @throws NumberFormatException if {@code val} is not a valid
 825      *         representation of a BigDecimal.
 826      * @since  1.5
 827      */
 828     public BigDecimal(String val, MathContext mc) {
 829         this(val.toCharArray(), 0, val.length(), mc);
 830     }
 831 
 832     /**
 833      * Translates a {@code double} into a {@code BigDecimal} which
 834      * is the exact decimal representation of the {@code double}'s
 835      * binary floating-point value.  The scale of the returned
 836      * {@code BigDecimal} is the smallest value such that
 837      * <code>(10<sup>scale</sup> &times; val)</code> is an integer.
 838      * <p>
 839      * <b>Notes:</b>
 840      * <ol>
 841      * <li>
 842      * The results of this constructor can be somewhat unpredictable.
 843      * One might assume that writing {@code new BigDecimal(0.1)} in
 844      * Java creates a {@code BigDecimal} which is exactly equal to
 845      * 0.1 (an unscaled value of 1, with a scale of 1), but it is
 846      * actually equal to
 847      * 0.1000000000000000055511151231257827021181583404541015625.
 848      * This is because 0.1 cannot be represented exactly as a
 849      * {@code double} (or, for that matter, as a binary fraction of
 850      * any finite length).  Thus, the value that is being passed
 851      * <i>in</i> to the constructor is not exactly equal to 0.1,
 852      * appearances notwithstanding.
 853      *
 854      * <li>
 855      * The {@code String} constructor, on the other hand, is
 856      * perfectly predictable: writing {@code new BigDecimal("0.1")}
 857      * creates a {@code BigDecimal} which is <i>exactly</i> equal to
 858      * 0.1, as one would expect.  Therefore, it is generally
 859      * recommended that the {@linkplain #BigDecimal(String)
 860      * String constructor} be used in preference to this one.
 861      *
 862      * <li>
 863      * When a {@code double} must be used as a source for a
 864      * {@code BigDecimal}, note that this constructor provides an
 865      * exact conversion; it does not give the same result as
 866      * converting the {@code double} to a {@code String} using the
 867      * {@link Double#toString(double)} method and then using the
 868      * {@link #BigDecimal(String)} constructor.  To get that result,
 869      * use the {@code static} {@link #valueOf(double)} method.
 870      * </ol>
 871      *
 872      * @param val {@code double} value to be converted to
 873      *        {@code BigDecimal}.
 874      * @throws NumberFormatException if {@code val} is infinite or NaN.
 875      */
 876     public BigDecimal(double val) {
 877         this(val,MathContext.UNLIMITED);
 878     }
 879 
 880     /**
 881      * Translates a {@code double} into a {@code BigDecimal}, with
 882      * rounding according to the context settings.  The scale of the
 883      * {@code BigDecimal} is the smallest value such that
 884      * <code>(10<sup>scale</sup> &times; val)</code> is an integer.
 885      *
 886      * <p>The results of this constructor can be somewhat unpredictable
 887      * and its use is generally not recommended; see the notes under
 888      * the {@link #BigDecimal(double)} constructor.
 889      *
 890      * @param  val {@code double} value to be converted to
 891      *         {@code BigDecimal}.
 892      * @param  mc the context to use.
 893      * @throws ArithmeticException if the result is inexact but the
 894      *         RoundingMode is UNNECESSARY.
 895      * @throws NumberFormatException if {@code val} is infinite or NaN.
 896      * @since  1.5
 897      */
 898     public BigDecimal(double val, MathContext mc) {
 899         if (Double.isInfinite(val) || Double.isNaN(val))
 900             throw new NumberFormatException("Infinite or NaN");
 901         // Translate the double into sign, exponent and significand, according
 902         // to the formulae in JLS, Section 20.10.22.
 903         long valBits = Double.doubleToLongBits(val);
 904         int sign = ((valBits >> 63) == 0 ? 1 : -1);
 905         int exponent = (int) ((valBits >> 52) & 0x7ffL);
 906         long significand = (exponent == 0
 907                 ? (valBits & ((1L << 52) - 1)) << 1
 908                 : (valBits & ((1L << 52) - 1)) | (1L << 52));
 909         exponent -= 1075;
 910         // At this point, val == sign * significand * 2**exponent.
 911 
 912         /*
 913          * Special case zero to supress nonterminating normalization and bogus
 914          * scale calculation.
 915          */
 916         if (significand == 0) {
 917             this.intVal = BigInteger.ZERO;
 918             this.scale = 0;
 919             this.intCompact = 0;
 920             this.precision = 1;
 921             return;
 922         }
 923         // Normalize
 924         while ((significand & 1) == 0) { // i.e., significand is even
 925             significand >>= 1;
 926             exponent++;
 927         }
 928         int scl = 0;
 929         // Calculate intVal and scale
 930         BigInteger rb;
 931         long compactVal = sign * significand;
 932         if (exponent == 0) {
 933             rb = (compactVal == INFLATED) ? INFLATED_BIGINT : null;
 934         } else {
 935             if (exponent < 0) {
 936                 rb = BigInteger.valueOf(5).pow(-exponent).multiply(compactVal);
 937                 scl = -exponent;
 938             } else { //  (exponent > 0)
 939                 rb = BigInteger.TWO.pow(exponent).multiply(compactVal);
 940             }
 941             compactVal = compactValFor(rb);
 942         }
 943         int prec = 0;
 944         int mcp = mc.precision;
 945         if (mcp > 0) { // do rounding
 946             int mode = mc.roundingMode.oldMode;
 947             int drop;
 948             if (compactVal == INFLATED) {
 949                 prec = bigDigitLength(rb);
 950                 drop = prec - mcp;
 951                 while (drop > 0) {
 952                     scl = checkScaleNonZero((long) scl - drop);
 953                     rb = divideAndRoundByTenPow(rb, drop, mode);
 954                     compactVal = compactValFor(rb);
 955                     if (compactVal != INFLATED) {
 956                         break;
 957                     }
 958                     prec = bigDigitLength(rb);
 959                     drop = prec - mcp;
 960                 }
 961             }
 962             if (compactVal != INFLATED) {
 963                 prec = longDigitLength(compactVal);
 964                 drop = prec - mcp;
 965                 while (drop > 0) {
 966                     scl = checkScaleNonZero((long) scl - drop);
 967                     compactVal = divideAndRound(compactVal, LONG_TEN_POWERS_TABLE[drop], mc.roundingMode.oldMode);
 968                     prec = longDigitLength(compactVal);
 969                     drop = prec - mcp;
 970                 }
 971                 rb = null;
 972             }
 973         }
 974         this.intVal = rb;
 975         this.intCompact = compactVal;
 976         this.scale = scl;
 977         this.precision = prec;
 978     }
 979 
 980     /**
 981      * Translates a {@code BigInteger} into a {@code BigDecimal}.
 982      * The scale of the {@code BigDecimal} is zero.
 983      *
 984      * @param val {@code BigInteger} value to be converted to
 985      *            {@code BigDecimal}.
 986      */
 987     public BigDecimal(BigInteger val) {
 988         scale = 0;
 989         intVal = val;
 990         intCompact = compactValFor(val);
 991     }
 992 
 993     /**
 994      * Translates a {@code BigInteger} into a {@code BigDecimal}
 995      * rounding according to the context settings.  The scale of the
 996      * {@code BigDecimal} is zero.
 997      *
 998      * @param val {@code BigInteger} value to be converted to
 999      *            {@code BigDecimal}.
1000      * @param  mc the context to use.
1001      * @throws ArithmeticException if the result is inexact but the
1002      *         rounding mode is {@code UNNECESSARY}.
1003      * @since  1.5
1004      */
1005     public BigDecimal(BigInteger val, MathContext mc) {
1006         this(val,0,mc);
1007     }
1008 
1009     /**
1010      * Translates a {@code BigInteger} unscaled value and an
1011      * {@code int} scale into a {@code BigDecimal}.  The value of
1012      * the {@code BigDecimal} is
1013      * <code>(unscaledVal &times; 10<sup>-scale</sup>)</code>.
1014      *
1015      * @param unscaledVal unscaled value of the {@code BigDecimal}.
1016      * @param scale scale of the {@code BigDecimal}.
1017      */
1018     public BigDecimal(BigInteger unscaledVal, int scale) {
1019         // Negative scales are now allowed
1020         this.intVal = unscaledVal;
1021         this.intCompact = compactValFor(unscaledVal);
1022         this.scale = scale;
1023     }
1024 
1025     /**
1026      * Translates a {@code BigInteger} unscaled value and an
1027      * {@code int} scale into a {@code BigDecimal}, with rounding
1028      * according to the context settings.  The value of the
1029      * {@code BigDecimal} is <code>(unscaledVal &times;
1030      * 10<sup>-scale</sup>)</code>, rounded according to the
1031      * {@code precision} and rounding mode settings.
1032      *
1033      * @param  unscaledVal unscaled value of the {@code BigDecimal}.
1034      * @param  scale scale of the {@code BigDecimal}.
1035      * @param  mc the context to use.
1036      * @throws ArithmeticException if the result is inexact but the
1037      *         rounding mode is {@code UNNECESSARY}.
1038      * @since  1.5
1039      */
1040     public BigDecimal(BigInteger unscaledVal, int scale, MathContext mc) {
1041         long compactVal = compactValFor(unscaledVal);
1042         int mcp = mc.precision;
1043         int prec = 0;
1044         if (mcp > 0) { // do rounding
1045             int mode = mc.roundingMode.oldMode;
1046             if (compactVal == INFLATED) {
1047                 prec = bigDigitLength(unscaledVal);
1048                 int drop = prec - mcp;
1049                 while (drop > 0) {
1050                     scale = checkScaleNonZero((long) scale - drop);
1051                     unscaledVal = divideAndRoundByTenPow(unscaledVal, drop, mode);
1052                     compactVal = compactValFor(unscaledVal);
1053                     if (compactVal != INFLATED) {
1054                         break;
1055                     }
1056                     prec = bigDigitLength(unscaledVal);
1057                     drop = prec - mcp;
1058                 }
1059             }
1060             if (compactVal != INFLATED) {
1061                 prec = longDigitLength(compactVal);
1062                 int drop = prec - mcp;     // drop can't be more than 18
1063                 while (drop > 0) {
1064                     scale = checkScaleNonZero((long) scale - drop);
1065                     compactVal = divideAndRound(compactVal, LONG_TEN_POWERS_TABLE[drop], mode);
1066                     prec = longDigitLength(compactVal);
1067                     drop = prec - mcp;
1068                 }
1069                 unscaledVal = null;
1070             }
1071         }
1072         this.intVal = unscaledVal;
1073         this.intCompact = compactVal;
1074         this.scale = scale;
1075         this.precision = prec;
1076     }
1077 
1078     /**
1079      * Translates an {@code int} into a {@code BigDecimal}.  The
1080      * scale of the {@code BigDecimal} is zero.
1081      *
1082      * @param val {@code int} value to be converted to
1083      *            {@code BigDecimal}.
1084      * @since  1.5
1085      */
1086     public BigDecimal(int val) {
1087         this.intCompact = val;
1088         this.scale = 0;
1089         this.intVal = null;
1090     }
1091 
1092     /**
1093      * Translates an {@code int} into a {@code BigDecimal}, with
1094      * rounding according to the context settings.  The scale of the
1095      * {@code BigDecimal}, before any rounding, is zero.
1096      *
1097      * @param  val {@code int} value to be converted to {@code BigDecimal}.
1098      * @param  mc the context to use.
1099      * @throws ArithmeticException if the result is inexact but the
1100      *         rounding mode is {@code UNNECESSARY}.
1101      * @since  1.5
1102      */
1103     public BigDecimal(int val, MathContext mc) {
1104         int mcp = mc.precision;
1105         long compactVal = val;
1106         int scl = 0;
1107         int prec = 0;
1108         if (mcp > 0) { // do rounding
1109             prec = longDigitLength(compactVal);
1110             int drop = prec - mcp; // drop can't be more than 18
1111             while (drop > 0) {
1112                 scl = checkScaleNonZero((long) scl - drop);
1113                 compactVal = divideAndRound(compactVal, LONG_TEN_POWERS_TABLE[drop], mc.roundingMode.oldMode);
1114                 prec = longDigitLength(compactVal);
1115                 drop = prec - mcp;
1116             }
1117         }
1118         this.intVal = null;
1119         this.intCompact = compactVal;
1120         this.scale = scl;
1121         this.precision = prec;
1122     }
1123 
1124     /**
1125      * Translates a {@code long} into a {@code BigDecimal}.  The
1126      * scale of the {@code BigDecimal} is zero.
1127      *
1128      * @param val {@code long} value to be converted to {@code BigDecimal}.
1129      * @since  1.5
1130      */
1131     public BigDecimal(long val) {
1132         this.intCompact = val;
1133         this.intVal = (val == INFLATED) ? INFLATED_BIGINT : null;
1134         this.scale = 0;
1135     }
1136 
1137     /**
1138      * Translates a {@code long} into a {@code BigDecimal}, with
1139      * rounding according to the context settings.  The scale of the
1140      * {@code BigDecimal}, before any rounding, is zero.
1141      *
1142      * @param  val {@code long} value to be converted to {@code BigDecimal}.
1143      * @param  mc the context to use.
1144      * @throws ArithmeticException if the result is inexact but the
1145      *         rounding mode is {@code UNNECESSARY}.
1146      * @since  1.5
1147      */
1148     public BigDecimal(long val, MathContext mc) {
1149         int mcp = mc.precision;
1150         int mode = mc.roundingMode.oldMode;
1151         int prec = 0;
1152         int scl = 0;
1153         BigInteger rb = (val == INFLATED) ? INFLATED_BIGINT : null;
1154         if (mcp > 0) { // do rounding
1155             if (val == INFLATED) {
1156                 prec = 19;
1157                 int drop = prec - mcp;
1158                 while (drop > 0) {
1159                     scl = checkScaleNonZero((long) scl - drop);
1160                     rb = divideAndRoundByTenPow(rb, drop, mode);
1161                     val = compactValFor(rb);
1162                     if (val != INFLATED) {
1163                         break;
1164                     }
1165                     prec = bigDigitLength(rb);
1166                     drop = prec - mcp;
1167                 }
1168             }
1169             if (val != INFLATED) {
1170                 prec = longDigitLength(val);
1171                 int drop = prec - mcp;
1172                 while (drop > 0) {
1173                     scl = checkScaleNonZero((long) scl - drop);
1174                     val = divideAndRound(val, LONG_TEN_POWERS_TABLE[drop], mc.roundingMode.oldMode);
1175                     prec = longDigitLength(val);
1176                     drop = prec - mcp;
1177                 }
1178                 rb = null;
1179             }
1180         }
1181         this.intVal = rb;
1182         this.intCompact = val;
1183         this.scale = scl;
1184         this.precision = prec;
1185     }
1186 
1187     // Static Factory Methods
1188 
1189     /**
1190      * Translates a {@code long} unscaled value and an
1191      * {@code int} scale into a {@code BigDecimal}.  This
1192      * {@literal "static factory method"} is provided in preference to
1193      * a ({@code long}, {@code int}) constructor because it
1194      * allows for reuse of frequently used {@code BigDecimal} values..
1195      *
1196      * @param unscaledVal unscaled value of the {@code BigDecimal}.
1197      * @param scale scale of the {@code BigDecimal}.
1198      * @return a {@code BigDecimal} whose value is
1199      *         <code>(unscaledVal &times; 10<sup>-scale</sup>)</code>.
1200      */
1201     public static BigDecimal valueOf(long unscaledVal, int scale) {
1202         if (scale == 0)
1203             return valueOf(unscaledVal);
1204         else if (unscaledVal == 0) {
1205             return zeroValueOf(scale);
1206         }
1207         return new BigDecimal(unscaledVal == INFLATED ?
1208                               INFLATED_BIGINT : null,
1209                               unscaledVal, scale, 0);
1210     }
1211 
1212     /**
1213      * Translates a {@code long} value into a {@code BigDecimal}
1214      * with a scale of zero.  This {@literal "static factory method"}
1215      * is provided in preference to a ({@code long}) constructor
1216      * because it allows for reuse of frequently used
1217      * {@code BigDecimal} values.
1218      *
1219      * @param val value of the {@code BigDecimal}.
1220      * @return a {@code BigDecimal} whose value is {@code val}.
1221      */
1222     public static BigDecimal valueOf(long val) {
1223         if (val >= 0 && val < ZERO_THROUGH_TEN.length)
1224             return ZERO_THROUGH_TEN[(int)val];
1225         else if (val != INFLATED)
1226             return new BigDecimal(null, val, 0, 0);
1227         return new BigDecimal(INFLATED_BIGINT, val, 0, 0);
1228     }
1229 
1230     static BigDecimal valueOf(long unscaledVal, int scale, int prec) {
1231         if (scale == 0 && unscaledVal >= 0 && unscaledVal < ZERO_THROUGH_TEN.length) {
1232             return ZERO_THROUGH_TEN[(int) unscaledVal];
1233         } else if (unscaledVal == 0) {
1234             return zeroValueOf(scale);
1235         }
1236         return new BigDecimal(unscaledVal == INFLATED ? INFLATED_BIGINT : null,
1237                 unscaledVal, scale, prec);
1238     }
1239 
1240     static BigDecimal valueOf(BigInteger intVal, int scale, int prec) {
1241         long val = compactValFor(intVal);
1242         if (val == 0) {
1243             return zeroValueOf(scale);
1244         } else if (scale == 0 && val >= 0 && val < ZERO_THROUGH_TEN.length) {
1245             return ZERO_THROUGH_TEN[(int) val];
1246         }
1247         return new BigDecimal(intVal, val, scale, prec);
1248     }
1249 
1250     static BigDecimal zeroValueOf(int scale) {
1251         if (scale >= 0 && scale < ZERO_SCALED_BY.length)
1252             return ZERO_SCALED_BY[scale];
1253         else
1254             return new BigDecimal(BigInteger.ZERO, 0, scale, 1);
1255     }
1256 
1257     /**
1258      * Translates a {@code double} into a {@code BigDecimal}, using
1259      * the {@code double}'s canonical string representation provided
1260      * by the {@link Double#toString(double)} method.
1261      *
1262      * <p><b>Note:</b> This is generally the preferred way to convert
1263      * a {@code double} (or {@code float}) into a
1264      * {@code BigDecimal}, as the value returned is equal to that
1265      * resulting from constructing a {@code BigDecimal} from the
1266      * result of using {@link Double#toString(double)}.
1267      *
1268      * @param  val {@code double} to convert to a {@code BigDecimal}.
1269      * @return a {@code BigDecimal} whose value is equal to or approximately
1270      *         equal to the value of {@code val}.
1271      * @throws NumberFormatException if {@code val} is infinite or NaN.
1272      * @since  1.5
1273      */
1274     public static BigDecimal valueOf(double val) {
1275         // Reminder: a zero double returns '0.0', so we cannot fastpath
1276         // to use the constant ZERO.  This might be important enough to
1277         // justify a factory approach, a cache, or a few private
1278         // constants, later.
1279         return new BigDecimal(Double.toString(val));
1280     }
1281 
1282     // Arithmetic Operations
1283     /**
1284      * Returns a {@code BigDecimal} whose value is {@code (this +
1285      * augend)}, and whose scale is {@code max(this.scale(),
1286      * augend.scale())}.
1287      *
1288      * @param  augend value to be added to this {@code BigDecimal}.
1289      * @return {@code this + augend}
1290      */
1291     public BigDecimal add(BigDecimal augend) {
1292         if (this.intCompact != INFLATED) {
1293             if ((augend.intCompact != INFLATED)) {
1294                 return add(this.intCompact, this.scale, augend.intCompact, augend.scale);
1295             } else {
1296                 return add(this.intCompact, this.scale, augend.intVal, augend.scale);
1297             }
1298         } else {
1299             if ((augend.intCompact != INFLATED)) {
1300                 return add(augend.intCompact, augend.scale, this.intVal, this.scale);
1301             } else {
1302                 return add(this.intVal, this.scale, augend.intVal, augend.scale);
1303             }
1304         }
1305     }
1306 
1307     /**
1308      * Returns a {@code BigDecimal} whose value is {@code (this + augend)},
1309      * with rounding according to the context settings.
1310      *
1311      * If either number is zero and the precision setting is nonzero then
1312      * the other number, rounded if necessary, is used as the result.
1313      *
1314      * @param  augend value to be added to this {@code BigDecimal}.
1315      * @param  mc the context to use.
1316      * @return {@code this + augend}, rounded as necessary.
1317      * @throws ArithmeticException if the result is inexact but the
1318      *         rounding mode is {@code UNNECESSARY}.
1319      * @since  1.5
1320      */
1321     public BigDecimal add(BigDecimal augend, MathContext mc) {
1322         if (mc.precision == 0)
1323             return add(augend);
1324         BigDecimal lhs = this;
1325 
1326         // If either number is zero then the other number, rounded and
1327         // scaled if necessary, is used as the result.
1328         {
1329             boolean lhsIsZero = lhs.signum() == 0;
1330             boolean augendIsZero = augend.signum() == 0;
1331 
1332             if (lhsIsZero || augendIsZero) {
1333                 int preferredScale = Math.max(lhs.scale(), augend.scale());
1334                 BigDecimal result;
1335 
1336                 if (lhsIsZero && augendIsZero)
1337                     return zeroValueOf(preferredScale);
1338                 result = lhsIsZero ? doRound(augend, mc) : doRound(lhs, mc);
1339 
1340                 if (result.scale() == preferredScale)
1341                     return result;
1342                 else if (result.scale() > preferredScale) {
1343                     return stripZerosToMatchScale(result.intVal, result.intCompact, result.scale, preferredScale);
1344                 } else { // result.scale < preferredScale
1345                     int precisionDiff = mc.precision - result.precision();
1346                     int scaleDiff     = preferredScale - result.scale();
1347 
1348                     if (precisionDiff >= scaleDiff)
1349                         return result.setScale(preferredScale); // can achieve target scale
1350                     else
1351                         return result.setScale(result.scale() + precisionDiff);
1352                 }
1353             }
1354         }
1355 
1356         long padding = (long) lhs.scale - augend.scale;
1357         if (padding != 0) { // scales differ; alignment needed
1358             BigDecimal arg[] = preAlign(lhs, augend, padding, mc);
1359             matchScale(arg);
1360             lhs = arg[0];
1361             augend = arg[1];
1362         }
1363         return doRound(lhs.inflated().add(augend.inflated()), lhs.scale, mc);
1364     }
1365 
1366     /**
1367      * Returns an array of length two, the sum of whose entries is
1368      * equal to the rounded sum of the {@code BigDecimal} arguments.
1369      *
1370      * <p>If the digit positions of the arguments have a sufficient
1371      * gap between them, the value smaller in magnitude can be
1372      * condensed into a {@literal "sticky bit"} and the end result will
1373      * round the same way <em>if</em> the precision of the final
1374      * result does not include the high order digit of the small
1375      * magnitude operand.
1376      *
1377      * <p>Note that while strictly speaking this is an optimization,
1378      * it makes a much wider range of additions practical.
1379      *
1380      * <p>This corresponds to a pre-shift operation in a fixed
1381      * precision floating-point adder; this method is complicated by
1382      * variable precision of the result as determined by the
1383      * MathContext.  A more nuanced operation could implement a
1384      * {@literal "right shift"} on the smaller magnitude operand so
1385      * that the number of digits of the smaller operand could be
1386      * reduced even though the significands partially overlapped.
1387      */
1388     private BigDecimal[] preAlign(BigDecimal lhs, BigDecimal augend, long padding, MathContext mc) {
1389         assert padding != 0;
1390         BigDecimal big;
1391         BigDecimal small;
1392 
1393         if (padding < 0) { // lhs is big; augend is small
1394             big = lhs;
1395             small = augend;
1396         } else { // lhs is small; augend is big
1397             big = augend;
1398             small = lhs;
1399         }
1400 
1401         /*
1402          * This is the estimated scale of an ulp of the result; it assumes that
1403          * the result doesn't have a carry-out on a true add (e.g. 999 + 1 =>
1404          * 1000) or any subtractive cancellation on borrowing (e.g. 100 - 1.2 =>
1405          * 98.8)
1406          */
1407         long estResultUlpScale = (long) big.scale - big.precision() + mc.precision;
1408 
1409         /*
1410          * The low-order digit position of big is big.scale().  This
1411          * is true regardless of whether big has a positive or
1412          * negative scale.  The high-order digit position of small is
1413          * small.scale - (small.precision() - 1).  To do the full
1414          * condensation, the digit positions of big and small must be
1415          * disjoint *and* the digit positions of small should not be
1416          * directly visible in the result.
1417          */
1418         long smallHighDigitPos = (long) small.scale - small.precision() + 1;
1419         if (smallHighDigitPos > big.scale + 2 && // big and small disjoint
1420             smallHighDigitPos > estResultUlpScale + 2) { // small digits not visible
1421             small = BigDecimal.valueOf(small.signum(), this.checkScale(Math.max(big.scale, estResultUlpScale) + 3));
1422         }
1423 
1424         // Since addition is symmetric, preserving input order in
1425         // returned operands doesn't matter
1426         BigDecimal[] result = {big, small};
1427         return result;
1428     }
1429 
1430     /**
1431      * Returns a {@code BigDecimal} whose value is {@code (this -
1432      * subtrahend)}, and whose scale is {@code max(this.scale(),
1433      * subtrahend.scale())}.
1434      *
1435      * @param  subtrahend value to be subtracted from this {@code BigDecimal}.
1436      * @return {@code this - subtrahend}
1437      */
1438     public BigDecimal subtract(BigDecimal subtrahend) {
1439         if (this.intCompact != INFLATED) {
1440             if ((subtrahend.intCompact != INFLATED)) {
1441                 return add(this.intCompact, this.scale, -subtrahend.intCompact, subtrahend.scale);
1442             } else {
1443                 return add(this.intCompact, this.scale, subtrahend.intVal.negate(), subtrahend.scale);
1444             }
1445         } else {
1446             if ((subtrahend.intCompact != INFLATED)) {
1447                 // Pair of subtrahend values given before pair of
1448                 // values from this BigDecimal to avoid need for
1449                 // method overloading on the specialized add method
1450                 return add(-subtrahend.intCompact, subtrahend.scale, this.intVal, this.scale);
1451             } else {
1452                 return add(this.intVal, this.scale, subtrahend.intVal.negate(), subtrahend.scale);
1453             }
1454         }
1455     }
1456 
1457     /**
1458      * Returns a {@code BigDecimal} whose value is {@code (this - subtrahend)},
1459      * with rounding according to the context settings.
1460      *
1461      * If {@code subtrahend} is zero then this, rounded if necessary, is used as the
1462      * result.  If this is zero then the result is {@code subtrahend.negate(mc)}.
1463      *
1464      * @param  subtrahend value to be subtracted from this {@code BigDecimal}.
1465      * @param  mc the context to use.
1466      * @return {@code this - subtrahend}, rounded as necessary.
1467      * @throws ArithmeticException if the result is inexact but the
1468      *         rounding mode is {@code UNNECESSARY}.
1469      * @since  1.5
1470      */
1471     public BigDecimal subtract(BigDecimal subtrahend, MathContext mc) {
1472         if (mc.precision == 0)
1473             return subtract(subtrahend);
1474         // share the special rounding code in add()
1475         return add(subtrahend.negate(), mc);
1476     }
1477 
1478     /**
1479      * Returns a {@code BigDecimal} whose value is <code>(this &times;
1480      * multiplicand)</code>, and whose scale is {@code (this.scale() +
1481      * multiplicand.scale())}.
1482      *
1483      * @param  multiplicand value to be multiplied by this {@code BigDecimal}.
1484      * @return {@code this * multiplicand}
1485      */
1486     public BigDecimal multiply(BigDecimal multiplicand) {
1487         int productScale = checkScale((long) scale + multiplicand.scale);
1488         if (this.intCompact != INFLATED) {
1489             if ((multiplicand.intCompact != INFLATED)) {
1490                 return multiply(this.intCompact, multiplicand.intCompact, productScale);
1491             } else {
1492                 return multiply(this.intCompact, multiplicand.intVal, productScale);
1493             }
1494         } else {
1495             if ((multiplicand.intCompact != INFLATED)) {
1496                 return multiply(multiplicand.intCompact, this.intVal, productScale);
1497             } else {
1498                 return multiply(this.intVal, multiplicand.intVal, productScale);
1499             }
1500         }
1501     }
1502 
1503     /**
1504      * Returns a {@code BigDecimal} whose value is <code>(this &times;
1505      * multiplicand)</code>, with rounding according to the context settings.
1506      *
1507      * @param  multiplicand value to be multiplied by this {@code BigDecimal}.
1508      * @param  mc the context to use.
1509      * @return {@code this * multiplicand}, rounded as necessary.
1510      * @throws ArithmeticException if the result is inexact but the
1511      *         rounding mode is {@code UNNECESSARY}.
1512      * @since  1.5
1513      */
1514     public BigDecimal multiply(BigDecimal multiplicand, MathContext mc) {
1515         if (mc.precision == 0)
1516             return multiply(multiplicand);
1517         int productScale = checkScale((long) scale + multiplicand.scale);
1518         if (this.intCompact != INFLATED) {
1519             if ((multiplicand.intCompact != INFLATED)) {
1520                 return multiplyAndRound(this.intCompact, multiplicand.intCompact, productScale, mc);
1521             } else {
1522                 return multiplyAndRound(this.intCompact, multiplicand.intVal, productScale, mc);
1523             }
1524         } else {
1525             if ((multiplicand.intCompact != INFLATED)) {
1526                 return multiplyAndRound(multiplicand.intCompact, this.intVal, productScale, mc);
1527             } else {
1528                 return multiplyAndRound(this.intVal, multiplicand.intVal, productScale, mc);
1529             }
1530         }
1531     }
1532 
1533     /**
1534      * Returns a {@code BigDecimal} whose value is {@code (this /
1535      * divisor)}, and whose scale is as specified.  If rounding must
1536      * be performed to generate a result with the specified scale, the
1537      * specified rounding mode is applied.
1538      *
1539      * @deprecated The method {@link #divide(BigDecimal, int, RoundingMode)}
1540      * should be used in preference to this legacy method.
1541      *
1542      * @param  divisor value by which this {@code BigDecimal} is to be divided.
1543      * @param  scale scale of the {@code BigDecimal} quotient to be returned.
1544      * @param  roundingMode rounding mode to apply.
1545      * @return {@code this / divisor}
1546      * @throws ArithmeticException if {@code divisor} is zero,
1547      *         {@code roundingMode==ROUND_UNNECESSARY} and
1548      *         the specified scale is insufficient to represent the result
1549      *         of the division exactly.
1550      * @throws IllegalArgumentException if {@code roundingMode} does not
1551      *         represent a valid rounding mode.
1552      * @see    #ROUND_UP
1553      * @see    #ROUND_DOWN
1554      * @see    #ROUND_CEILING
1555      * @see    #ROUND_FLOOR
1556      * @see    #ROUND_HALF_UP
1557      * @see    #ROUND_HALF_DOWN
1558      * @see    #ROUND_HALF_EVEN
1559      * @see    #ROUND_UNNECESSARY
1560      */
1561     @Deprecated(since="9")
1562     public BigDecimal divide(BigDecimal divisor, int scale, int roundingMode) {
1563         if (roundingMode < ROUND_UP || roundingMode > ROUND_UNNECESSARY)
1564             throw new IllegalArgumentException("Invalid rounding mode");
1565         if (this.intCompact != INFLATED) {
1566             if ((divisor.intCompact != INFLATED)) {
1567                 return divide(this.intCompact, this.scale, divisor.intCompact, divisor.scale, scale, roundingMode);
1568             } else {
1569                 return divide(this.intCompact, this.scale, divisor.intVal, divisor.scale, scale, roundingMode);
1570             }
1571         } else {
1572             if ((divisor.intCompact != INFLATED)) {
1573                 return divide(this.intVal, this.scale, divisor.intCompact, divisor.scale, scale, roundingMode);
1574             } else {
1575                 return divide(this.intVal, this.scale, divisor.intVal, divisor.scale, scale, roundingMode);
1576             }
1577         }
1578     }
1579 
1580     /**
1581      * Returns a {@code BigDecimal} whose value is {@code (this /
1582      * divisor)}, and whose scale is as specified.  If rounding must
1583      * be performed to generate a result with the specified scale, the
1584      * specified rounding mode is applied.
1585      *
1586      * @param  divisor value by which this {@code BigDecimal} is to be divided.
1587      * @param  scale scale of the {@code BigDecimal} quotient to be returned.
1588      * @param  roundingMode rounding mode to apply.
1589      * @return {@code this / divisor}
1590      * @throws ArithmeticException if {@code divisor} is zero,
1591      *         {@code roundingMode==RoundingMode.UNNECESSARY} and
1592      *         the specified scale is insufficient to represent the result
1593      *         of the division exactly.
1594      * @since 1.5
1595      */
1596     public BigDecimal divide(BigDecimal divisor, int scale, RoundingMode roundingMode) {
1597         return divide(divisor, scale, roundingMode.oldMode);
1598     }
1599 
1600     /**
1601      * Returns a {@code BigDecimal} whose value is {@code (this /
1602      * divisor)}, and whose scale is {@code this.scale()}.  If
1603      * rounding must be performed to generate a result with the given
1604      * scale, the specified rounding mode is applied.
1605      *
1606      * @deprecated The method {@link #divide(BigDecimal, RoundingMode)} 
1607      * should be used in preference to this legacy method.
1608      *
1609      * @param  divisor value by which this {@code BigDecimal} is to be divided.
1610      * @param  roundingMode rounding mode to apply.
1611      * @return {@code this / divisor}
1612      * @throws ArithmeticException if {@code divisor==0}, or
1613      *         {@code roundingMode==ROUND_UNNECESSARY} and
1614      *         {@code this.scale()} is insufficient to represent the result
1615      *         of the division exactly.
1616      * @throws IllegalArgumentException if {@code roundingMode} does not
1617      *         represent a valid rounding mode.
1618      * @see    #ROUND_UP
1619      * @see    #ROUND_DOWN
1620      * @see    #ROUND_CEILING
1621      * @see    #ROUND_FLOOR
1622      * @see    #ROUND_HALF_UP
1623      * @see    #ROUND_HALF_DOWN
1624      * @see    #ROUND_HALF_EVEN
1625      * @see    #ROUND_UNNECESSARY
1626      */
1627     @Deprecated(since="9")
1628     public BigDecimal divide(BigDecimal divisor, int roundingMode) {
1629         return this.divide(divisor, scale, roundingMode);
1630     }
1631 
1632     /**
1633      * Returns a {@code BigDecimal} whose value is {@code (this /
1634      * divisor)}, and whose scale is {@code this.scale()}.  If
1635      * rounding must be performed to generate a result with the given
1636      * scale, the specified rounding mode is applied.
1637      *
1638      * @param  divisor value by which this {@code BigDecimal} is to be divided.
1639      * @param  roundingMode rounding mode to apply.
1640      * @return {@code this / divisor}
1641      * @throws ArithmeticException if {@code divisor==0}, or
1642      *         {@code roundingMode==RoundingMode.UNNECESSARY} and
1643      *         {@code this.scale()} is insufficient to represent the result
1644      *         of the division exactly.
1645      * @since 1.5
1646      */
1647     public BigDecimal divide(BigDecimal divisor, RoundingMode roundingMode) {
1648         return this.divide(divisor, scale, roundingMode.oldMode);
1649     }
1650 
1651     /**
1652      * Returns a {@code BigDecimal} whose value is {@code (this /
1653      * divisor)}, and whose preferred scale is {@code (this.scale() -
1654      * divisor.scale())}; if the exact quotient cannot be
1655      * represented (because it has a non-terminating decimal
1656      * expansion) an {@code ArithmeticException} is thrown.
1657      *
1658      * @param  divisor value by which this {@code BigDecimal} is to be divided.
1659      * @throws ArithmeticException if the exact quotient does not have a
1660      *         terminating decimal expansion
1661      * @return {@code this / divisor}
1662      * @since 1.5
1663      * @author Joseph D. Darcy
1664      */
1665     public BigDecimal divide(BigDecimal divisor) {
1666         /*
1667          * Handle zero cases first.
1668          */
1669         if (divisor.signum() == 0) {   // x/0
1670             if (this.signum() == 0)    // 0/0
1671                 throw new ArithmeticException("Division undefined");  // NaN
1672             throw new ArithmeticException("Division by zero");
1673         }
1674 
1675         // Calculate preferred scale
1676         int preferredScale = saturateLong((long) this.scale - divisor.scale);
1677 
1678         if (this.signum() == 0) // 0/y
1679             return zeroValueOf(preferredScale);
1680         else {
1681             /*
1682              * If the quotient this/divisor has a terminating decimal
1683              * expansion, the expansion can have no more than
1684              * (a.precision() + ceil(10*b.precision)/3) digits.
1685              * Therefore, create a MathContext object with this
1686              * precision and do a divide with the UNNECESSARY rounding
1687              * mode.
1688              */
1689             MathContext mc = new MathContext( (int)Math.min(this.precision() +
1690                                                             (long)Math.ceil(10.0*divisor.precision()/3.0),
1691                                                             Integer.MAX_VALUE),
1692                                               RoundingMode.UNNECESSARY);
1693             BigDecimal quotient;
1694             try {
1695                 quotient = this.divide(divisor, mc);
1696             } catch (ArithmeticException e) {
1697                 throw new ArithmeticException("Non-terminating decimal expansion; " +
1698                                               "no exact representable decimal result.");
1699             }
1700 
1701             int quotientScale = quotient.scale();
1702 
1703             // divide(BigDecimal, mc) tries to adjust the quotient to
1704             // the desired one by removing trailing zeros; since the
1705             // exact divide method does not have an explicit digit
1706             // limit, we can add zeros too.
1707             if (preferredScale > quotientScale)
1708                 return quotient.setScale(preferredScale, ROUND_UNNECESSARY);
1709 
1710             return quotient;
1711         }
1712     }
1713 
1714     /**
1715      * Returns a {@code BigDecimal} whose value is {@code (this /
1716      * divisor)}, with rounding according to the context settings.
1717      *
1718      * @param  divisor value by which this {@code BigDecimal} is to be divided.
1719      * @param  mc the context to use.
1720      * @return {@code this / divisor}, rounded as necessary.
1721      * @throws ArithmeticException if the result is inexact but the
1722      *         rounding mode is {@code UNNECESSARY} or
1723      *         {@code mc.precision == 0} and the quotient has a
1724      *         non-terminating decimal expansion.
1725      * @since  1.5
1726      */
1727     public BigDecimal divide(BigDecimal divisor, MathContext mc) {
1728         int mcp = mc.precision;
1729         if (mcp == 0)
1730             return divide(divisor);
1731 
1732         BigDecimal dividend = this;
1733         long preferredScale = (long)dividend.scale - divisor.scale;
1734         // Now calculate the answer.  We use the existing
1735         // divide-and-round method, but as this rounds to scale we have
1736         // to normalize the values here to achieve the desired result.
1737         // For x/y we first handle y=0 and x=0, and then normalize x and
1738         // y to give x' and y' with the following constraints:
1739         //   (a) 0.1 <= x' < 1
1740         //   (b)  x' <= y' < 10*x'
1741         // Dividing x'/y' with the required scale set to mc.precision then
1742         // will give a result in the range 0.1 to 1 rounded to exactly
1743         // the right number of digits (except in the case of a result of
1744         // 1.000... which can arise when x=y, or when rounding overflows
1745         // The 1.000... case will reduce properly to 1.
1746         if (divisor.signum() == 0) {      // x/0
1747             if (dividend.signum() == 0)    // 0/0
1748                 throw new ArithmeticException("Division undefined");  // NaN
1749             throw new ArithmeticException("Division by zero");
1750         }
1751         if (dividend.signum() == 0) // 0/y
1752             return zeroValueOf(saturateLong(preferredScale));
1753         int xscale = dividend.precision();
1754         int yscale = divisor.precision();
1755         if(dividend.intCompact!=INFLATED) {
1756             if(divisor.intCompact!=INFLATED) {
1757                 return divide(dividend.intCompact, xscale, divisor.intCompact, yscale, preferredScale, mc);
1758             } else {
1759                 return divide(dividend.intCompact, xscale, divisor.intVal, yscale, preferredScale, mc);
1760             }
1761         } else {
1762             if(divisor.intCompact!=INFLATED) {
1763                 return divide(dividend.intVal, xscale, divisor.intCompact, yscale, preferredScale, mc);
1764             } else {
1765                 return divide(dividend.intVal, xscale, divisor.intVal, yscale, preferredScale, mc);
1766             }
1767         }
1768     }
1769 
1770     /**
1771      * Returns a {@code BigDecimal} whose value is the integer part
1772      * of the quotient {@code (this / divisor)} rounded down.  The
1773      * preferred scale of the result is {@code (this.scale() -
1774      * divisor.scale())}.
1775      *
1776      * @param  divisor value by which this {@code BigDecimal} is to be divided.
1777      * @return The integer part of {@code this / divisor}.
1778      * @throws ArithmeticException if {@code divisor==0}
1779      * @since  1.5
1780      */
1781     public BigDecimal divideToIntegralValue(BigDecimal divisor) {
1782         // Calculate preferred scale
1783         int preferredScale = saturateLong((long) this.scale - divisor.scale);
1784         if (this.compareMagnitude(divisor) < 0) {
1785             // much faster when this << divisor
1786             return zeroValueOf(preferredScale);
1787         }
1788 
1789         if (this.signum() == 0 && divisor.signum() != 0)
1790             return this.setScale(preferredScale, ROUND_UNNECESSARY);
1791 
1792         // Perform a divide with enough digits to round to a correct
1793         // integer value; then remove any fractional digits
1794 
1795         int maxDigits = (int)Math.min(this.precision() +
1796                                       (long)Math.ceil(10.0*divisor.precision()/3.0) +
1797                                       Math.abs((long)this.scale() - divisor.scale()) + 2,
1798                                       Integer.MAX_VALUE);
1799         BigDecimal quotient = this.divide(divisor, new MathContext(maxDigits,
1800                                                                    RoundingMode.DOWN));
1801         if (quotient.scale > 0) {
1802             quotient = quotient.setScale(0, RoundingMode.DOWN);
1803             quotient = stripZerosToMatchScale(quotient.intVal, quotient.intCompact, quotient.scale, preferredScale);
1804         }
1805 
1806         if (quotient.scale < preferredScale) {
1807             // pad with zeros if necessary
1808             quotient = quotient.setScale(preferredScale, ROUND_UNNECESSARY);
1809         }
1810 
1811         return quotient;
1812     }
1813 
1814     /**
1815      * Returns a {@code BigDecimal} whose value is the integer part
1816      * of {@code (this / divisor)}.  Since the integer part of the
1817      * exact quotient does not depend on the rounding mode, the
1818      * rounding mode does not affect the values returned by this
1819      * method.  The preferred scale of the result is
1820      * {@code (this.scale() - divisor.scale())}.  An
1821      * {@code ArithmeticException} is thrown if the integer part of
1822      * the exact quotient needs more than {@code mc.precision}
1823      * digits.
1824      *
1825      * @param  divisor value by which this {@code BigDecimal} is to be divided.
1826      * @param  mc the context to use.
1827      * @return The integer part of {@code this / divisor}.
1828      * @throws ArithmeticException if {@code divisor==0}
1829      * @throws ArithmeticException if {@code mc.precision} {@literal >} 0 and the result
1830      *         requires a precision of more than {@code mc.precision} digits.
1831      * @since  1.5
1832      * @author Joseph D. Darcy
1833      */
1834     public BigDecimal divideToIntegralValue(BigDecimal divisor, MathContext mc) {
1835         if (mc.precision == 0 || // exact result
1836             (this.compareMagnitude(divisor) < 0)) // zero result
1837             return divideToIntegralValue(divisor);
1838 
1839         // Calculate preferred scale
1840         int preferredScale = saturateLong((long)this.scale - divisor.scale);
1841 
1842         /*
1843          * Perform a normal divide to mc.precision digits.  If the
1844          * remainder has absolute value less than the divisor, the
1845          * integer portion of the quotient fits into mc.precision
1846          * digits.  Next, remove any fractional digits from the
1847          * quotient and adjust the scale to the preferred value.
1848          */
1849         BigDecimal result = this.divide(divisor, new MathContext(mc.precision, RoundingMode.DOWN));
1850 
1851         if (result.scale() < 0) {
1852             /*
1853              * Result is an integer. See if quotient represents the
1854              * full integer portion of the exact quotient; if it does,
1855              * the computed remainder will be less than the divisor.
1856              */
1857             BigDecimal product = result.multiply(divisor);
1858             // If the quotient is the full integer value,
1859             // |dividend-product| < |divisor|.
1860             if (this.subtract(product).compareMagnitude(divisor) >= 0) {
1861                 throw new ArithmeticException("Division impossible");
1862             }
1863         } else if (result.scale() > 0) {
1864             /*
1865              * Integer portion of quotient will fit into precision
1866              * digits; recompute quotient to scale 0 to avoid double
1867              * rounding and then try to adjust, if necessary.
1868              */
1869             result = result.setScale(0, RoundingMode.DOWN);
1870         }
1871         // else result.scale() == 0;
1872 
1873         int precisionDiff;
1874         if ((preferredScale > result.scale()) &&
1875             (precisionDiff = mc.precision - result.precision()) > 0) {
1876             return result.setScale(result.scale() +
1877                                    Math.min(precisionDiff, preferredScale - result.scale) );
1878         } else {
1879             return stripZerosToMatchScale(result.intVal,result.intCompact,result.scale,preferredScale);
1880         }
1881     }
1882 
1883     /**
1884      * Returns a {@code BigDecimal} whose value is {@code (this % divisor)}.
1885      *
1886      * <p>The remainder is given by
1887      * {@code this.subtract(this.divideToIntegralValue(divisor).multiply(divisor))}.
1888      * Note that this is not the modulo operation (the result can be
1889      * negative).
1890      *
1891      * @param  divisor value by which this {@code BigDecimal} is to be divided.
1892      * @return {@code this % divisor}.
1893      * @throws ArithmeticException if {@code divisor==0}
1894      * @since  1.5
1895      */
1896     public BigDecimal remainder(BigDecimal divisor) {
1897         BigDecimal divrem[] = this.divideAndRemainder(divisor);
1898         return divrem[1];
1899     }
1900 
1901 
1902     /**
1903      * Returns a {@code BigDecimal} whose value is {@code (this %
1904      * divisor)}, with rounding according to the context settings.
1905      * The {@code MathContext} settings affect the implicit divide
1906      * used to compute the remainder.  The remainder computation
1907      * itself is by definition exact.  Therefore, the remainder may
1908      * contain more than {@code mc.getPrecision()} digits.
1909      *
1910      * <p>The remainder is given by
1911      * {@code this.subtract(this.divideToIntegralValue(divisor,
1912      * mc).multiply(divisor))}.  Note that this is not the modulo
1913      * operation (the result can be negative).
1914      *
1915      * @param  divisor value by which this {@code BigDecimal} is to be divided.
1916      * @param  mc the context to use.
1917      * @return {@code this % divisor}, rounded as necessary.
1918      * @throws ArithmeticException if {@code divisor==0}
1919      * @throws ArithmeticException if the result is inexact but the
1920      *         rounding mode is {@code UNNECESSARY}, or {@code mc.precision}
1921      *         {@literal >} 0 and the result of {@code this.divideToIntgralValue(divisor)} would
1922      *         require a precision of more than {@code mc.precision} digits.
1923      * @see    #divideToIntegralValue(java.math.BigDecimal, java.math.MathContext)
1924      * @since  1.5
1925      */
1926     public BigDecimal remainder(BigDecimal divisor, MathContext mc) {
1927         BigDecimal divrem[] = this.divideAndRemainder(divisor, mc);
1928         return divrem[1];
1929     }
1930 
1931     /**
1932      * Returns a two-element {@code BigDecimal} array containing the
1933      * result of {@code divideToIntegralValue} followed by the result of
1934      * {@code remainder} on the two operands.
1935      *
1936      * <p>Note that if both the integer quotient and remainder are
1937      * needed, this method is faster than using the
1938      * {@code divideToIntegralValue} and {@code remainder} methods
1939      * separately because the division need only be carried out once.
1940      *
1941      * @param  divisor value by which this {@code BigDecimal} is to be divided,
1942      *         and the remainder computed.
1943      * @return a two element {@code BigDecimal} array: the quotient
1944      *         (the result of {@code divideToIntegralValue}) is the initial element
1945      *         and the remainder is the final element.
1946      * @throws ArithmeticException if {@code divisor==0}
1947      * @see    #divideToIntegralValue(java.math.BigDecimal, java.math.MathContext)
1948      * @see    #remainder(java.math.BigDecimal, java.math.MathContext)
1949      * @since  1.5
1950      */
1951     public BigDecimal[] divideAndRemainder(BigDecimal divisor) {
1952         // we use the identity  x = i * y + r to determine r
1953         BigDecimal[] result = new BigDecimal[2];
1954 
1955         result[0] = this.divideToIntegralValue(divisor);
1956         result[1] = this.subtract(result[0].multiply(divisor));
1957         return result;
1958     }
1959 
1960     /**
1961      * Returns a two-element {@code BigDecimal} array containing the
1962      * result of {@code divideToIntegralValue} followed by the result of
1963      * {@code remainder} on the two operands calculated with rounding
1964      * according to the context settings.
1965      *
1966      * <p>Note that if both the integer quotient and remainder are
1967      * needed, this method is faster than using the
1968      * {@code divideToIntegralValue} and {@code remainder} methods
1969      * separately because the division need only be carried out once.
1970      *
1971      * @param  divisor value by which this {@code BigDecimal} is to be divided,
1972      *         and the remainder computed.
1973      * @param  mc the context to use.
1974      * @return a two element {@code BigDecimal} array: the quotient
1975      *         (the result of {@code divideToIntegralValue}) is the
1976      *         initial element and the remainder is the final element.
1977      * @throws ArithmeticException if {@code divisor==0}
1978      * @throws ArithmeticException if the result is inexact but the
1979      *         rounding mode is {@code UNNECESSARY}, or {@code mc.precision}
1980      *         {@literal >} 0 and the result of {@code this.divideToIntgralValue(divisor)} would
1981      *         require a precision of more than {@code mc.precision} digits.
1982      * @see    #divideToIntegralValue(java.math.BigDecimal, java.math.MathContext)
1983      * @see    #remainder(java.math.BigDecimal, java.math.MathContext)
1984      * @since  1.5
1985      */
1986     public BigDecimal[] divideAndRemainder(BigDecimal divisor, MathContext mc) {
1987         if (mc.precision == 0)
1988             return divideAndRemainder(divisor);
1989 
1990         BigDecimal[] result = new BigDecimal[2];
1991         BigDecimal lhs = this;
1992 
1993         result[0] = lhs.divideToIntegralValue(divisor, mc);
1994         result[1] = lhs.subtract(result[0].multiply(divisor));
1995         return result;
1996     }
1997 
1998     /**
1999      * Returns a {@code BigDecimal} whose value is
2000      * <code>(this<sup>n</sup>)</code>, The power is computed exactly, to
2001      * unlimited precision.
2002      *
2003      * <p>The parameter {@code n} must be in the range 0 through
2004      * 999999999, inclusive.  {@code ZERO.pow(0)} returns {@link
2005      * #ONE}.
2006      *
2007      * Note that future releases may expand the allowable exponent
2008      * range of this method.
2009      *
2010      * @param  n power to raise this {@code BigDecimal} to.
2011      * @return <code>this<sup>n</sup></code>
2012      * @throws ArithmeticException if {@code n} is out of range.
2013      * @since  1.5
2014      */
2015     public BigDecimal pow(int n) {
2016         if (n < 0 || n > 999999999)
2017             throw new ArithmeticException("Invalid operation");
2018         // No need to calculate pow(n) if result will over/underflow.
2019         // Don't attempt to support "supernormal" numbers.
2020         int newScale = checkScale((long)scale * n);
2021         return new BigDecimal(this.inflated().pow(n), newScale);
2022     }
2023 
2024 
2025     /**
2026      * Returns a {@code BigDecimal} whose value is
2027      * <code>(this<sup>n</sup>)</code>.  The current implementation uses
2028      * the core algorithm defined in ANSI standard X3.274-1996 with
2029      * rounding according to the context settings.  In general, the
2030      * returned numerical value is within two ulps of the exact
2031      * numerical value for the chosen precision.  Note that future
2032      * releases may use a different algorithm with a decreased
2033      * allowable error bound and increased allowable exponent range.
2034      *
2035      * <p>The X3.274-1996 algorithm is:
2036      *
2037      * <ul>
2038      * <li> An {@code ArithmeticException} exception is thrown if
2039      *  <ul>
2040      *    <li>{@code abs(n) > 999999999}
2041      *    <li>{@code mc.precision == 0} and {@code n < 0}
2042      *    <li>{@code mc.precision > 0} and {@code n} has more than
2043      *    {@code mc.precision} decimal digits
2044      *  </ul>
2045      *
2046      * <li> if {@code n} is zero, {@link #ONE} is returned even if
2047      * {@code this} is zero, otherwise
2048      * <ul>
2049      *   <li> if {@code n} is positive, the result is calculated via
2050      *   the repeated squaring technique into a single accumulator.
2051      *   The individual multiplications with the accumulator use the
2052      *   same math context settings as in {@code mc} except for a
2053      *   precision increased to {@code mc.precision + elength + 1}
2054      *   where {@code elength} is the number of decimal digits in
2055      *   {@code n}.
2056      *
2057      *   <li> if {@code n} is negative, the result is calculated as if
2058      *   {@code n} were positive; this value is then divided into one
2059      *   using the working precision specified above.
2060      *
2061      *   <li> The final value from either the positive or negative case
2062      *   is then rounded to the destination precision.
2063      *   </ul>
2064      * </ul>
2065      *
2066      * @param  n power to raise this {@code BigDecimal} to.
2067      * @param  mc the context to use.
2068      * @return <code>this<sup>n</sup></code> using the ANSI standard X3.274-1996
2069      *         algorithm
2070      * @throws ArithmeticException if the result is inexact but the
2071      *         rounding mode is {@code UNNECESSARY}, or {@code n} is out
2072      *         of range.
2073      * @since  1.5
2074      */
2075     public BigDecimal pow(int n, MathContext mc) {
2076         if (mc.precision == 0)
2077             return pow(n);
2078         if (n < -999999999 || n > 999999999)
2079             throw new ArithmeticException("Invalid operation");
2080         if (n == 0)
2081             return ONE;                      // x**0 == 1 in X3.274
2082         BigDecimal lhs = this;
2083         MathContext workmc = mc;           // working settings
2084         int mag = Math.abs(n);               // magnitude of n
2085         if (mc.precision > 0) {
2086             int elength = longDigitLength(mag); // length of n in digits
2087             if (elength > mc.precision)        // X3.274 rule
2088                 throw new ArithmeticException("Invalid operation");
2089             workmc = new MathContext(mc.precision + elength + 1,
2090                                       mc.roundingMode);
2091         }
2092         // ready to carry out power calculation...
2093         BigDecimal acc = ONE;           // accumulator
2094         boolean seenbit = false;        // set once we've seen a 1-bit
2095         for (int i=1;;i++) {            // for each bit [top bit ignored]
2096             mag += mag;                 // shift left 1 bit
2097             if (mag < 0) {              // top bit is set
2098                 seenbit = true;         // OK, we're off
2099                 acc = acc.multiply(lhs, workmc); // acc=acc*x
2100             }
2101             if (i == 31)
2102                 break;                  // that was the last bit
2103             if (seenbit)
2104                 acc=acc.multiply(acc, workmc);   // acc=acc*acc [square]
2105                 // else (!seenbit) no point in squaring ONE
2106         }
2107         // if negative n, calculate the reciprocal using working precision
2108         if (n < 0) // [hence mc.precision>0]
2109             acc=ONE.divide(acc, workmc);
2110         // round to final precision and strip zeros
2111         return doRound(acc, mc);
2112     }
2113 
2114     /**
2115      * Returns a {@code BigDecimal} whose value is the absolute value
2116      * of this {@code BigDecimal}, and whose scale is
2117      * {@code this.scale()}.
2118      *
2119      * @return {@code abs(this)}
2120      */
2121     public BigDecimal abs() {
2122         return (signum() < 0 ? negate() : this);
2123     }
2124 
2125     /**
2126      * Returns a {@code BigDecimal} whose value is the absolute value
2127      * of this {@code BigDecimal}, with rounding according to the
2128      * context settings.
2129      *
2130      * @param mc the context to use.
2131      * @return {@code abs(this)}, rounded as necessary.
2132      * @throws ArithmeticException if the result is inexact but the
2133      *         rounding mode is {@code UNNECESSARY}.
2134      * @since 1.5
2135      */
2136     public BigDecimal abs(MathContext mc) {
2137         return (signum() < 0 ? negate(mc) : plus(mc));
2138     }
2139 
2140     /**
2141      * Returns a {@code BigDecimal} whose value is {@code (-this)},
2142      * and whose scale is {@code this.scale()}.
2143      *
2144      * @return {@code -this}.
2145      */
2146     public BigDecimal negate() {
2147         if (intCompact == INFLATED) {
2148             return new BigDecimal(intVal.negate(), INFLATED, scale, precision);
2149         } else {
2150             return valueOf(-intCompact, scale, precision);
2151         }
2152     }
2153 
2154     /**
2155      * Returns a {@code BigDecimal} whose value is {@code (-this)},
2156      * with rounding according to the context settings.
2157      *
2158      * @param mc the context to use.
2159      * @return {@code -this}, rounded as necessary.
2160      * @throws ArithmeticException if the result is inexact but the
2161      *         rounding mode is {@code UNNECESSARY}.
2162      * @since  1.5
2163      */
2164     public BigDecimal negate(MathContext mc) {
2165         return negate().plus(mc);
2166     }
2167 
2168     /**
2169      * Returns a {@code BigDecimal} whose value is {@code (+this)}, and whose
2170      * scale is {@code this.scale()}.
2171      *
2172      * <p>This method, which simply returns this {@code BigDecimal}
2173      * is included for symmetry with the unary minus method {@link
2174      * #negate()}.
2175      *
2176      * @return {@code this}.
2177      * @see #negate()
2178      * @since  1.5
2179      */
2180     public BigDecimal plus() {
2181         return this;
2182     }
2183 
2184     /**
2185      * Returns a {@code BigDecimal} whose value is {@code (+this)},
2186      * with rounding according to the context settings.
2187      *
2188      * <p>The effect of this method is identical to that of the {@link
2189      * #round(MathContext)} method.
2190      *
2191      * @param mc the context to use.
2192      * @return {@code this}, rounded as necessary.  A zero result will
2193      *         have a scale of 0.
2194      * @throws ArithmeticException if the result is inexact but the
2195      *         rounding mode is {@code UNNECESSARY}.
2196      * @see    #round(MathContext)
2197      * @since  1.5
2198      */
2199     public BigDecimal plus(MathContext mc) {
2200         if (mc.precision == 0)                 // no rounding please
2201             return this;
2202         return doRound(this, mc);
2203     }
2204 
2205     /**
2206      * Returns the signum function of this {@code BigDecimal}.
2207      *
2208      * @return -1, 0, or 1 as the value of this {@code BigDecimal}
2209      *         is negative, zero, or positive.
2210      */
2211     public int signum() {
2212         return (intCompact != INFLATED)?
2213             Long.signum(intCompact):
2214             intVal.signum();
2215     }
2216 
2217     /**
2218      * Returns the <i>scale</i> of this {@code BigDecimal}.  If zero
2219      * or positive, the scale is the number of digits to the right of
2220      * the decimal point.  If negative, the unscaled value of the
2221      * number is multiplied by ten to the power of the negation of the
2222      * scale.  For example, a scale of {@code -3} means the unscaled
2223      * value is multiplied by 1000.
2224      *
2225      * @return the scale of this {@code BigDecimal}.
2226      */
2227     public int scale() {
2228         return scale;
2229     }
2230 
2231     /**
2232      * Returns the <i>precision</i> of this {@code BigDecimal}.  (The
2233      * precision is the number of digits in the unscaled value.)
2234      *
2235      * <p>The precision of a zero value is 1.
2236      *
2237      * @return the precision of this {@code BigDecimal}.
2238      * @since  1.5
2239      */
2240     public int precision() {
2241         int result = precision;
2242         if (result == 0) {
2243             long s = intCompact;
2244             if (s != INFLATED)
2245                 result = longDigitLength(s);
2246             else
2247                 result = bigDigitLength(intVal);
2248             precision = result;
2249         }
2250         return result;
2251     }
2252 
2253 
2254     /**
2255      * Returns a {@code BigInteger} whose value is the <i>unscaled
2256      * value</i> of this {@code BigDecimal}.  (Computes <code>(this *
2257      * 10<sup>this.scale()</sup>)</code>.)
2258      *
2259      * @return the unscaled value of this {@code BigDecimal}.
2260      * @since  1.2
2261      */
2262     public BigInteger unscaledValue() {
2263         return this.inflated();
2264     }
2265 
2266     // Rounding Modes
2267 
2268     /**
2269      * Rounding mode to round away from zero.  Always increments the
2270      * digit prior to a nonzero discarded fraction.  Note that this rounding
2271      * mode never decreases the magnitude of the calculated value.
2272      *
2273      * @deprecated Use {@link RoundingMode#UP} instead.
2274      */
2275     @Deprecated(since="9")
2276     public static final int ROUND_UP =           0;
2277 
2278     /**
2279      * Rounding mode to round towards zero.  Never increments the digit
2280      * prior to a discarded fraction (i.e., truncates).  Note that this
2281      * rounding mode never increases the magnitude of the calculated value.
2282      *
2283      * @deprecated Use {@link RoundingMode#DOWN} instead.
2284      */
2285     @Deprecated(since="9")
2286     public static final int ROUND_DOWN =         1;
2287 
2288     /**
2289      * Rounding mode to round towards positive infinity.  If the
2290      * {@code BigDecimal} is positive, behaves as for
2291      * {@code ROUND_UP}; if negative, behaves as for
2292      * {@code ROUND_DOWN}.  Note that this rounding mode never
2293      * decreases the calculated value.
2294      *
2295      * @deprecated Use {@link RoundingMode#CEILING} instead.
2296      */
2297     @Deprecated(since="9")
2298     public static final int ROUND_CEILING =      2;
2299 
2300     /**
2301      * Rounding mode to round towards negative infinity.  If the
2302      * {@code BigDecimal} is positive, behave as for
2303      * {@code ROUND_DOWN}; if negative, behave as for
2304      * {@code ROUND_UP}.  Note that this rounding mode never
2305      * increases the calculated value.
2306      *
2307      * @deprecated Use {@link RoundingMode#FLOOR} instead.
2308      */
2309     @Deprecated(since="9")
2310     public static final int ROUND_FLOOR =        3;
2311 
2312     /**
2313      * Rounding mode to round towards {@literal "nearest neighbor"}
2314      * unless both neighbors are equidistant, in which case round up.
2315      * Behaves as for {@code ROUND_UP} if the discarded fraction is
2316      * &ge; 0.5; otherwise, behaves as for {@code ROUND_DOWN}.  Note
2317      * that this is the rounding mode that most of us were taught in
2318      * grade school.
2319      *
2320      * @deprecated Use {@link RoundingMode#HALF_UP} instead.
2321      */
2322     @Deprecated(since="9")
2323     public static final int ROUND_HALF_UP =      4;
2324 
2325     /**
2326      * Rounding mode to round towards {@literal "nearest neighbor"}
2327      * unless both neighbors are equidistant, in which case round
2328      * down.  Behaves as for {@code ROUND_UP} if the discarded
2329      * fraction is {@literal >} 0.5; otherwise, behaves as for
2330      * {@code ROUND_DOWN}.
2331      *
2332      * @deprecated Use {@link RoundingMode#HALF_DOWN} instead.
2333      */
2334     @Deprecated(since="9")
2335     public static final int ROUND_HALF_DOWN =    5;
2336 
2337     /**
2338      * Rounding mode to round towards the {@literal "nearest neighbor"}
2339      * unless both neighbors are equidistant, in which case, round
2340      * towards the even neighbor.  Behaves as for
2341      * {@code ROUND_HALF_UP} if the digit to the left of the
2342      * discarded fraction is odd; behaves as for
2343      * {@code ROUND_HALF_DOWN} if it's even.  Note that this is the
2344      * rounding mode that minimizes cumulative error when applied
2345      * repeatedly over a sequence of calculations.
2346      *
2347      * @deprecated Use {@link RoundingMode#HALF_EVEN} instead.
2348      */
2349     @Deprecated(since="9")
2350     public static final int ROUND_HALF_EVEN =    6;
2351 
2352     /**
2353      * Rounding mode to assert that the requested operation has an exact
2354      * result, hence no rounding is necessary.  If this rounding mode is
2355      * specified on an operation that yields an inexact result, an
2356      * {@code ArithmeticException} is thrown.
2357      *
2358      * @deprecated Use {@link RoundingMode#UNNECESSARY} instead.
2359      */
2360     @Deprecated(since="9")
2361     public static final int ROUND_UNNECESSARY =  7;
2362 
2363 
2364     // Scaling/Rounding Operations
2365 
2366     /**
2367      * Returns a {@code BigDecimal} rounded according to the
2368      * {@code MathContext} settings.  If the precision setting is 0 then
2369      * no rounding takes place.
2370      *
2371      * <p>The effect of this method is identical to that of the
2372      * {@link #plus(MathContext)} method.
2373      *
2374      * @param mc the context to use.
2375      * @return a {@code BigDecimal} rounded according to the
2376      *         {@code MathContext} settings.
2377      * @throws ArithmeticException if the rounding mode is
2378      *         {@code UNNECESSARY} and the
2379      *         {@code BigDecimal}  operation would require rounding.
2380      * @see    #plus(MathContext)
2381      * @since  1.5
2382      */
2383     public BigDecimal round(MathContext mc) {
2384         return plus(mc);
2385     }
2386 
2387     /**
2388      * Returns a {@code BigDecimal} whose scale is the specified
2389      * value, and whose unscaled value is determined by multiplying or
2390      * dividing this {@code BigDecimal}'s unscaled value by the
2391      * appropriate power of ten to maintain its overall value.  If the
2392      * scale is reduced by the operation, the unscaled value must be
2393      * divided (rather than multiplied), and the value may be changed;
2394      * in this case, the specified rounding mode is applied to the
2395      * division.
2396      *
2397      * <p>Note that since BigDecimal objects are immutable, calls of
2398      * this method do <i>not</i> result in the original object being
2399      * modified, contrary to the usual convention of having methods
2400      * named <code>set<i>X</i></code> mutate field <i>{@code X}</i>.
2401      * Instead, {@code setScale} returns an object with the proper
2402      * scale; the returned object may or may not be newly allocated.
2403      *
2404      * @param  newScale scale of the {@code BigDecimal} value to be returned.
2405      * @param  roundingMode The rounding mode to apply.
2406      * @return a {@code BigDecimal} whose scale is the specified value,
2407      *         and whose unscaled value is determined by multiplying or
2408      *         dividing this {@code BigDecimal}'s unscaled value by the
2409      *         appropriate power of ten to maintain its overall value.
2410      * @throws ArithmeticException if {@code roundingMode==UNNECESSARY}
2411      *         and the specified scaling operation would require
2412      *         rounding.
2413      * @see    RoundingMode
2414      * @since  1.5
2415      */
2416     public BigDecimal setScale(int newScale, RoundingMode roundingMode) {
2417         return setScale(newScale, roundingMode.oldMode);
2418     }
2419 
2420     /**
2421      * Returns a {@code BigDecimal} whose scale is the specified
2422      * value, and whose unscaled value is determined by multiplying or
2423      * dividing this {@code BigDecimal}'s unscaled value by the
2424      * appropriate power of ten to maintain its overall value.  If the
2425      * scale is reduced by the operation, the unscaled value must be
2426      * divided (rather than multiplied), and the value may be changed;
2427      * in this case, the specified rounding mode is applied to the
2428      * division.
2429      *
2430      * <p>Note that since BigDecimal objects are immutable, calls of
2431      * this method do <i>not</i> result in the original object being
2432      * modified, contrary to the usual convention of having methods
2433      * named <code>set<i>X</i></code> mutate field <i>{@code X}</i>.
2434      * Instead, {@code setScale} returns an object with the proper
2435      * scale; the returned object may or may not be newly allocated.
2436      *
2437      * @deprecated The method {@link #setScale(int, RoundingMode)} should
2438      * be used in preference to this legacy method.
2439      *
2440      * @param  newScale scale of the {@code BigDecimal} value to be returned.
2441      * @param  roundingMode The rounding mode to apply.
2442      * @return a {@code BigDecimal} whose scale is the specified value,
2443      *         and whose unscaled value is determined by multiplying or
2444      *         dividing this {@code BigDecimal}'s unscaled value by the
2445      *         appropriate power of ten to maintain its overall value.
2446      * @throws ArithmeticException if {@code roundingMode==ROUND_UNNECESSARY}
2447      *         and the specified scaling operation would require
2448      *         rounding.
2449      * @throws IllegalArgumentException if {@code roundingMode} does not
2450      *         represent a valid rounding mode.
2451      * @see    #ROUND_UP
2452      * @see    #ROUND_DOWN
2453      * @see    #ROUND_CEILING
2454      * @see    #ROUND_FLOOR
2455      * @see    #ROUND_HALF_UP
2456      * @see    #ROUND_HALF_DOWN
2457      * @see    #ROUND_HALF_EVEN
2458      * @see    #ROUND_UNNECESSARY
2459      */
2460     @Deprecated(since="9")
2461     public BigDecimal setScale(int newScale, int roundingMode) {
2462         if (roundingMode < ROUND_UP || roundingMode > ROUND_UNNECESSARY)
2463             throw new IllegalArgumentException("Invalid rounding mode");
2464 
2465         int oldScale = this.scale;
2466         if (newScale == oldScale)        // easy case
2467             return this;
2468         if (this.signum() == 0)            // zero can have any scale
2469             return zeroValueOf(newScale);
2470         if(this.intCompact!=INFLATED) {
2471             long rs = this.intCompact;
2472             if (newScale > oldScale) {
2473                 int raise = checkScale((long) newScale - oldScale);
2474                 if ((rs = longMultiplyPowerTen(rs, raise)) != INFLATED) {
2475                     return valueOf(rs,newScale);
2476                 }
2477                 BigInteger rb = bigMultiplyPowerTen(raise);
2478                 return new BigDecimal(rb, INFLATED, newScale, (precision > 0) ? precision + raise : 0);
2479             } else {
2480                 // newScale < oldScale -- drop some digits
2481                 // Can't predict the precision due to the effect of rounding.
2482                 int drop = checkScale((long) oldScale - newScale);
2483                 if (drop < LONG_TEN_POWERS_TABLE.length) {
2484                     return divideAndRound(rs, LONG_TEN_POWERS_TABLE[drop], newScale, roundingMode, newScale);
2485                 } else {
2486                     return divideAndRound(this.inflated(), bigTenToThe(drop), newScale, roundingMode, newScale);
2487                 }
2488             }
2489         } else {
2490             if (newScale > oldScale) {
2491                 int raise = checkScale((long) newScale - oldScale);
2492                 BigInteger rb = bigMultiplyPowerTen(this.intVal,raise);
2493                 return new BigDecimal(rb, INFLATED, newScale, (precision > 0) ? precision + raise : 0);
2494             } else {
2495                 // newScale < oldScale -- drop some digits
2496                 // Can't predict the precision due to the effect of rounding.
2497                 int drop = checkScale((long) oldScale - newScale);
2498                 if (drop < LONG_TEN_POWERS_TABLE.length)
2499                     return divideAndRound(this.intVal, LONG_TEN_POWERS_TABLE[drop], newScale, roundingMode,
2500                                           newScale);
2501                 else
2502                     return divideAndRound(this.intVal,  bigTenToThe(drop), newScale, roundingMode, newScale);
2503             }
2504         }
2505     }
2506 
2507     /**
2508      * Returns a {@code BigDecimal} whose scale is the specified
2509      * value, and whose value is numerically equal to this
2510      * {@code BigDecimal}'s.  Throws an {@code ArithmeticException}
2511      * if this is not possible.
2512      *
2513      * <p>This call is typically used to increase the scale, in which
2514      * case it is guaranteed that there exists a {@code BigDecimal}
2515      * of the specified scale and the correct value.  The call can
2516      * also be used to reduce the scale if the caller knows that the
2517      * {@code BigDecimal} has sufficiently many zeros at the end of
2518      * its fractional part (i.e., factors of ten in its integer value)
2519      * to allow for the rescaling without changing its value.
2520      *
2521      * <p>This method returns the same result as the two-argument
2522      * versions of {@code setScale}, but saves the caller the trouble
2523      * of specifying a rounding mode in cases where it is irrelevant.
2524      *
2525      * <p>Note that since {@code BigDecimal} objects are immutable,
2526      * calls of this method do <i>not</i> result in the original
2527      * object being modified, contrary to the usual convention of
2528      * having methods named <code>set<i>X</i></code> mutate field
2529      * <i>{@code X}</i>.  Instead, {@code setScale} returns an
2530      * object with the proper scale; the returned object may or may
2531      * not be newly allocated.
2532      *
2533      * @param  newScale scale of the {@code BigDecimal} value to be returned.
2534      * @return a {@code BigDecimal} whose scale is the specified value, and
2535      *         whose unscaled value is determined by multiplying or dividing
2536      *         this {@code BigDecimal}'s unscaled value by the appropriate
2537      *         power of ten to maintain its overall value.
2538      * @throws ArithmeticException if the specified scaling operation would
2539      *         require rounding.
2540      * @see    #setScale(int, int)
2541      * @see    #setScale(int, RoundingMode)
2542      */
2543     public BigDecimal setScale(int newScale) {
2544         return setScale(newScale, ROUND_UNNECESSARY);
2545     }
2546 
2547     // Decimal Point Motion Operations
2548 
2549     /**
2550      * Returns a {@code BigDecimal} which is equivalent to this one
2551      * with the decimal point moved {@code n} places to the left.  If
2552      * {@code n} is non-negative, the call merely adds {@code n} to
2553      * the scale.  If {@code n} is negative, the call is equivalent
2554      * to {@code movePointRight(-n)}.  The {@code BigDecimal}
2555      * returned by this call has value <code>(this &times;
2556      * 10<sup>-n</sup>)</code> and scale {@code max(this.scale()+n,
2557      * 0)}.
2558      *
2559      * @param  n number of places to move the decimal point to the left.
2560      * @return a {@code BigDecimal} which is equivalent to this one with the
2561      *         decimal point moved {@code n} places to the left.
2562      * @throws ArithmeticException if scale overflows.
2563      */
2564     public BigDecimal movePointLeft(int n) {
2565         // Cannot use movePointRight(-n) in case of n==Integer.MIN_VALUE
2566         int newScale = checkScale((long)scale + n);
2567         BigDecimal num = new BigDecimal(intVal, intCompact, newScale, 0);
2568         return num.scale < 0 ? num.setScale(0, ROUND_UNNECESSARY) : num;
2569     }
2570 
2571     /**
2572      * Returns a {@code BigDecimal} which is equivalent to this one
2573      * with the decimal point moved {@code n} places to the right.
2574      * If {@code n} is non-negative, the call merely subtracts
2575      * {@code n} from the scale.  If {@code n} is negative, the call
2576      * is equivalent to {@code movePointLeft(-n)}.  The
2577      * {@code BigDecimal} returned by this call has value <code>(this
2578      * &times; 10<sup>n</sup>)</code> and scale {@code max(this.scale()-n,
2579      * 0)}.
2580      *
2581      * @param  n number of places to move the decimal point to the right.
2582      * @return a {@code BigDecimal} which is equivalent to this one
2583      *         with the decimal point moved {@code n} places to the right.
2584      * @throws ArithmeticException if scale overflows.
2585      */
2586     public BigDecimal movePointRight(int n) {
2587         // Cannot use movePointLeft(-n) in case of n==Integer.MIN_VALUE
2588         int newScale = checkScale((long)scale - n);
2589         BigDecimal num = new BigDecimal(intVal, intCompact, newScale, 0);
2590         return num.scale < 0 ? num.setScale(0, ROUND_UNNECESSARY) : num;
2591     }
2592 
2593     /**
2594      * Returns a BigDecimal whose numerical value is equal to
2595      * ({@code this} * 10<sup>n</sup>).  The scale of
2596      * the result is {@code (this.scale() - n)}.
2597      *
2598      * @param n the exponent power of ten to scale by
2599      * @return a BigDecimal whose numerical value is equal to
2600      * ({@code this} * 10<sup>n</sup>)
2601      * @throws ArithmeticException if the scale would be
2602      *         outside the range of a 32-bit integer.
2603      *
2604      * @since 1.5
2605      */
2606     public BigDecimal scaleByPowerOfTen(int n) {
2607         return new BigDecimal(intVal, intCompact,
2608                               checkScale((long)scale - n), precision);
2609     }
2610 
2611     /**
2612      * Returns a {@code BigDecimal} which is numerically equal to
2613      * this one but with any trailing zeros removed from the
2614      * representation.  For example, stripping the trailing zeros from
2615      * the {@code BigDecimal} value {@code 600.0}, which has
2616      * [{@code BigInteger}, {@code scale}] components equals to
2617      * [6000, 1], yields {@code 6E2} with [{@code BigInteger},
2618      * {@code scale}] components equals to [6, -2].  If
2619      * this BigDecimal is numerically equal to zero, then
2620      * {@code BigDecimal.ZERO} is returned.
2621      *
2622      * @return a numerically equal {@code BigDecimal} with any
2623      * trailing zeros removed.
2624      * @since 1.5
2625      */
2626     public BigDecimal stripTrailingZeros() {
2627         if (intCompact == 0 || (intVal != null && intVal.signum() == 0)) {
2628             return BigDecimal.ZERO;
2629         } else if (intCompact != INFLATED) {
2630             return createAndStripZerosToMatchScale(intCompact, scale, Long.MIN_VALUE);
2631         } else {
2632             return createAndStripZerosToMatchScale(intVal, scale, Long.MIN_VALUE);
2633         }
2634     }
2635 
2636     // Comparison Operations
2637 
2638     /**
2639      * Compares this {@code BigDecimal} with the specified
2640      * {@code BigDecimal}.  Two {@code BigDecimal} objects that are
2641      * equal in value but have a different scale (like 2.0 and 2.00)
2642      * are considered equal by this method.  This method is provided
2643      * in preference to individual methods for each of the six boolean
2644      * comparison operators ({@literal <}, ==,
2645      * {@literal >}, {@literal >=}, !=, {@literal <=}).  The
2646      * suggested idiom for performing these comparisons is:
2647      * {@code (x.compareTo(y)} &lt;<i>op</i>&gt; {@code 0)}, where
2648      * &lt;<i>op</i>&gt; is one of the six comparison operators.
2649      *
2650      * @param  val {@code BigDecimal} to which this {@code BigDecimal} is
2651      *         to be compared.
2652      * @return -1, 0, or 1 as this {@code BigDecimal} is numerically
2653      *          less than, equal to, or greater than {@code val}.
2654      */
2655     @Override
2656     public int compareTo(BigDecimal val) {
2657         // Quick path for equal scale and non-inflated case.
2658         if (scale == val.scale) {
2659             long xs = intCompact;
2660             long ys = val.intCompact;
2661             if (xs != INFLATED && ys != INFLATED)
2662                 return xs != ys ? ((xs > ys) ? 1 : -1) : 0;
2663         }
2664         int xsign = this.signum();
2665         int ysign = val.signum();
2666         if (xsign != ysign)
2667             return (xsign > ysign) ? 1 : -1;
2668         if (xsign == 0)
2669             return 0;
2670         int cmp = compareMagnitude(val);
2671         return (xsign > 0) ? cmp : -cmp;
2672     }
2673 
2674     /**
2675      * Version of compareTo that ignores sign.
2676      */
2677     private int compareMagnitude(BigDecimal val) {
2678         // Match scales, avoid unnecessary inflation
2679         long ys = val.intCompact;
2680         long xs = this.intCompact;
2681         if (xs == 0)
2682             return (ys == 0) ? 0 : -1;
2683         if (ys == 0)
2684             return 1;
2685 
2686         long sdiff = (long)this.scale - val.scale;
2687         if (sdiff != 0) {
2688             // Avoid matching scales if the (adjusted) exponents differ
2689             long xae = (long)this.precision() - this.scale;   // [-1]
2690             long yae = (long)val.precision() - val.scale;     // [-1]
2691             if (xae < yae)
2692                 return -1;
2693             if (xae > yae)
2694                 return 1;
2695             if (sdiff < 0) {
2696                 // The cases sdiff <= Integer.MIN_VALUE intentionally fall through.
2697                 if ( sdiff > Integer.MIN_VALUE &&
2698                       (xs == INFLATED ||
2699                       (xs = longMultiplyPowerTen(xs, (int)-sdiff)) == INFLATED) &&
2700                      ys == INFLATED) {
2701                     BigInteger rb = bigMultiplyPowerTen((int)-sdiff);
2702                     return rb.compareMagnitude(val.intVal);
2703                 }
2704             } else { // sdiff > 0
2705                 // The cases sdiff > Integer.MAX_VALUE intentionally fall through.
2706                 if ( sdiff <= Integer.MAX_VALUE &&
2707                       (ys == INFLATED ||
2708                       (ys = longMultiplyPowerTen(ys, (int)sdiff)) == INFLATED) &&
2709                      xs == INFLATED) {
2710                     BigInteger rb = val.bigMultiplyPowerTen((int)sdiff);
2711                     return this.intVal.compareMagnitude(rb);
2712                 }
2713             }
2714         }
2715         if (xs != INFLATED)
2716             return (ys != INFLATED) ? longCompareMagnitude(xs, ys) : -1;
2717         else if (ys != INFLATED)
2718             return 1;
2719         else
2720             return this.intVal.compareMagnitude(val.intVal);
2721     }
2722 
2723     /**
2724      * Compares this {@code BigDecimal} with the specified
2725      * {@code Object} for equality.  Unlike {@link
2726      * #compareTo(BigDecimal) compareTo}, this method considers two
2727      * {@code BigDecimal} objects equal only if they are equal in
2728      * value and scale (thus 2.0 is not equal to 2.00 when compared by
2729      * this method).
2730      *
2731      * @param  x {@code Object} to which this {@code BigDecimal} is
2732      *         to be compared.
2733      * @return {@code true} if and only if the specified {@code Object} is a
2734      *         {@code BigDecimal} whose value and scale are equal to this
2735      *         {@code BigDecimal}'s.
2736      * @see    #compareTo(java.math.BigDecimal)
2737      * @see    #hashCode
2738      */
2739     @Override
2740     public boolean equals(Object x) {
2741         if (!(x instanceof BigDecimal))
2742             return false;
2743         BigDecimal xDec = (BigDecimal) x;
2744         if (x == this)
2745             return true;
2746         if (scale != xDec.scale)
2747             return false;
2748         long s = this.intCompact;
2749         long xs = xDec.intCompact;
2750         if (s != INFLATED) {
2751             if (xs == INFLATED)
2752                 xs = compactValFor(xDec.intVal);
2753             return xs == s;
2754         } else if (xs != INFLATED)
2755             return xs == compactValFor(this.intVal);
2756 
2757         return this.inflated().equals(xDec.inflated());
2758     }
2759 
2760     /**
2761      * Returns the minimum of this {@code BigDecimal} and
2762      * {@code val}.
2763      *
2764      * @param  val value with which the minimum is to be computed.
2765      * @return the {@code BigDecimal} whose value is the lesser of this
2766      *         {@code BigDecimal} and {@code val}.  If they are equal,
2767      *         as defined by the {@link #compareTo(BigDecimal) compareTo}
2768      *         method, {@code this} is returned.
2769      * @see    #compareTo(java.math.BigDecimal)
2770      */
2771     public BigDecimal min(BigDecimal val) {
2772         return (compareTo(val) <= 0 ? this : val);
2773     }
2774 
2775     /**
2776      * Returns the maximum of this {@code BigDecimal} and {@code val}.
2777      *
2778      * @param  val value with which the maximum is to be computed.
2779      * @return the {@code BigDecimal} whose value is the greater of this
2780      *         {@code BigDecimal} and {@code val}.  If they are equal,
2781      *         as defined by the {@link #compareTo(BigDecimal) compareTo}
2782      *         method, {@code this} is returned.
2783      * @see    #compareTo(java.math.BigDecimal)
2784      */
2785     public BigDecimal max(BigDecimal val) {
2786         return (compareTo(val) >= 0 ? this : val);
2787     }
2788 
2789     // Hash Function
2790 
2791     /**
2792      * Returns the hash code for this {@code BigDecimal}.  Note that
2793      * two {@code BigDecimal} objects that are numerically equal but
2794      * differ in scale (like 2.0 and 2.00) will generally <i>not</i>
2795      * have the same hash code.
2796      *
2797      * @return hash code for this {@code BigDecimal}.
2798      * @see #equals(Object)
2799      */
2800     @Override
2801     public int hashCode() {
2802         if (intCompact != INFLATED) {
2803             long val2 = (intCompact < 0)? -intCompact : intCompact;
2804             int temp = (int)( ((int)(val2 >>> 32)) * 31  +
2805                               (val2 & LONG_MASK));
2806             return 31*((intCompact < 0) ?-temp:temp) + scale;
2807         } else
2808             return 31*intVal.hashCode() + scale;
2809     }
2810 
2811     // Format Converters
2812 
2813     /**
2814      * Returns the string representation of this {@code BigDecimal},
2815      * using scientific notation if an exponent is needed.
2816      *
2817      * <p>A standard canonical string form of the {@code BigDecimal}
2818      * is created as though by the following steps: first, the
2819      * absolute value of the unscaled value of the {@code BigDecimal}
2820      * is converted to a string in base ten using the characters
2821      * {@code '0'} through {@code '9'} with no leading zeros (except
2822      * if its value is zero, in which case a single {@code '0'}
2823      * character is used).
2824      *
2825      * <p>Next, an <i>adjusted exponent</i> is calculated; this is the
2826      * negated scale, plus the number of characters in the converted
2827      * unscaled value, less one.  That is,
2828      * {@code -scale+(ulength-1)}, where {@code ulength} is the
2829      * length of the absolute value of the unscaled value in decimal
2830      * digits (its <i>precision</i>).
2831      *
2832      * <p>If the scale is greater than or equal to zero and the
2833      * adjusted exponent is greater than or equal to {@code -6}, the
2834      * number will be converted to a character form without using
2835      * exponential notation.  In this case, if the scale is zero then
2836      * no decimal point is added and if the scale is positive a
2837      * decimal point will be inserted with the scale specifying the
2838      * number of characters to the right of the decimal point.
2839      * {@code '0'} characters are added to the left of the converted
2840      * unscaled value as necessary.  If no character precedes the
2841      * decimal point after this insertion then a conventional
2842      * {@code '0'} character is prefixed.
2843      *
2844      * <p>Otherwise (that is, if the scale is negative, or the
2845      * adjusted exponent is less than {@code -6}), the number will be
2846      * converted to a character form using exponential notation.  In
2847      * this case, if the converted {@code BigInteger} has more than
2848      * one digit a decimal point is inserted after the first digit.
2849      * An exponent in character form is then suffixed to the converted
2850      * unscaled value (perhaps with inserted decimal point); this
2851      * comprises the letter {@code 'E'} followed immediately by the
2852      * adjusted exponent converted to a character form.  The latter is
2853      * in base ten, using the characters {@code '0'} through
2854      * {@code '9'} with no leading zeros, and is always prefixed by a
2855      * sign character {@code '-'} (<code>'\u002D'</code>) if the
2856      * adjusted exponent is negative, {@code '+'}
2857      * (<code>'\u002B'</code>) otherwise).
2858      *
2859      * <p>Finally, the entire string is prefixed by a minus sign
2860      * character {@code '-'} (<code>'\u002D'</code>) if the unscaled
2861      * value is less than zero.  No sign character is prefixed if the
2862      * unscaled value is zero or positive.
2863      *
2864      * <p><b>Examples:</b>
2865      * <p>For each representation [<i>unscaled value</i>, <i>scale</i>]
2866      * on the left, the resulting string is shown on the right.
2867      * <pre>
2868      * [123,0]      "123"
2869      * [-123,0]     "-123"
2870      * [123,-1]     "1.23E+3"
2871      * [123,-3]     "1.23E+5"
2872      * [123,1]      "12.3"
2873      * [123,5]      "0.00123"
2874      * [123,10]     "1.23E-8"
2875      * [-123,12]    "-1.23E-10"
2876      * </pre>
2877      *
2878      * <b>Notes:</b>
2879      * <ol>
2880      *
2881      * <li>There is a one-to-one mapping between the distinguishable
2882      * {@code BigDecimal} values and the result of this conversion.
2883      * That is, every distinguishable {@code BigDecimal} value
2884      * (unscaled value and scale) has a unique string representation
2885      * as a result of using {@code toString}.  If that string
2886      * representation is converted back to a {@code BigDecimal} using
2887      * the {@link #BigDecimal(String)} constructor, then the original
2888      * value will be recovered.
2889      *
2890      * <li>The string produced for a given number is always the same;
2891      * it is not affected by locale.  This means that it can be used
2892      * as a canonical string representation for exchanging decimal
2893      * data, or as a key for a Hashtable, etc.  Locale-sensitive
2894      * number formatting and parsing is handled by the {@link
2895      * java.text.NumberFormat} class and its subclasses.
2896      *
2897      * <li>The {@link #toEngineeringString} method may be used for
2898      * presenting numbers with exponents in engineering notation, and the
2899      * {@link #setScale(int,RoundingMode) setScale} method may be used for
2900      * rounding a {@code BigDecimal} so it has a known number of digits after
2901      * the decimal point.
2902      *
2903      * <li>The digit-to-character mapping provided by
2904      * {@code Character.forDigit} is used.
2905      *
2906      * </ol>
2907      *
2908      * @return string representation of this {@code BigDecimal}.
2909      * @see    Character#forDigit
2910      * @see    #BigDecimal(java.lang.String)
2911      */
2912     @Override
2913     public String toString() {
2914         String sc = stringCache;
2915         if (sc == null) {
2916             stringCache = sc = layoutChars(true);
2917         }
2918         return sc;
2919     }
2920 
2921     /**
2922      * Returns a string representation of this {@code BigDecimal},
2923      * using engineering notation if an exponent is needed.
2924      *
2925      * <p>Returns a string that represents the {@code BigDecimal} as
2926      * described in the {@link #toString()} method, except that if
2927      * exponential notation is used, the power of ten is adjusted to
2928      * be a multiple of three (engineering notation) such that the
2929      * integer part of nonzero values will be in the range 1 through
2930      * 999.  If exponential notation is used for zero values, a
2931      * decimal point and one or two fractional zero digits are used so
2932      * that the scale of the zero value is preserved.  Note that
2933      * unlike the output of {@link #toString()}, the output of this
2934      * method is <em>not</em> guaranteed to recover the same [integer,
2935      * scale] pair of this {@code BigDecimal} if the output string is
2936      * converting back to a {@code BigDecimal} using the {@linkplain
2937      * #BigDecimal(String) string constructor}.  The result of this method meets
2938      * the weaker constraint of always producing a numerically equal
2939      * result from applying the string constructor to the method's output.
2940      *
2941      * @return string representation of this {@code BigDecimal}, using
2942      *         engineering notation if an exponent is needed.
2943      * @since  1.5
2944      */
2945     public String toEngineeringString() {
2946         return layoutChars(false);
2947     }
2948 
2949     /**
2950      * Returns a string representation of this {@code BigDecimal}
2951      * without an exponent field.  For values with a positive scale,
2952      * the number of digits to the right of the decimal point is used
2953      * to indicate scale.  For values with a zero or negative scale,
2954      * the resulting string is generated as if the value were
2955      * converted to a numerically equal value with zero scale and as
2956      * if all the trailing zeros of the zero scale value were present
2957      * in the result.
2958      *
2959      * The entire string is prefixed by a minus sign character '-'
2960      * (<code>'\u002D'</code>) if the unscaled value is less than
2961      * zero. No sign character is prefixed if the unscaled value is
2962      * zero or positive.
2963      *
2964      * Note that if the result of this method is passed to the
2965      * {@linkplain #BigDecimal(String) string constructor}, only the
2966      * numerical value of this {@code BigDecimal} will necessarily be
2967      * recovered; the representation of the new {@code BigDecimal}
2968      * may have a different scale.  In particular, if this
2969      * {@code BigDecimal} has a negative scale, the string resulting
2970      * from this method will have a scale of zero when processed by
2971      * the string constructor.
2972      *
2973      * (This method behaves analogously to the {@code toString}
2974      * method in 1.4 and earlier releases.)
2975      *
2976      * @return a string representation of this {@code BigDecimal}
2977      * without an exponent field.
2978      * @since 1.5
2979      * @see #toString()
2980      * @see #toEngineeringString()
2981      */
2982     public String toPlainString() {
2983         if(scale==0) {
2984             if(intCompact!=INFLATED) {
2985                 return Long.toString(intCompact);
2986             } else {
2987                 return intVal.toString();
2988             }
2989         }
2990         if(this.scale<0) { // No decimal point
2991             if(signum()==0) {
2992                 return "0";
2993             }
2994             int trailingZeros = checkScaleNonZero((-(long)scale));
2995             StringBuilder buf;
2996             if(intCompact!=INFLATED) {
2997                 buf = new StringBuilder(20+trailingZeros);
2998                 buf.append(intCompact);
2999             } else {
3000                 String str = intVal.toString();
3001                 buf = new StringBuilder(str.length()+trailingZeros);
3002                 buf.append(str);
3003             }
3004             for (int i = 0; i < trailingZeros; i++) {
3005                 buf.append('0');
3006             }
3007             return buf.toString();
3008         }
3009         String str ;
3010         if(intCompact!=INFLATED) {
3011             str = Long.toString(Math.abs(intCompact));
3012         } else {
3013             str = intVal.abs().toString();
3014         }
3015         return getValueString(signum(), str, scale);
3016     }
3017 
3018     /* Returns a digit.digit string */
3019     private String getValueString(int signum, String intString, int scale) {
3020         /* Insert decimal point */
3021         StringBuilder buf;
3022         int insertionPoint = intString.length() - scale;
3023         if (insertionPoint == 0) {  /* Point goes right before intVal */
3024             return (signum<0 ? "-0." : "0.") + intString;
3025         } else if (insertionPoint > 0) { /* Point goes inside intVal */
3026             buf = new StringBuilder(intString);
3027             buf.insert(insertionPoint, '.');
3028             if (signum < 0)
3029                 buf.insert(0, '-');
3030         } else { /* We must insert zeros between point and intVal */
3031             buf = new StringBuilder(3-insertionPoint + intString.length());
3032             buf.append(signum<0 ? "-0." : "0.");
3033             for (int i=0; i<-insertionPoint; i++) {
3034                 buf.append('0');
3035             }
3036             buf.append(intString);
3037         }
3038         return buf.toString();
3039     }
3040 
3041     /**
3042      * Converts this {@code BigDecimal} to a {@code BigInteger}.
3043      * This conversion is analogous to the
3044      * <i>narrowing primitive conversion</i> from {@code double} to
3045      * {@code long} as defined in section 5.1.3 of
3046      * <cite>The Java&trade; Language Specification</cite>:
3047      * any fractional part of this
3048      * {@code BigDecimal} will be discarded.  Note that this
3049      * conversion can lose information about the precision of the
3050      * {@code BigDecimal} value.
3051      * <p>
3052      * To have an exception thrown if the conversion is inexact (in
3053      * other words if a nonzero fractional part is discarded), use the
3054      * {@link #toBigIntegerExact()} method.
3055      *
3056      * @return this {@code BigDecimal} converted to a {@code BigInteger}.
3057      */
3058     public BigInteger toBigInteger() {
3059         // force to an integer, quietly
3060         return this.setScale(0, ROUND_DOWN).inflated();
3061     }
3062 
3063     /**
3064      * Converts this {@code BigDecimal} to a {@code BigInteger},
3065      * checking for lost information.  An exception is thrown if this
3066      * {@code BigDecimal} has a nonzero fractional part.
3067      *
3068      * @return this {@code BigDecimal} converted to a {@code BigInteger}.
3069      * @throws ArithmeticException if {@code this} has a nonzero
3070      *         fractional part.
3071      * @since  1.5
3072      */
3073     public BigInteger toBigIntegerExact() {
3074         // round to an integer, with Exception if decimal part non-0
3075         return this.setScale(0, ROUND_UNNECESSARY).inflated();
3076     }
3077 
3078     /**
3079      * Converts this {@code BigDecimal} to a {@code long}.
3080      * This conversion is analogous to the
3081      * <i>narrowing primitive conversion</i> from {@code double} to
3082      * {@code short} as defined in section 5.1.3 of
3083      * <cite>The Java&trade; Language Specification</cite>:
3084      * any fractional part of this
3085      * {@code BigDecimal} will be discarded, and if the resulting
3086      * "{@code BigInteger}" is too big to fit in a
3087      * {@code long}, only the low-order 64 bits are returned.
3088      * Note that this conversion can lose information about the
3089      * overall magnitude and precision of this {@code BigDecimal} value as well
3090      * as return a result with the opposite sign.
3091      *
3092      * @return this {@code BigDecimal} converted to a {@code long}.
3093      */
3094     @Override
3095     public long longValue(){
3096         return (intCompact != INFLATED && scale == 0) ?
3097             intCompact:
3098             toBigInteger().longValue();
3099     }
3100 
3101     /**
3102      * Converts this {@code BigDecimal} to a {@code long}, checking
3103      * for lost information.  If this {@code BigDecimal} has a
3104      * nonzero fractional part or is out of the possible range for a
3105      * {@code long} result then an {@code ArithmeticException} is
3106      * thrown.
3107      *
3108      * @return this {@code BigDecimal} converted to a {@code long}.
3109      * @throws ArithmeticException if {@code this} has a nonzero
3110      *         fractional part, or will not fit in a {@code long}.
3111      * @since  1.5
3112      */
3113     public long longValueExact() {
3114         if (intCompact != INFLATED && scale == 0)
3115             return intCompact;
3116         // If more than 19 digits in integer part it cannot possibly fit
3117         if ((precision() - scale) > 19) // [OK for negative scale too]
3118             throw new java.lang.ArithmeticException("Overflow");
3119         // Fastpath zero and < 1.0 numbers (the latter can be very slow
3120         // to round if very small)
3121         if (this.signum() == 0)
3122             return 0;
3123         if ((this.precision() - this.scale) <= 0)
3124             throw new ArithmeticException("Rounding necessary");
3125         // round to an integer, with Exception if decimal part non-0
3126         BigDecimal num = this.setScale(0, ROUND_UNNECESSARY);
3127         if (num.precision() >= 19) // need to check carefully
3128             LongOverflow.check(num);
3129         return num.inflated().longValue();
3130     }
3131 
3132     private static class LongOverflow {
3133         /** BigInteger equal to Long.MIN_VALUE. */
3134         private static final BigInteger LONGMIN = BigInteger.valueOf(Long.MIN_VALUE);
3135 
3136         /** BigInteger equal to Long.MAX_VALUE. */
3137         private static final BigInteger LONGMAX = BigInteger.valueOf(Long.MAX_VALUE);
3138 
3139         public static void check(BigDecimal num) {
3140             BigInteger intVal = num.inflated();
3141             if (intVal.compareTo(LONGMIN) < 0 ||
3142                 intVal.compareTo(LONGMAX) > 0)
3143                 throw new java.lang.ArithmeticException("Overflow");
3144         }
3145     }
3146 
3147     /**
3148      * Converts this {@code BigDecimal} to an {@code int}.
3149      * This conversion is analogous to the
3150      * <i>narrowing primitive conversion</i> from {@code double} to
3151      * {@code short} as defined in section 5.1.3 of
3152      * <cite>The Java&trade; Language Specification</cite>:
3153      * any fractional part of this
3154      * {@code BigDecimal} will be discarded, and if the resulting
3155      * "{@code BigInteger}" is too big to fit in an
3156      * {@code int}, only the low-order 32 bits are returned.
3157      * Note that this conversion can lose information about the
3158      * overall magnitude and precision of this {@code BigDecimal}
3159      * value as well as return a result with the opposite sign.
3160      *
3161      * @return this {@code BigDecimal} converted to an {@code int}.
3162      */
3163     @Override
3164     public int intValue() {
3165         return  (intCompact != INFLATED && scale == 0) ?
3166             (int)intCompact :
3167             toBigInteger().intValue();
3168     }
3169 
3170     /**
3171      * Converts this {@code BigDecimal} to an {@code int}, checking
3172      * for lost information.  If this {@code BigDecimal} has a
3173      * nonzero fractional part or is out of the possible range for an
3174      * {@code int} result then an {@code ArithmeticException} is
3175      * thrown.
3176      *
3177      * @return this {@code BigDecimal} converted to an {@code int}.
3178      * @throws ArithmeticException if {@code this} has a nonzero
3179      *         fractional part, or will not fit in an {@code int}.
3180      * @since  1.5
3181      */
3182     public int intValueExact() {
3183        long num;
3184        num = this.longValueExact();     // will check decimal part
3185        if ((int)num != num)
3186            throw new java.lang.ArithmeticException("Overflow");
3187        return (int)num;
3188     }
3189 
3190     /**
3191      * Converts this {@code BigDecimal} to a {@code short}, checking
3192      * for lost information.  If this {@code BigDecimal} has a
3193      * nonzero fractional part or is out of the possible range for a
3194      * {@code short} result then an {@code ArithmeticException} is
3195      * thrown.
3196      *
3197      * @return this {@code BigDecimal} converted to a {@code short}.
3198      * @throws ArithmeticException if {@code this} has a nonzero
3199      *         fractional part, or will not fit in a {@code short}.
3200      * @since  1.5
3201      */
3202     public short shortValueExact() {
3203        long num;
3204        num = this.longValueExact();     // will check decimal part
3205        if ((short)num != num)
3206            throw new java.lang.ArithmeticException("Overflow");
3207        return (short)num;
3208     }
3209 
3210     /**
3211      * Converts this {@code BigDecimal} to a {@code byte}, checking
3212      * for lost information.  If this {@code BigDecimal} has a
3213      * nonzero fractional part or is out of the possible range for a
3214      * {@code byte} result then an {@code ArithmeticException} is
3215      * thrown.
3216      *
3217      * @return this {@code BigDecimal} converted to a {@code byte}.
3218      * @throws ArithmeticException if {@code this} has a nonzero
3219      *         fractional part, or will not fit in a {@code byte}.
3220      * @since  1.5
3221      */
3222     public byte byteValueExact() {
3223        long num;
3224        num = this.longValueExact();     // will check decimal part
3225        if ((byte)num != num)
3226            throw new java.lang.ArithmeticException("Overflow");
3227        return (byte)num;
3228     }
3229 
3230     /**
3231      * Converts this {@code BigDecimal} to a {@code float}.
3232      * This conversion is similar to the
3233      * <i>narrowing primitive conversion</i> from {@code double} to
3234      * {@code float} as defined in section 5.1.3 of
3235      * <cite>The Java&trade; Language Specification</cite>:
3236      * if this {@code BigDecimal} has too great a
3237      * magnitude to represent as a {@code float}, it will be
3238      * converted to {@link Float#NEGATIVE_INFINITY} or {@link
3239      * Float#POSITIVE_INFINITY} as appropriate.  Note that even when
3240      * the return value is finite, this conversion can lose
3241      * information about the precision of the {@code BigDecimal}
3242      * value.
3243      *
3244      * @return this {@code BigDecimal} converted to a {@code float}.
3245      */
3246     @Override
3247     public float floatValue(){
3248         if(intCompact != INFLATED) {
3249             if (scale == 0) {
3250                 return (float)intCompact;
3251             } else {
3252                 /*
3253                  * If both intCompact and the scale can be exactly
3254                  * represented as float values, perform a single float
3255                  * multiply or divide to compute the (properly
3256                  * rounded) result.
3257                  */
3258                 if (Math.abs(intCompact) < 1L<<22 ) {
3259                     // Don't have too guard against
3260                     // Math.abs(MIN_VALUE) because of outer check
3261                     // against INFLATED.
3262                     if (scale > 0 && scale < FLOAT_10_POW.length) {
3263                         return (float)intCompact / FLOAT_10_POW[scale];
3264                     } else if (scale < 0 && scale > -FLOAT_10_POW.length) {
3265                         return (float)intCompact * FLOAT_10_POW[-scale];
3266                     }
3267                 }
3268             }
3269         }
3270         // Somewhat inefficient, but guaranteed to work.
3271         return Float.parseFloat(this.toString());
3272     }
3273 
3274     /**
3275      * Converts this {@code BigDecimal} to a {@code double}.
3276      * This conversion is similar to the
3277      * <i>narrowing primitive conversion</i> from {@code double} to
3278      * {@code float} as defined in section 5.1.3 of
3279      * <cite>The Java&trade; Language Specification</cite>:
3280      * if this {@code BigDecimal} has too great a
3281      * magnitude represent as a {@code double}, it will be
3282      * converted to {@link Double#NEGATIVE_INFINITY} or {@link
3283      * Double#POSITIVE_INFINITY} as appropriate.  Note that even when
3284      * the return value is finite, this conversion can lose
3285      * information about the precision of the {@code BigDecimal}
3286      * value.
3287      *
3288      * @return this {@code BigDecimal} converted to a {@code double}.
3289      */
3290     @Override
3291     public double doubleValue(){
3292         if(intCompact != INFLATED) {
3293             if (scale == 0) {
3294                 return (double)intCompact;
3295             } else {
3296                 /*
3297                  * If both intCompact and the scale can be exactly
3298                  * represented as double values, perform a single
3299                  * double multiply or divide to compute the (properly
3300                  * rounded) result.
3301                  */
3302                 if (Math.abs(intCompact) < 1L<<52 ) {
3303                     // Don't have too guard against
3304                     // Math.abs(MIN_VALUE) because of outer check
3305                     // against INFLATED.
3306                     if (scale > 0 && scale < DOUBLE_10_POW.length) {
3307                         return (double)intCompact / DOUBLE_10_POW[scale];
3308                     } else if (scale < 0 && scale > -DOUBLE_10_POW.length) {
3309                         return (double)intCompact * DOUBLE_10_POW[-scale];
3310                     }
3311                 }
3312             }
3313         }
3314         // Somewhat inefficient, but guaranteed to work.
3315         return Double.parseDouble(this.toString());
3316     }
3317 
3318     /**
3319      * Powers of 10 which can be represented exactly in {@code
3320      * double}.
3321      */
3322     private static final double DOUBLE_10_POW[] = {
3323         1.0e0,  1.0e1,  1.0e2,  1.0e3,  1.0e4,  1.0e5,
3324         1.0e6,  1.0e7,  1.0e8,  1.0e9,  1.0e10, 1.0e11,
3325         1.0e12, 1.0e13, 1.0e14, 1.0e15, 1.0e16, 1.0e17,
3326         1.0e18, 1.0e19, 1.0e20, 1.0e21, 1.0e22
3327     };
3328 
3329     /**
3330      * Powers of 10 which can be represented exactly in {@code
3331      * float}.
3332      */
3333     private static final float FLOAT_10_POW[] = {
3334         1.0e0f, 1.0e1f, 1.0e2f, 1.0e3f, 1.0e4f, 1.0e5f,
3335         1.0e6f, 1.0e7f, 1.0e8f, 1.0e9f, 1.0e10f
3336     };
3337 
3338     /**
3339      * Returns the size of an ulp, a unit in the last place, of this
3340      * {@code BigDecimal}.  An ulp of a nonzero {@code BigDecimal}
3341      * value is the positive distance between this value and the
3342      * {@code BigDecimal} value next larger in magnitude with the
3343      * same number of digits.  An ulp of a zero value is numerically
3344      * equal to 1 with the scale of {@code this}.  The result is
3345      * stored with the same scale as {@code this} so the result
3346      * for zero and nonzero values is equal to {@code [1,
3347      * this.scale()]}.
3348      *
3349      * @return the size of an ulp of {@code this}
3350      * @since 1.5
3351      */
3352     public BigDecimal ulp() {
3353         return BigDecimal.valueOf(1, this.scale(), 1);
3354     }
3355 
3356     // Private class to build a string representation for BigDecimal object.
3357     // "StringBuilderHelper" is constructed as a thread local variable so it is
3358     // thread safe. The StringBuilder field acts as a buffer to hold the temporary
3359     // representation of BigDecimal. The cmpCharArray holds all the characters for
3360     // the compact representation of BigDecimal (except for '-' sign' if it is
3361     // negative) if its intCompact field is not INFLATED. It is shared by all
3362     // calls to toString() and its variants in that particular thread.
3363     static class StringBuilderHelper {
3364         final StringBuilder sb;    // Placeholder for BigDecimal string
3365         final char[] cmpCharArray; // character array to place the intCompact
3366 
3367         StringBuilderHelper() {
3368             sb = new StringBuilder();
3369             // All non negative longs can be made to fit into 19 character array.
3370             cmpCharArray = new char[19];
3371         }
3372 
3373         // Accessors.
3374         StringBuilder getStringBuilder() {
3375             sb.setLength(0);
3376             return sb;
3377         }
3378 
3379         char[] getCompactCharArray() {
3380             return cmpCharArray;
3381         }
3382 
3383         /**
3384          * Places characters representing the intCompact in {@code long} into
3385          * cmpCharArray and returns the offset to the array where the
3386          * representation starts.
3387          *
3388          * @param intCompact the number to put into the cmpCharArray.
3389          * @return offset to the array where the representation starts.
3390          * Note: intCompact must be greater or equal to zero.
3391          */
3392         int putIntCompact(long intCompact) {
3393             assert intCompact >= 0;
3394 
3395             long q;
3396             int r;
3397             // since we start from the least significant digit, charPos points to
3398             // the last character in cmpCharArray.
3399             int charPos = cmpCharArray.length;
3400 
3401             // Get 2 digits/iteration using longs until quotient fits into an int
3402             while (intCompact > Integer.MAX_VALUE) {
3403                 q = intCompact / 100;
3404                 r = (int)(intCompact - q * 100);
3405                 intCompact = q;
3406                 cmpCharArray[--charPos] = DIGIT_ONES[r];
3407                 cmpCharArray[--charPos] = DIGIT_TENS[r];
3408             }
3409 
3410             // Get 2 digits/iteration using ints when i2 >= 100
3411             int q2;
3412             int i2 = (int)intCompact;
3413             while (i2 >= 100) {
3414                 q2 = i2 / 100;
3415                 r  = i2 - q2 * 100;
3416                 i2 = q2;
3417                 cmpCharArray[--charPos] = DIGIT_ONES[r];
3418                 cmpCharArray[--charPos] = DIGIT_TENS[r];
3419             }
3420 
3421             cmpCharArray[--charPos] = DIGIT_ONES[i2];
3422             if (i2 >= 10)
3423                 cmpCharArray[--charPos] = DIGIT_TENS[i2];
3424 
3425             return charPos;
3426         }
3427 
3428         static final char[] DIGIT_TENS = {
3429             '0', '0', '0', '0', '0', '0', '0', '0', '0', '0',
3430             '1', '1', '1', '1', '1', '1', '1', '1', '1', '1',
3431             '2', '2', '2', '2', '2', '2', '2', '2', '2', '2',
3432             '3', '3', '3', '3', '3', '3', '3', '3', '3', '3',
3433             '4', '4', '4', '4', '4', '4', '4', '4', '4', '4',
3434             '5', '5', '5', '5', '5', '5', '5', '5', '5', '5',
3435             '6', '6', '6', '6', '6', '6', '6', '6', '6', '6',
3436             '7', '7', '7', '7', '7', '7', '7', '7', '7', '7',
3437             '8', '8', '8', '8', '8', '8', '8', '8', '8', '8',
3438             '9', '9', '9', '9', '9', '9', '9', '9', '9', '9',
3439         };
3440 
3441         static final char[] DIGIT_ONES = {
3442             '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
3443             '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
3444             '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
3445             '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
3446             '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
3447             '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
3448             '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
3449             '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
3450             '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
3451             '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
3452         };
3453     }
3454 
3455     /**
3456      * Lay out this {@code BigDecimal} into a {@code char[]} array.
3457      * The Java 1.2 equivalent to this was called {@code getValueString}.
3458      *
3459      * @param  sci {@code true} for Scientific exponential notation;
3460      *          {@code false} for Engineering
3461      * @return string with canonical string representation of this
3462      *         {@code BigDecimal}
3463      */
3464     private String layoutChars(boolean sci) {
3465         if (scale == 0)                      // zero scale is trivial
3466             return (intCompact != INFLATED) ?
3467                 Long.toString(intCompact):
3468                 intVal.toString();
3469         if (scale == 2  &&
3470             intCompact >= 0 && intCompact < Integer.MAX_VALUE) {
3471             // currency fast path
3472             int lowInt = (int)intCompact % 100;
3473             int highInt = (int)intCompact / 100;
3474             return (Integer.toString(highInt) + '.' +
3475                     StringBuilderHelper.DIGIT_TENS[lowInt] +
3476                     StringBuilderHelper.DIGIT_ONES[lowInt]) ;
3477         }
3478 
3479         StringBuilderHelper sbHelper = threadLocalStringBuilderHelper.get();
3480         char[] coeff;
3481         int offset;  // offset is the starting index for coeff array
3482         // Get the significand as an absolute value
3483         if (intCompact != INFLATED) {
3484             offset = sbHelper.putIntCompact(Math.abs(intCompact));
3485             coeff  = sbHelper.getCompactCharArray();
3486         } else {
3487             offset = 0;
3488             coeff  = intVal.abs().toString().toCharArray();
3489         }
3490 
3491         // Construct a buffer, with sufficient capacity for all cases.
3492         // If E-notation is needed, length will be: +1 if negative, +1
3493         // if '.' needed, +2 for "E+", + up to 10 for adjusted exponent.
3494         // Otherwise it could have +1 if negative, plus leading "0.00000"
3495         StringBuilder buf = sbHelper.getStringBuilder();
3496         if (signum() < 0)             // prefix '-' if negative
3497             buf.append('-');
3498         int coeffLen = coeff.length - offset;
3499         long adjusted = -(long)scale + (coeffLen -1);
3500         if ((scale >= 0) && (adjusted >= -6)) { // plain number
3501             int pad = scale - coeffLen;         // count of padding zeros
3502             if (pad >= 0) {                     // 0.xxx form
3503                 buf.append('0');
3504                 buf.append('.');
3505                 for (; pad>0; pad--) {
3506                     buf.append('0');
3507                 }
3508                 buf.append(coeff, offset, coeffLen);
3509             } else {                         // xx.xx form
3510                 buf.append(coeff, offset, -pad);
3511                 buf.append('.');
3512                 buf.append(coeff, -pad + offset, scale);
3513             }
3514         } else { // E-notation is needed
3515             if (sci) {                       // Scientific notation
3516                 buf.append(coeff[offset]);   // first character
3517                 if (coeffLen > 1) {          // more to come
3518                     buf.append('.');
3519                     buf.append(coeff, offset + 1, coeffLen - 1);
3520                 }
3521             } else {                         // Engineering notation
3522                 int sig = (int)(adjusted % 3);
3523                 if (sig < 0)
3524                     sig += 3;                // [adjusted was negative]
3525                 adjusted -= sig;             // now a multiple of 3
3526                 sig++;
3527                 if (signum() == 0) {
3528                     switch (sig) {
3529                     case 1:
3530                         buf.append('0'); // exponent is a multiple of three
3531                         break;
3532                     case 2:
3533                         buf.append("0.00");
3534                         adjusted += 3;
3535                         break;
3536                     case 3:
3537                         buf.append("0.0");
3538                         adjusted += 3;
3539                         break;
3540                     default:
3541                         throw new AssertionError("Unexpected sig value " + sig);
3542                     }
3543                 } else if (sig >= coeffLen) {   // significand all in integer
3544                     buf.append(coeff, offset, coeffLen);
3545                     // may need some zeros, too
3546                     for (int i = sig - coeffLen; i > 0; i--) {
3547                         buf.append('0');
3548                     }
3549                 } else {                     // xx.xxE form
3550                     buf.append(coeff, offset, sig);
3551                     buf.append('.');
3552                     buf.append(coeff, offset + sig, coeffLen - sig);
3553                 }
3554             }
3555             if (adjusted != 0) {             // [!sci could have made 0]
3556                 buf.append('E');
3557                 if (adjusted > 0)            // force sign for positive
3558                     buf.append('+');
3559                 buf.append(adjusted);
3560             }
3561         }
3562         return buf.toString();
3563     }
3564 
3565     /**
3566      * Return 10 to the power n, as a {@code BigInteger}.
3567      *
3568      * @param  n the power of ten to be returned (>=0)
3569      * @return a {@code BigInteger} with the value (10<sup>n</sup>)
3570      */
3571     private static BigInteger bigTenToThe(int n) {
3572         if (n < 0)
3573             return BigInteger.ZERO;
3574 
3575         if (n < BIG_TEN_POWERS_TABLE_MAX) {
3576             BigInteger[] pows = BIG_TEN_POWERS_TABLE;
3577             if (n < pows.length)
3578                 return pows[n];
3579             else
3580                 return expandBigIntegerTenPowers(n);
3581         }
3582 
3583         return BigInteger.TEN.pow(n);
3584     }
3585 
3586     /**
3587      * Expand the BIG_TEN_POWERS_TABLE array to contain at least 10**n.
3588      *
3589      * @param n the power of ten to be returned (>=0)
3590      * @return a {@code BigDecimal} with the value (10<sup>n</sup>) and
3591      *         in the meantime, the BIG_TEN_POWERS_TABLE array gets
3592      *         expanded to the size greater than n.
3593      */
3594     private static BigInteger expandBigIntegerTenPowers(int n) {
3595         synchronized(BigDecimal.class) {
3596             BigInteger[] pows = BIG_TEN_POWERS_TABLE;
3597             int curLen = pows.length;
3598             // The following comparison and the above synchronized statement is
3599             // to prevent multiple threads from expanding the same array.
3600             if (curLen <= n) {
3601                 int newLen = curLen << 1;
3602                 while (newLen <= n) {
3603                     newLen <<= 1;
3604                 }
3605                 pows = Arrays.copyOf(pows, newLen);
3606                 for (int i = curLen; i < newLen; i++) {
3607                     pows[i] = pows[i - 1].multiply(BigInteger.TEN);
3608                 }
3609                 // Based on the following facts:
3610                 // 1. pows is a private local varible;
3611                 // 2. the following store is a volatile store.
3612                 // the newly created array elements can be safely published.
3613                 BIG_TEN_POWERS_TABLE = pows;
3614             }
3615             return pows[n];
3616         }
3617     }
3618 
3619     private static final long[] LONG_TEN_POWERS_TABLE = {
3620         1,                     // 0 / 10^0
3621         10,                    // 1 / 10^1
3622         100,                   // 2 / 10^2
3623         1000,                  // 3 / 10^3
3624         10000,                 // 4 / 10^4
3625         100000,                // 5 / 10^5
3626         1000000,               // 6 / 10^6
3627         10000000,              // 7 / 10^7
3628         100000000,             // 8 / 10^8
3629         1000000000,            // 9 / 10^9
3630         10000000000L,          // 10 / 10^10
3631         100000000000L,         // 11 / 10^11
3632         1000000000000L,        // 12 / 10^12
3633         10000000000000L,       // 13 / 10^13
3634         100000000000000L,      // 14 / 10^14
3635         1000000000000000L,     // 15 / 10^15
3636         10000000000000000L,    // 16 / 10^16
3637         100000000000000000L,   // 17 / 10^17
3638         1000000000000000000L   // 18 / 10^18
3639     };
3640 
3641     private static volatile BigInteger BIG_TEN_POWERS_TABLE[] = {
3642         BigInteger.ONE,
3643         BigInteger.valueOf(10),
3644         BigInteger.valueOf(100),
3645         BigInteger.valueOf(1000),
3646         BigInteger.valueOf(10000),
3647         BigInteger.valueOf(100000),
3648         BigInteger.valueOf(1000000),
3649         BigInteger.valueOf(10000000),
3650         BigInteger.valueOf(100000000),
3651         BigInteger.valueOf(1000000000),
3652         BigInteger.valueOf(10000000000L),
3653         BigInteger.valueOf(100000000000L),
3654         BigInteger.valueOf(1000000000000L),
3655         BigInteger.valueOf(10000000000000L),
3656         BigInteger.valueOf(100000000000000L),
3657         BigInteger.valueOf(1000000000000000L),
3658         BigInteger.valueOf(10000000000000000L),
3659         BigInteger.valueOf(100000000000000000L),
3660         BigInteger.valueOf(1000000000000000000L)
3661     };
3662 
3663     private static final int BIG_TEN_POWERS_TABLE_INITLEN =
3664         BIG_TEN_POWERS_TABLE.length;
3665     private static final int BIG_TEN_POWERS_TABLE_MAX =
3666         16 * BIG_TEN_POWERS_TABLE_INITLEN;
3667 
3668     private static final long THRESHOLDS_TABLE[] = {
3669         Long.MAX_VALUE,                     // 0
3670         Long.MAX_VALUE/10L,                 // 1
3671         Long.MAX_VALUE/100L,                // 2
3672         Long.MAX_VALUE/1000L,               // 3
3673         Long.MAX_VALUE/10000L,              // 4
3674         Long.MAX_VALUE/100000L,             // 5
3675         Long.MAX_VALUE/1000000L,            // 6
3676         Long.MAX_VALUE/10000000L,           // 7
3677         Long.MAX_VALUE/100000000L,          // 8
3678         Long.MAX_VALUE/1000000000L,         // 9
3679         Long.MAX_VALUE/10000000000L,        // 10
3680         Long.MAX_VALUE/100000000000L,       // 11
3681         Long.MAX_VALUE/1000000000000L,      // 12
3682         Long.MAX_VALUE/10000000000000L,     // 13
3683         Long.MAX_VALUE/100000000000000L,    // 14
3684         Long.MAX_VALUE/1000000000000000L,   // 15
3685         Long.MAX_VALUE/10000000000000000L,  // 16
3686         Long.MAX_VALUE/100000000000000000L, // 17
3687         Long.MAX_VALUE/1000000000000000000L // 18
3688     };
3689 
3690     /**
3691      * Compute val * 10 ^ n; return this product if it is
3692      * representable as a long, INFLATED otherwise.
3693      */
3694     private static long longMultiplyPowerTen(long val, int n) {
3695         if (val == 0 || n <= 0)
3696             return val;
3697         long[] tab = LONG_TEN_POWERS_TABLE;
3698         long[] bounds = THRESHOLDS_TABLE;
3699         if (n < tab.length && n < bounds.length) {
3700             long tenpower = tab[n];
3701             if (val == 1)
3702                 return tenpower;
3703             if (Math.abs(val) <= bounds[n])
3704                 return val * tenpower;
3705         }
3706         return INFLATED;
3707     }
3708 
3709     /**
3710      * Compute this * 10 ^ n.
3711      * Needed mainly to allow special casing to trap zero value
3712      */
3713     private BigInteger bigMultiplyPowerTen(int n) {
3714         if (n <= 0)
3715             return this.inflated();
3716 
3717         if (intCompact != INFLATED)
3718             return bigTenToThe(n).multiply(intCompact);
3719         else
3720             return intVal.multiply(bigTenToThe(n));
3721     }
3722 
3723     /**
3724      * Returns appropriate BigInteger from intVal field if intVal is
3725      * null, i.e. the compact representation is in use.
3726      */
3727     private BigInteger inflated() {
3728         if (intVal == null) {
3729             return BigInteger.valueOf(intCompact);
3730         }
3731         return intVal;
3732     }
3733 
3734     /**
3735      * Match the scales of two {@code BigDecimal}s to align their
3736      * least significant digits.
3737      *
3738      * <p>If the scales of val[0] and val[1] differ, rescale
3739      * (non-destructively) the lower-scaled {@code BigDecimal} so
3740      * they match.  That is, the lower-scaled reference will be
3741      * replaced by a reference to a new object with the same scale as
3742      * the other {@code BigDecimal}.
3743      *
3744      * @param  val array of two elements referring to the two
3745      *         {@code BigDecimal}s to be aligned.
3746      */
3747     private static void matchScale(BigDecimal[] val) {
3748         if (val[0].scale < val[1].scale) {
3749             val[0] = val[0].setScale(val[1].scale, ROUND_UNNECESSARY);
3750         } else if (val[1].scale < val[0].scale) {
3751             val[1] = val[1].setScale(val[0].scale, ROUND_UNNECESSARY);
3752         }
3753     }
3754 
3755     private static class UnsafeHolder {
3756         private static final jdk.internal.misc.Unsafe unsafe;
3757         private static final long intCompactOffset;
3758         private static final long intValOffset;
3759         static {
3760             try {
3761                 unsafe = jdk.internal.misc.Unsafe.getUnsafe();
3762                 intCompactOffset = unsafe.objectFieldOffset
3763                     (BigDecimal.class.getDeclaredField("intCompact"));
3764                 intValOffset = unsafe.objectFieldOffset
3765                     (BigDecimal.class.getDeclaredField("intVal"));
3766             } catch (Exception ex) {
3767                 throw new ExceptionInInitializerError(ex);
3768             }
3769         }
3770         static void setIntCompact(BigDecimal bd, long val) {
3771             unsafe.putLong(bd, intCompactOffset, val);
3772         }
3773 
3774         static void setIntValVolatile(BigDecimal bd, BigInteger val) {
3775             unsafe.putObjectVolatile(bd, intValOffset, val);
3776         }
3777     }
3778 
3779     /**
3780      * Reconstitute the {@code BigDecimal} instance from a stream (that is,
3781      * deserialize it).
3782      *
3783      * @param s the stream being read.
3784      */
3785     private void readObject(java.io.ObjectInputStream s)
3786         throws java.io.IOException, ClassNotFoundException {
3787         // Read in all fields
3788         s.defaultReadObject();
3789         // validate possibly bad fields
3790         if (intVal == null) {
3791             String message = "BigDecimal: null intVal in stream";
3792             throw new java.io.StreamCorruptedException(message);
3793         // [all values of scale are now allowed]
3794         }
3795         UnsafeHolder.setIntCompact(this, compactValFor(intVal));
3796     }
3797 
3798    /**
3799     * Serialize this {@code BigDecimal} to the stream in question
3800     *
3801     * @param s the stream to serialize to.
3802     */
3803    private void writeObject(java.io.ObjectOutputStream s)
3804        throws java.io.IOException {
3805        // Must inflate to maintain compatible serial form.
3806        if (this.intVal == null)
3807            UnsafeHolder.setIntValVolatile(this, BigInteger.valueOf(this.intCompact));
3808        // Could reset intVal back to null if it has to be set.
3809        s.defaultWriteObject();
3810    }
3811 
3812     /**
3813      * Returns the length of the absolute value of a {@code long}, in decimal
3814      * digits.
3815      *
3816      * @param x the {@code long}
3817      * @return the length of the unscaled value, in deciaml digits.
3818      */
3819     static int longDigitLength(long x) {
3820         /*
3821          * As described in "Bit Twiddling Hacks" by Sean Anderson,
3822          * (http://graphics.stanford.edu/~seander/bithacks.html)
3823          * integer log 10 of x is within 1 of (1233/4096)* (1 +
3824          * integer log 2 of x). The fraction 1233/4096 approximates
3825          * log10(2). So we first do a version of log2 (a variant of
3826          * Long class with pre-checks and opposite directionality) and
3827          * then scale and check against powers table. This is a little
3828          * simpler in present context than the version in Hacker's
3829          * Delight sec 11-4. Adding one to bit length allows comparing
3830          * downward from the LONG_TEN_POWERS_TABLE that we need
3831          * anyway.
3832          */
3833         assert x != BigDecimal.INFLATED;
3834         if (x < 0)
3835             x = -x;
3836         if (x < 10) // must screen for 0, might as well 10
3837             return 1;
3838         int r = ((64 - Long.numberOfLeadingZeros(x) + 1) * 1233) >>> 12;
3839         long[] tab = LONG_TEN_POWERS_TABLE;
3840         // if r >= length, must have max possible digits for long
3841         return (r >= tab.length || x < tab[r]) ? r : r + 1;
3842     }
3843 
3844     /**
3845      * Returns the length of the absolute value of a BigInteger, in
3846      * decimal digits.
3847      *
3848      * @param b the BigInteger
3849      * @return the length of the unscaled value, in decimal digits
3850      */
3851     private static int bigDigitLength(BigInteger b) {
3852         /*
3853          * Same idea as the long version, but we need a better
3854          * approximation of log10(2). Using 646456993/2^31
3855          * is accurate up to max possible reported bitLength.
3856          */
3857         if (b.signum == 0)
3858             return 1;
3859         int r = (int)((((long)b.bitLength() + 1) * 646456993) >>> 31);
3860         return b.compareMagnitude(bigTenToThe(r)) < 0? r : r+1;
3861     }
3862 
3863     /**
3864      * Check a scale for Underflow or Overflow.  If this BigDecimal is
3865      * nonzero, throw an exception if the scale is outof range. If this
3866      * is zero, saturate the scale to the extreme value of the right
3867      * sign if the scale is out of range.
3868      *
3869      * @param val The new scale.
3870      * @throws ArithmeticException (overflow or underflow) if the new
3871      *         scale is out of range.
3872      * @return validated scale as an int.
3873      */
3874     private int checkScale(long val) {
3875         int asInt = (int)val;
3876         if (asInt != val) {
3877             asInt = val>Integer.MAX_VALUE ? Integer.MAX_VALUE : Integer.MIN_VALUE;
3878             BigInteger b;
3879             if (intCompact != 0 &&
3880                 ((b = intVal) == null || b.signum() != 0))
3881                 throw new ArithmeticException(asInt>0 ? "Underflow":"Overflow");
3882         }
3883         return asInt;
3884     }
3885 
3886    /**
3887      * Returns the compact value for given {@code BigInteger}, or
3888      * INFLATED if too big. Relies on internal representation of
3889      * {@code BigInteger}.
3890      */
3891     private static long compactValFor(BigInteger b) {
3892         int[] m = b.mag;
3893         int len = m.length;
3894         if (len == 0)
3895             return 0;
3896         int d = m[0];
3897         if (len > 2 || (len == 2 && d < 0))
3898             return INFLATED;
3899 
3900         long u = (len == 2)?
3901             (((long) m[1] & LONG_MASK) + (((long)d) << 32)) :
3902             (((long)d)   & LONG_MASK);
3903         return (b.signum < 0)? -u : u;
3904     }
3905 
3906     private static int longCompareMagnitude(long x, long y) {
3907         if (x < 0)
3908             x = -x;
3909         if (y < 0)
3910             y = -y;
3911         return (x < y) ? -1 : ((x == y) ? 0 : 1);
3912     }
3913 
3914     private static int saturateLong(long s) {
3915         int i = (int)s;
3916         return (s == i) ? i : (s < 0 ? Integer.MIN_VALUE : Integer.MAX_VALUE);
3917     }
3918 
3919     /*
3920      * Internal printing routine
3921      */
3922     private static void print(String name, BigDecimal bd) {
3923         System.err.format("%s:\tintCompact %d\tintVal %d\tscale %d\tprecision %d%n",
3924                           name,
3925                           bd.intCompact,
3926                           bd.intVal,
3927                           bd.scale,
3928                           bd.precision);
3929     }
3930 
3931     /**
3932      * Check internal invariants of this BigDecimal.  These invariants
3933      * include:
3934      *
3935      * <ul>
3936      *
3937      * <li>The object must be initialized; either intCompact must not be
3938      * INFLATED or intVal is non-null.  Both of these conditions may
3939      * be true.
3940      *
3941      * <li>If both intCompact and intVal and set, their values must be
3942      * consistent.
3943      *
3944      * <li>If precision is nonzero, it must have the right value.
3945      * </ul>
3946      *
3947      * Note: Since this is an audit method, we are not supposed to change the
3948      * state of this BigDecimal object.
3949      */
3950     private BigDecimal audit() {
3951         if (intCompact == INFLATED) {
3952             if (intVal == null) {
3953                 print("audit", this);
3954                 throw new AssertionError("null intVal");
3955             }
3956             // Check precision
3957             if (precision > 0 && precision != bigDigitLength(intVal)) {
3958                 print("audit", this);
3959                 throw new AssertionError("precision mismatch");
3960             }
3961         } else {
3962             if (intVal != null) {
3963                 long val = intVal.longValue();
3964                 if (val != intCompact) {
3965                     print("audit", this);
3966                     throw new AssertionError("Inconsistent state, intCompact=" +
3967                                              intCompact + "\t intVal=" + val);
3968                 }
3969             }
3970             // Check precision
3971             if (precision > 0 && precision != longDigitLength(intCompact)) {
3972                 print("audit", this);
3973                 throw new AssertionError("precision mismatch");
3974             }
3975         }
3976         return this;
3977     }
3978 
3979     /* the same as checkScale where value!=0 */
3980     private static int checkScaleNonZero(long val) {
3981         int asInt = (int)val;
3982         if (asInt != val) {
3983             throw new ArithmeticException(asInt>0 ? "Underflow":"Overflow");
3984         }
3985         return asInt;
3986     }
3987 
3988     private static int checkScale(long intCompact, long val) {
3989         int asInt = (int)val;
3990         if (asInt != val) {
3991             asInt = val>Integer.MAX_VALUE ? Integer.MAX_VALUE : Integer.MIN_VALUE;
3992             if (intCompact != 0)
3993                 throw new ArithmeticException(asInt>0 ? "Underflow":"Overflow");
3994         }
3995         return asInt;
3996     }
3997 
3998     private static int checkScale(BigInteger intVal, long val) {
3999         int asInt = (int)val;
4000         if (asInt != val) {
4001             asInt = val>Integer.MAX_VALUE ? Integer.MAX_VALUE : Integer.MIN_VALUE;
4002             if (intVal.signum() != 0)
4003                 throw new ArithmeticException(asInt>0 ? "Underflow":"Overflow");
4004         }
4005         return asInt;
4006     }
4007 
4008     /**
4009      * Returns a {@code BigDecimal} rounded according to the MathContext
4010      * settings;
4011      * If rounding is needed a new {@code BigDecimal} is created and returned.
4012      *
4013      * @param val the value to be rounded
4014      * @param mc the context to use.
4015      * @return a {@code BigDecimal} rounded according to the MathContext
4016      *         settings.  May return {@code value}, if no rounding needed.
4017      * @throws ArithmeticException if the rounding mode is
4018      *         {@code RoundingMode.UNNECESSARY} and the
4019      *         result is inexact.
4020      */
4021     private static BigDecimal doRound(BigDecimal val, MathContext mc) {
4022         int mcp = mc.precision;
4023         boolean wasDivided = false;
4024         if (mcp > 0) {
4025             BigInteger intVal = val.intVal;
4026             long compactVal = val.intCompact;
4027             int scale = val.scale;
4028             int prec = val.precision();
4029             int mode = mc.roundingMode.oldMode;
4030             int drop;
4031             if (compactVal == INFLATED) {
4032                 drop = prec - mcp;
4033                 while (drop > 0) {
4034                     scale = checkScaleNonZero((long) scale - drop);
4035                     intVal = divideAndRoundByTenPow(intVal, drop, mode);
4036                     wasDivided = true;
4037                     compactVal = compactValFor(intVal);
4038                     if (compactVal != INFLATED) {
4039                         prec = longDigitLength(compactVal);
4040                         break;
4041                     }
4042                     prec = bigDigitLength(intVal);
4043                     drop = prec - mcp;
4044                 }
4045             }
4046             if (compactVal != INFLATED) {
4047                 drop = prec - mcp;  // drop can't be more than 18
4048                 while (drop > 0) {
4049                     scale = checkScaleNonZero((long) scale - drop);
4050                     compactVal = divideAndRound(compactVal, LONG_TEN_POWERS_TABLE[drop], mc.roundingMode.oldMode);
4051                     wasDivided = true;
4052                     prec = longDigitLength(compactVal);
4053                     drop = prec - mcp;
4054                     intVal = null;
4055                 }
4056             }
4057             return wasDivided ? new BigDecimal(intVal,compactVal,scale,prec) : val;
4058         }
4059         return val;
4060     }
4061 
4062     /*
4063      * Returns a {@code BigDecimal} created from {@code long} value with
4064      * given scale rounded according to the MathContext settings
4065      */
4066     private static BigDecimal doRound(long compactVal, int scale, MathContext mc) {
4067         int mcp = mc.precision;
4068         if (mcp > 0 && mcp < 19) {
4069             int prec = longDigitLength(compactVal);
4070             int drop = prec - mcp;  // drop can't be more than 18
4071             while (drop > 0) {
4072                 scale = checkScaleNonZero((long) scale - drop);
4073                 compactVal = divideAndRound(compactVal, LONG_TEN_POWERS_TABLE[drop], mc.roundingMode.oldMode);
4074                 prec = longDigitLength(compactVal);
4075                 drop = prec - mcp;
4076             }
4077             return valueOf(compactVal, scale, prec);
4078         }
4079         return valueOf(compactVal, scale);
4080     }
4081 
4082     /*
4083      * Returns a {@code BigDecimal} created from {@code BigInteger} value with
4084      * given scale rounded according to the MathContext settings
4085      */
4086     private static BigDecimal doRound(BigInteger intVal, int scale, MathContext mc) {
4087         int mcp = mc.precision;
4088         int prec = 0;
4089         if (mcp > 0) {
4090             long compactVal = compactValFor(intVal);
4091             int mode = mc.roundingMode.oldMode;
4092             int drop;
4093             if (compactVal == INFLATED) {
4094                 prec = bigDigitLength(intVal);
4095                 drop = prec - mcp;
4096                 while (drop > 0) {
4097                     scale = checkScaleNonZero((long) scale - drop);
4098                     intVal = divideAndRoundByTenPow(intVal, drop, mode);
4099                     compactVal = compactValFor(intVal);
4100                     if (compactVal != INFLATED) {
4101                         break;
4102                     }
4103                     prec = bigDigitLength(intVal);
4104                     drop = prec - mcp;
4105                 }
4106             }
4107             if (compactVal != INFLATED) {
4108                 prec = longDigitLength(compactVal);
4109                 drop = prec - mcp;     // drop can't be more than 18
4110                 while (drop > 0) {
4111                     scale = checkScaleNonZero((long) scale - drop);
4112                     compactVal = divideAndRound(compactVal, LONG_TEN_POWERS_TABLE[drop], mc.roundingMode.oldMode);
4113                     prec = longDigitLength(compactVal);
4114                     drop = prec - mcp;
4115                 }
4116                 return valueOf(compactVal,scale,prec);
4117             }
4118         }
4119         return new BigDecimal(intVal,INFLATED,scale,prec);
4120     }
4121 
4122     /*
4123      * Divides {@code BigInteger} value by ten power.
4124      */
4125     private static BigInteger divideAndRoundByTenPow(BigInteger intVal, int tenPow, int roundingMode) {
4126         if (tenPow < LONG_TEN_POWERS_TABLE.length)
4127             intVal = divideAndRound(intVal, LONG_TEN_POWERS_TABLE[tenPow], roundingMode);
4128         else
4129             intVal = divideAndRound(intVal, bigTenToThe(tenPow), roundingMode);
4130         return intVal;
4131     }
4132 
4133     /**
4134      * Internally used for division operation for division {@code long} by
4135      * {@code long}.
4136      * The returned {@code BigDecimal} object is the quotient whose scale is set
4137      * to the passed in scale. If the remainder is not zero, it will be rounded
4138      * based on the passed in roundingMode. Also, if the remainder is zero and
4139      * the last parameter, i.e. preferredScale is NOT equal to scale, the
4140      * trailing zeros of the result is stripped to match the preferredScale.
4141      */
4142     private static BigDecimal divideAndRound(long ldividend, long ldivisor, int scale, int roundingMode,
4143                                              int preferredScale) {
4144 
4145         int qsign; // quotient sign
4146         long q = ldividend / ldivisor; // store quotient in long
4147         if (roundingMode == ROUND_DOWN && scale == preferredScale)
4148             return valueOf(q, scale);
4149         long r = ldividend % ldivisor; // store remainder in long
4150         qsign = ((ldividend < 0) == (ldivisor < 0)) ? 1 : -1;
4151         if (r != 0) {
4152             boolean increment = needIncrement(ldivisor, roundingMode, qsign, q, r);
4153             return valueOf((increment ? q + qsign : q), scale);
4154         } else {
4155             if (preferredScale != scale)
4156                 return createAndStripZerosToMatchScale(q, scale, preferredScale);
4157             else
4158                 return valueOf(q, scale);
4159         }
4160     }
4161 
4162     /**
4163      * Divides {@code long} by {@code long} and do rounding based on the
4164      * passed in roundingMode.
4165      */
4166     private static long divideAndRound(long ldividend, long ldivisor, int roundingMode) {
4167         int qsign; // quotient sign
4168         long q = ldividend / ldivisor; // store quotient in long
4169         if (roundingMode == ROUND_DOWN)
4170             return q;
4171         long r = ldividend % ldivisor; // store remainder in long
4172         qsign = ((ldividend < 0) == (ldivisor < 0)) ? 1 : -1;
4173         if (r != 0) {
4174             boolean increment = needIncrement(ldivisor, roundingMode, qsign, q,     r);
4175             return increment ? q + qsign : q;
4176         } else {
4177             return q;
4178         }
4179     }
4180 
4181     /**
4182      * Shared logic of need increment computation.
4183      */
4184     private static boolean commonNeedIncrement(int roundingMode, int qsign,
4185                                         int cmpFracHalf, boolean oddQuot) {
4186         switch(roundingMode) {
4187         case ROUND_UNNECESSARY:
4188             throw new ArithmeticException("Rounding necessary");
4189 
4190         case ROUND_UP: // Away from zero
4191             return true;
4192 
4193         case ROUND_DOWN: // Towards zero
4194             return false;
4195 
4196         case ROUND_CEILING: // Towards +infinity
4197             return qsign > 0;
4198 
4199         case ROUND_FLOOR: // Towards -infinity
4200             return qsign < 0;
4201 
4202         default: // Some kind of half-way rounding
4203             assert roundingMode >= ROUND_HALF_UP &&
4204                 roundingMode <= ROUND_HALF_EVEN: "Unexpected rounding mode" + RoundingMode.valueOf(roundingMode);
4205 
4206             if (cmpFracHalf < 0 ) // We're closer to higher digit
4207                 return false;
4208             else if (cmpFracHalf > 0 ) // We're closer to lower digit
4209                 return true;
4210             else { // half-way
4211                 assert cmpFracHalf == 0;
4212 
4213                 switch(roundingMode) {
4214                 case ROUND_HALF_DOWN:
4215                     return false;
4216 
4217                 case ROUND_HALF_UP:
4218                     return true;
4219 
4220                 case ROUND_HALF_EVEN:
4221                     return oddQuot;
4222 
4223                 default:
4224                     throw new AssertionError("Unexpected rounding mode" + roundingMode);
4225                 }
4226             }
4227         }
4228     }
4229 
4230     /**
4231      * Tests if quotient has to be incremented according the roundingMode
4232      */
4233     private static boolean needIncrement(long ldivisor, int roundingMode,
4234                                          int qsign, long q, long r) {
4235         assert r != 0L;
4236 
4237         int cmpFracHalf;
4238         if (r <= HALF_LONG_MIN_VALUE || r > HALF_LONG_MAX_VALUE) {
4239             cmpFracHalf = 1; // 2 * r can't fit into long
4240         } else {
4241             cmpFracHalf = longCompareMagnitude(2 * r, ldivisor);
4242         }
4243 
4244         return commonNeedIncrement(roundingMode, qsign, cmpFracHalf, (q & 1L) != 0L);
4245     }
4246 
4247     /**
4248      * Divides {@code BigInteger} value by {@code long} value and
4249      * do rounding based on the passed in roundingMode.
4250      */
4251     private static BigInteger divideAndRound(BigInteger bdividend, long ldivisor, int roundingMode) {
4252         // Descend into mutables for faster remainder checks
4253         MutableBigInteger mdividend = new MutableBigInteger(bdividend.mag);
4254         // store quotient
4255         MutableBigInteger mq = new MutableBigInteger();
4256         // store quotient & remainder in long
4257         long r = mdividend.divide(ldivisor, mq);
4258         // record remainder is zero or not
4259         boolean isRemainderZero = (r == 0);
4260         // quotient sign
4261         int qsign = (ldivisor < 0) ? -bdividend.signum : bdividend.signum;
4262         if (!isRemainderZero) {
4263             if(needIncrement(ldivisor, roundingMode, qsign, mq, r)) {
4264                 mq.add(MutableBigInteger.ONE);
4265             }
4266         }
4267         return mq.toBigInteger(qsign);
4268     }
4269 
4270     /**
4271      * Internally used for division operation for division {@code BigInteger}
4272      * by {@code long}.
4273      * The returned {@code BigDecimal} object is the quotient whose scale is set
4274      * to the passed in scale. If the remainder is not zero, it will be rounded
4275      * based on the passed in roundingMode. Also, if the remainder is zero and
4276      * the last parameter, i.e. preferredScale is NOT equal to scale, the
4277      * trailing zeros of the result is stripped to match the preferredScale.
4278      */
4279     private static BigDecimal divideAndRound(BigInteger bdividend,
4280                                              long ldivisor, int scale, int roundingMode, int preferredScale) {
4281         // Descend into mutables for faster remainder checks
4282         MutableBigInteger mdividend = new MutableBigInteger(bdividend.mag);
4283         // store quotient
4284         MutableBigInteger mq = new MutableBigInteger();
4285         // store quotient & remainder in long
4286         long r = mdividend.divide(ldivisor, mq);
4287         // record remainder is zero or not
4288         boolean isRemainderZero = (r == 0);
4289         // quotient sign
4290         int qsign = (ldivisor < 0) ? -bdividend.signum : bdividend.signum;
4291         if (!isRemainderZero) {
4292             if(needIncrement(ldivisor, roundingMode, qsign, mq, r)) {
4293                 mq.add(MutableBigInteger.ONE);
4294             }
4295             return mq.toBigDecimal(qsign, scale);
4296         } else {
4297             if (preferredScale != scale) {
4298                 long compactVal = mq.toCompactValue(qsign);
4299                 if(compactVal!=INFLATED) {
4300                     return createAndStripZerosToMatchScale(compactVal, scale, preferredScale);
4301                 }
4302                 BigInteger intVal =  mq.toBigInteger(qsign);
4303                 return createAndStripZerosToMatchScale(intVal,scale, preferredScale);
4304             } else {
4305                 return mq.toBigDecimal(qsign, scale);
4306             }
4307         }
4308     }
4309 
4310     /**
4311      * Tests if quotient has to be incremented according the roundingMode
4312      */
4313     private static boolean needIncrement(long ldivisor, int roundingMode,
4314                                          int qsign, MutableBigInteger mq, long r) {
4315         assert r != 0L;
4316 
4317         int cmpFracHalf;
4318         if (r <= HALF_LONG_MIN_VALUE || r > HALF_LONG_MAX_VALUE) {
4319             cmpFracHalf = 1; // 2 * r can't fit into long
4320         } else {
4321             cmpFracHalf = longCompareMagnitude(2 * r, ldivisor);
4322         }
4323 
4324         return commonNeedIncrement(roundingMode, qsign, cmpFracHalf, mq.isOdd());
4325     }
4326 
4327     /**
4328      * Divides {@code BigInteger} value by {@code BigInteger} value and
4329      * do rounding based on the passed in roundingMode.
4330      */
4331     private static BigInteger divideAndRound(BigInteger bdividend, BigInteger bdivisor, int roundingMode) {
4332         boolean isRemainderZero; // record remainder is zero or not
4333         int qsign; // quotient sign
4334         // Descend into mutables for faster remainder checks
4335         MutableBigInteger mdividend = new MutableBigInteger(bdividend.mag);
4336         MutableBigInteger mq = new MutableBigInteger();
4337         MutableBigInteger mdivisor = new MutableBigInteger(bdivisor.mag);
4338         MutableBigInteger mr = mdividend.divide(mdivisor, mq);
4339         isRemainderZero = mr.isZero();
4340         qsign = (bdividend.signum != bdivisor.signum) ? -1 : 1;
4341         if (!isRemainderZero) {
4342             if (needIncrement(mdivisor, roundingMode, qsign, mq, mr)) {
4343                 mq.add(MutableBigInteger.ONE);
4344             }
4345         }
4346         return mq.toBigInteger(qsign);
4347     }
4348 
4349     /**
4350      * Internally used for division operation for division {@code BigInteger}
4351      * by {@code BigInteger}.
4352      * The returned {@code BigDecimal} object is the quotient whose scale is set
4353      * to the passed in scale. If the remainder is not zero, it will be rounded
4354      * based on the passed in roundingMode. Also, if the remainder is zero and
4355      * the last parameter, i.e. preferredScale is NOT equal to scale, the
4356      * trailing zeros of the result is stripped to match the preferredScale.
4357      */
4358     private static BigDecimal divideAndRound(BigInteger bdividend, BigInteger bdivisor, int scale, int roundingMode,
4359                                              int preferredScale) {
4360         boolean isRemainderZero; // record remainder is zero or not
4361         int qsign; // quotient sign
4362         // Descend into mutables for faster remainder checks
4363         MutableBigInteger mdividend = new MutableBigInteger(bdividend.mag);
4364         MutableBigInteger mq = new MutableBigInteger();
4365         MutableBigInteger mdivisor = new MutableBigInteger(bdivisor.mag);
4366         MutableBigInteger mr = mdividend.divide(mdivisor, mq);
4367         isRemainderZero = mr.isZero();
4368         qsign = (bdividend.signum != bdivisor.signum) ? -1 : 1;
4369         if (!isRemainderZero) {
4370             if (needIncrement(mdivisor, roundingMode, qsign, mq, mr)) {
4371                 mq.add(MutableBigInteger.ONE);
4372             }
4373             return mq.toBigDecimal(qsign, scale);
4374         } else {
4375             if (preferredScale != scale) {
4376                 long compactVal = mq.toCompactValue(qsign);
4377                 if (compactVal != INFLATED) {
4378                     return createAndStripZerosToMatchScale(compactVal, scale, preferredScale);
4379                 }
4380                 BigInteger intVal = mq.toBigInteger(qsign);
4381                 return createAndStripZerosToMatchScale(intVal, scale, preferredScale);
4382             } else {
4383                 return mq.toBigDecimal(qsign, scale);
4384             }
4385         }
4386     }
4387 
4388     /**
4389      * Tests if quotient has to be incremented according the roundingMode
4390      */
4391     private static boolean needIncrement(MutableBigInteger mdivisor, int roundingMode,
4392                                          int qsign, MutableBigInteger mq, MutableBigInteger mr) {
4393         assert !mr.isZero();
4394         int cmpFracHalf = mr.compareHalf(mdivisor);
4395         return commonNeedIncrement(roundingMode, qsign, cmpFracHalf, mq.isOdd());
4396     }
4397 
4398     /**
4399      * Remove insignificant trailing zeros from this
4400      * {@code BigInteger} value until the preferred scale is reached or no
4401      * more zeros can be removed.  If the preferred scale is less than
4402      * Integer.MIN_VALUE, all the trailing zeros will be removed.
4403      *
4404      * @return new {@code BigDecimal} with a scale possibly reduced
4405      * to be closed to the preferred scale.
4406      */
4407     private static BigDecimal createAndStripZerosToMatchScale(BigInteger intVal, int scale, long preferredScale) {
4408         BigInteger qr[]; // quotient-remainder pair
4409         while (intVal.compareMagnitude(BigInteger.TEN) >= 0
4410                && scale > preferredScale) {
4411             if (intVal.testBit(0))
4412                 break; // odd number cannot end in 0
4413             qr = intVal.divideAndRemainder(BigInteger.TEN);
4414             if (qr[1].signum() != 0)
4415                 break; // non-0 remainder
4416             intVal = qr[0];
4417             scale = checkScale(intVal,(long) scale - 1); // could Overflow
4418         }
4419         return valueOf(intVal, scale, 0);
4420     }
4421 
4422     /**
4423      * Remove insignificant trailing zeros from this
4424      * {@code long} value until the preferred scale is reached or no
4425      * more zeros can be removed.  If the preferred scale is less than
4426      * Integer.MIN_VALUE, all the trailing zeros will be removed.
4427      *
4428      * @return new {@code BigDecimal} with a scale possibly reduced
4429      * to be closed to the preferred scale.
4430      */
4431     private static BigDecimal createAndStripZerosToMatchScale(long compactVal, int scale, long preferredScale) {
4432         while (Math.abs(compactVal) >= 10L && scale > preferredScale) {
4433             if ((compactVal & 1L) != 0L)
4434                 break; // odd number cannot end in 0
4435             long r = compactVal % 10L;
4436             if (r != 0L)
4437                 break; // non-0 remainder
4438             compactVal /= 10;
4439             scale = checkScale(compactVal, (long) scale - 1); // could Overflow
4440         }
4441         return valueOf(compactVal, scale);
4442     }
4443 
4444     private static BigDecimal stripZerosToMatchScale(BigInteger intVal, long intCompact, int scale, int preferredScale) {
4445         if(intCompact!=INFLATED) {
4446             return createAndStripZerosToMatchScale(intCompact, scale, preferredScale);
4447         } else {
4448             return createAndStripZerosToMatchScale(intVal==null ? INFLATED_BIGINT : intVal,
4449                                                    scale, preferredScale);
4450         }
4451     }
4452 
4453     /*
4454      * returns INFLATED if oveflow
4455      */
4456     private static long add(long xs, long ys){
4457         long sum = xs + ys;
4458         // See "Hacker's Delight" section 2-12 for explanation of
4459         // the overflow test.
4460         if ( (((sum ^ xs) & (sum ^ ys))) >= 0L) { // not overflowed
4461             return sum;
4462         }
4463         return INFLATED;
4464     }
4465 
4466     private static BigDecimal add(long xs, long ys, int scale){
4467         long sum = add(xs, ys);
4468         if (sum!=INFLATED)
4469             return BigDecimal.valueOf(sum, scale);
4470         return new BigDecimal(BigInteger.valueOf(xs).add(ys), scale);
4471     }
4472 
4473     private static BigDecimal add(final long xs, int scale1, final long ys, int scale2) {
4474         long sdiff = (long) scale1 - scale2;
4475         if (sdiff == 0) {
4476             return add(xs, ys, scale1);
4477         } else if (sdiff < 0) {
4478             int raise = checkScale(xs,-sdiff);
4479             long scaledX = longMultiplyPowerTen(xs, raise);
4480             if (scaledX != INFLATED) {
4481                 return add(scaledX, ys, scale2);
4482             } else {
4483                 BigInteger bigsum = bigMultiplyPowerTen(xs,raise).add(ys);
4484                 return ((xs^ys)>=0) ? // same sign test
4485                     new BigDecimal(bigsum, INFLATED, scale2, 0)
4486                     : valueOf(bigsum, scale2, 0);
4487             }
4488         } else {
4489             int raise = checkScale(ys,sdiff);
4490             long scaledY = longMultiplyPowerTen(ys, raise);
4491             if (scaledY != INFLATED) {
4492                 return add(xs, scaledY, scale1);
4493             } else {
4494                 BigInteger bigsum = bigMultiplyPowerTen(ys,raise).add(xs);
4495                 return ((xs^ys)>=0) ?
4496                     new BigDecimal(bigsum, INFLATED, scale1, 0)
4497                     : valueOf(bigsum, scale1, 0);
4498             }
4499         }
4500     }
4501 
4502     private static BigDecimal add(final long xs, int scale1, BigInteger snd, int scale2) {
4503         int rscale = scale1;
4504         long sdiff = (long)rscale - scale2;
4505         boolean sameSigns =  (Long.signum(xs) == snd.signum);
4506         BigInteger sum;
4507         if (sdiff < 0) {
4508             int raise = checkScale(xs,-sdiff);
4509             rscale = scale2;
4510             long scaledX = longMultiplyPowerTen(xs, raise);
4511             if (scaledX == INFLATED) {
4512                 sum = snd.add(bigMultiplyPowerTen(xs,raise));
4513             } else {
4514                 sum = snd.add(scaledX);
4515             }
4516         } else { //if (sdiff > 0) {
4517             int raise = checkScale(snd,sdiff);
4518             snd = bigMultiplyPowerTen(snd,raise);
4519             sum = snd.add(xs);
4520         }
4521         return (sameSigns) ?
4522             new BigDecimal(sum, INFLATED, rscale, 0) :
4523             valueOf(sum, rscale, 0);
4524     }
4525 
4526     private static BigDecimal add(BigInteger fst, int scale1, BigInteger snd, int scale2) {
4527         int rscale = scale1;
4528         long sdiff = (long)rscale - scale2;
4529         if (sdiff != 0) {
4530             if (sdiff < 0) {
4531                 int raise = checkScale(fst,-sdiff);
4532                 rscale = scale2;
4533                 fst = bigMultiplyPowerTen(fst,raise);
4534             } else {
4535                 int raise = checkScale(snd,sdiff);
4536                 snd = bigMultiplyPowerTen(snd,raise);
4537             }
4538         }
4539         BigInteger sum = fst.add(snd);
4540         return (fst.signum == snd.signum) ?
4541                 new BigDecimal(sum, INFLATED, rscale, 0) :
4542                 valueOf(sum, rscale, 0);
4543     }
4544 
4545     private static BigInteger bigMultiplyPowerTen(long value, int n) {
4546         if (n <= 0)
4547             return BigInteger.valueOf(value);
4548         return bigTenToThe(n).multiply(value);
4549     }
4550 
4551     private static BigInteger bigMultiplyPowerTen(BigInteger value, int n) {
4552         if (n <= 0)
4553             return value;
4554         if(n<LONG_TEN_POWERS_TABLE.length) {
4555                 return value.multiply(LONG_TEN_POWERS_TABLE[n]);
4556         }
4557         return value.multiply(bigTenToThe(n));
4558     }
4559 
4560     /**
4561      * Returns a {@code BigDecimal} whose value is {@code (xs /
4562      * ys)}, with rounding according to the context settings.
4563      *
4564      * Fast path - used only when (xscale <= yscale && yscale < 18
4565      *  && mc.presision<18) {
4566      */
4567     private static BigDecimal divideSmallFastPath(final long xs, int xscale,
4568                                                   final long ys, int yscale,
4569                                                   long preferredScale, MathContext mc) {
4570         int mcp = mc.precision;
4571         int roundingMode = mc.roundingMode.oldMode;
4572 
4573         assert (xscale <= yscale) && (yscale < 18) && (mcp < 18);
4574         int xraise = yscale - xscale; // xraise >=0
4575         long scaledX = (xraise==0) ? xs :
4576             longMultiplyPowerTen(xs, xraise); // can't overflow here!
4577         BigDecimal quotient;
4578 
4579         int cmp = longCompareMagnitude(scaledX, ys);
4580         if(cmp > 0) { // satisfy constraint (b)
4581             yscale -= 1; // [that is, divisor *= 10]
4582             int scl = checkScaleNonZero(preferredScale + yscale - xscale + mcp);
4583             if (checkScaleNonZero((long) mcp + yscale - xscale) > 0) {
4584                 // assert newScale >= xscale
4585                 int raise = checkScaleNonZero((long) mcp + yscale - xscale);
4586                 long scaledXs;
4587                 if ((scaledXs = longMultiplyPowerTen(xs, raise)) == INFLATED) {
4588                     quotient = null;
4589                     if((mcp-1) >=0 && (mcp-1)<LONG_TEN_POWERS_TABLE.length) {
4590                         quotient = multiplyDivideAndRound(LONG_TEN_POWERS_TABLE[mcp-1], scaledX, ys, scl, roundingMode, checkScaleNonZero(preferredScale));
4591                     }
4592                     if(quotient==null) {
4593                         BigInteger rb = bigMultiplyPowerTen(scaledX,mcp-1);
4594                         quotient = divideAndRound(rb, ys,
4595                                                   scl, roundingMode, checkScaleNonZero(preferredScale));
4596                     }
4597                 } else {
4598                     quotient = divideAndRound(scaledXs, ys, scl, roundingMode, checkScaleNonZero(preferredScale));
4599                 }
4600             } else {
4601                 int newScale = checkScaleNonZero((long) xscale - mcp);
4602                 // assert newScale >= yscale
4603                 if (newScale == yscale) { // easy case
4604                     quotient = divideAndRound(xs, ys, scl, roundingMode,checkScaleNonZero(preferredScale));
4605                 } else {
4606                     int raise = checkScaleNonZero((long) newScale - yscale);
4607                     long scaledYs;
4608                     if ((scaledYs = longMultiplyPowerTen(ys, raise)) == INFLATED) {
4609                         BigInteger rb = bigMultiplyPowerTen(ys,raise);
4610                         quotient = divideAndRound(BigInteger.valueOf(xs),
4611                                                   rb, scl, roundingMode,checkScaleNonZero(preferredScale));
4612                     } else {
4613                         quotient = divideAndRound(xs, scaledYs, scl, roundingMode,checkScaleNonZero(preferredScale));
4614                     }
4615                 }
4616             }
4617         } else {
4618             // abs(scaledX) <= abs(ys)
4619             // result is "scaledX * 10^msp / ys"
4620             int scl = checkScaleNonZero(preferredScale + yscale - xscale + mcp);
4621             if(cmp==0) {
4622                 // abs(scaleX)== abs(ys) => result will be scaled 10^mcp + correct sign
4623                 quotient = roundedTenPower(((scaledX < 0) == (ys < 0)) ? 1 : -1, mcp, scl, checkScaleNonZero(preferredScale));
4624             } else {
4625                 // abs(scaledX) < abs(ys)
4626                 long scaledXs;
4627                 if ((scaledXs = longMultiplyPowerTen(scaledX, mcp)) == INFLATED) {
4628                     quotient = null;
4629                     if(mcp<LONG_TEN_POWERS_TABLE.length) {
4630                         quotient = multiplyDivideAndRound(LONG_TEN_POWERS_TABLE[mcp], scaledX, ys, scl, roundingMode, checkScaleNonZero(preferredScale));
4631                     }
4632                     if(quotient==null) {
4633                         BigInteger rb = bigMultiplyPowerTen(scaledX,mcp);
4634                         quotient = divideAndRound(rb, ys,
4635                                                   scl, roundingMode, checkScaleNonZero(preferredScale));
4636                     }
4637                 } else {
4638                     quotient = divideAndRound(scaledXs, ys, scl, roundingMode, checkScaleNonZero(preferredScale));
4639                 }
4640             }
4641         }
4642         // doRound, here, only affects 1000000000 case.
4643         return doRound(quotient,mc);
4644     }
4645 
4646     /**
4647      * Returns a {@code BigDecimal} whose value is {@code (xs /
4648      * ys)}, with rounding according to the context settings.
4649      */
4650     private static BigDecimal divide(final long xs, int xscale, final long ys, int yscale, long preferredScale, MathContext mc) {
4651         int mcp = mc.precision;
4652         if(xscale <= yscale && yscale < 18 && mcp<18) {
4653             return divideSmallFastPath(xs, xscale, ys, yscale, preferredScale, mc);
4654         }
4655         if (compareMagnitudeNormalized(xs, xscale, ys, yscale) > 0) {// satisfy constraint (b)
4656             yscale -= 1; // [that is, divisor *= 10]
4657         }
4658         int roundingMode = mc.roundingMode.oldMode;
4659         // In order to find out whether the divide generates the exact result,
4660         // we avoid calling the above divide method. 'quotient' holds the
4661         // return BigDecimal object whose scale will be set to 'scl'.
4662         int scl = checkScaleNonZero(preferredScale + yscale - xscale + mcp);
4663         BigDecimal quotient;
4664         if (checkScaleNonZero((long) mcp + yscale - xscale) > 0) {
4665             int raise = checkScaleNonZero((long) mcp + yscale - xscale);
4666             long scaledXs;
4667             if ((scaledXs = longMultiplyPowerTen(xs, raise)) == INFLATED) {
4668                 BigInteger rb = bigMultiplyPowerTen(xs,raise);
4669                 quotient = divideAndRound(rb, ys, scl, roundingMode, checkScaleNonZero(preferredScale));
4670             } else {
4671                 quotient = divideAndRound(scaledXs, ys, scl, roundingMode, checkScaleNonZero(preferredScale));
4672             }
4673         } else {
4674             int newScale = checkScaleNonZero((long) xscale - mcp);
4675             // assert newScale >= yscale
4676             if (newScale == yscale) { // easy case
4677                 quotient = divideAndRound(xs, ys, scl, roundingMode,checkScaleNonZero(preferredScale));
4678             } else {
4679                 int raise = checkScaleNonZero((long) newScale - yscale);
4680                 long scaledYs;
4681                 if ((scaledYs = longMultiplyPowerTen(ys, raise)) == INFLATED) {
4682                     BigInteger rb = bigMultiplyPowerTen(ys,raise);
4683                     quotient = divideAndRound(BigInteger.valueOf(xs),
4684                                               rb, scl, roundingMode,checkScaleNonZero(preferredScale));
4685                 } else {
4686                     quotient = divideAndRound(xs, scaledYs, scl, roundingMode,checkScaleNonZero(preferredScale));
4687                 }
4688             }
4689         }
4690         // doRound, here, only affects 1000000000 case.
4691         return doRound(quotient,mc);
4692     }
4693 
4694     /**
4695      * Returns a {@code BigDecimal} whose value is {@code (xs /
4696      * ys)}, with rounding according to the context settings.
4697      */
4698     private static BigDecimal divide(BigInteger xs, int xscale, long ys, int yscale, long preferredScale, MathContext mc) {
4699         // Normalize dividend & divisor so that both fall into [0.1, 0.999...]
4700         if ((-compareMagnitudeNormalized(ys, yscale, xs, xscale)) > 0) {// satisfy constraint (b)
4701             yscale -= 1; // [that is, divisor *= 10]
4702         }
4703         int mcp = mc.precision;
4704         int roundingMode = mc.roundingMode.oldMode;
4705 
4706         // In order to find out whether the divide generates the exact result,
4707         // we avoid calling the above divide method. 'quotient' holds the
4708         // return BigDecimal object whose scale will be set to 'scl'.
4709         BigDecimal quotient;
4710         int scl = checkScaleNonZero(preferredScale + yscale - xscale + mcp);
4711         if (checkScaleNonZero((long) mcp + yscale - xscale) > 0) {
4712             int raise = checkScaleNonZero((long) mcp + yscale - xscale);
4713             BigInteger rb = bigMultiplyPowerTen(xs,raise);
4714             quotient = divideAndRound(rb, ys, scl, roundingMode, checkScaleNonZero(preferredScale));
4715         } else {
4716             int newScale = checkScaleNonZero((long) xscale - mcp);
4717             // assert newScale >= yscale
4718             if (newScale == yscale) { // easy case
4719                 quotient = divideAndRound(xs, ys, scl, roundingMode,checkScaleNonZero(preferredScale));
4720             } else {
4721                 int raise = checkScaleNonZero((long) newScale - yscale);
4722                 long scaledYs;
4723                 if ((scaledYs = longMultiplyPowerTen(ys, raise)) == INFLATED) {
4724                     BigInteger rb = bigMultiplyPowerTen(ys,raise);
4725                     quotient = divideAndRound(xs, rb, scl, roundingMode,checkScaleNonZero(preferredScale));
4726                 } else {
4727                     quotient = divideAndRound(xs, scaledYs, scl, roundingMode,checkScaleNonZero(preferredScale));
4728                 }
4729             }
4730         }
4731         // doRound, here, only affects 1000000000 case.
4732         return doRound(quotient, mc);
4733     }
4734 
4735     /**
4736      * Returns a {@code BigDecimal} whose value is {@code (xs /
4737      * ys)}, with rounding according to the context settings.
4738      */
4739     private static BigDecimal divide(long xs, int xscale, BigInteger ys, int yscale, long preferredScale, MathContext mc) {
4740         // Normalize dividend & divisor so that both fall into [0.1, 0.999...]
4741         if (compareMagnitudeNormalized(xs, xscale, ys, yscale) > 0) {// satisfy constraint (b)
4742             yscale -= 1; // [that is, divisor *= 10]
4743         }
4744         int mcp = mc.precision;
4745         int roundingMode = mc.roundingMode.oldMode;
4746 
4747         // In order to find out whether the divide generates the exact result,
4748         // we avoid calling the above divide method. 'quotient' holds the
4749         // return BigDecimal object whose scale will be set to 'scl'.
4750         BigDecimal quotient;
4751         int scl = checkScaleNonZero(preferredScale + yscale - xscale + mcp);
4752         if (checkScaleNonZero((long) mcp + yscale - xscale) > 0) {
4753             int raise = checkScaleNonZero((long) mcp + yscale - xscale);
4754             BigInteger rb = bigMultiplyPowerTen(xs,raise);
4755             quotient = divideAndRound(rb, ys, scl, roundingMode, checkScaleNonZero(preferredScale));
4756         } else {
4757             int newScale = checkScaleNonZero((long) xscale - mcp);
4758             int raise = checkScaleNonZero((long) newScale - yscale);
4759             BigInteger rb = bigMultiplyPowerTen(ys,raise);
4760             quotient = divideAndRound(BigInteger.valueOf(xs), rb, scl, roundingMode,checkScaleNonZero(preferredScale));
4761         }
4762         // doRound, here, only affects 1000000000 case.
4763         return doRound(quotient, mc);
4764     }
4765 
4766     /**
4767      * Returns a {@code BigDecimal} whose value is {@code (xs /
4768      * ys)}, with rounding according to the context settings.
4769      */
4770     private static BigDecimal divide(BigInteger xs, int xscale, BigInteger ys, int yscale, long preferredScale, MathContext mc) {
4771         // Normalize dividend & divisor so that both fall into [0.1, 0.999...]
4772         if (compareMagnitudeNormalized(xs, xscale, ys, yscale) > 0) {// satisfy constraint (b)
4773             yscale -= 1; // [that is, divisor *= 10]
4774         }
4775         int mcp = mc.precision;
4776         int roundingMode = mc.roundingMode.oldMode;
4777 
4778         // In order to find out whether the divide generates the exact result,
4779         // we avoid calling the above divide method. 'quotient' holds the
4780         // return BigDecimal object whose scale will be set to 'scl'.
4781         BigDecimal quotient;
4782         int scl = checkScaleNonZero(preferredScale + yscale - xscale + mcp);
4783         if (checkScaleNonZero((long) mcp + yscale - xscale) > 0) {
4784             int raise = checkScaleNonZero((long) mcp + yscale - xscale);
4785             BigInteger rb = bigMultiplyPowerTen(xs,raise);
4786             quotient = divideAndRound(rb, ys, scl, roundingMode, checkScaleNonZero(preferredScale));
4787         } else {
4788             int newScale = checkScaleNonZero((long) xscale - mcp);
4789             int raise = checkScaleNonZero((long) newScale - yscale);
4790             BigInteger rb = bigMultiplyPowerTen(ys,raise);
4791             quotient = divideAndRound(xs, rb, scl, roundingMode,checkScaleNonZero(preferredScale));
4792         }
4793         // doRound, here, only affects 1000000000 case.
4794         return doRound(quotient, mc);
4795     }
4796 
4797     /*
4798      * performs divideAndRound for (dividend0*dividend1, divisor)
4799      * returns null if quotient can't fit into long value;
4800      */
4801     private static BigDecimal multiplyDivideAndRound(long dividend0, long dividend1, long divisor, int scale, int roundingMode,
4802                                                      int preferredScale) {
4803         int qsign = Long.signum(dividend0)*Long.signum(dividend1)*Long.signum(divisor);
4804         dividend0 = Math.abs(dividend0);
4805         dividend1 = Math.abs(dividend1);
4806         divisor = Math.abs(divisor);
4807         // multiply dividend0 * dividend1
4808         long d0_hi = dividend0 >>> 32;
4809         long d0_lo = dividend0 & LONG_MASK;
4810         long d1_hi = dividend1 >>> 32;
4811         long d1_lo = dividend1 & LONG_MASK;
4812         long product = d0_lo * d1_lo;
4813         long d0 = product & LONG_MASK;
4814         long d1 = product >>> 32;
4815         product = d0_hi * d1_lo + d1;
4816         d1 = product & LONG_MASK;
4817         long d2 = product >>> 32;
4818         product = d0_lo * d1_hi + d1;
4819         d1 = product & LONG_MASK;
4820         d2 += product >>> 32;
4821         long d3 = d2>>>32;
4822         d2 &= LONG_MASK;
4823         product = d0_hi*d1_hi + d2;
4824         d2 = product & LONG_MASK;
4825         d3 = ((product>>>32) + d3) & LONG_MASK;
4826         final long dividendHi = make64(d3,d2);
4827         final long dividendLo = make64(d1,d0);
4828         // divide
4829         return divideAndRound128(dividendHi, dividendLo, divisor, qsign, scale, roundingMode, preferredScale);
4830     }
4831 
4832     private static final long DIV_NUM_BASE = (1L<<32); // Number base (32 bits).
4833 
4834     /*
4835      * divideAndRound 128-bit value by long divisor.
4836      * returns null if quotient can't fit into long value;
4837      * Specialized version of Knuth's division
4838      */
4839     private static BigDecimal divideAndRound128(final long dividendHi, final long dividendLo, long divisor, int sign,
4840                                                 int scale, int roundingMode, int preferredScale) {
4841         if (dividendHi >= divisor) {
4842             return null;
4843         }
4844 
4845         final int shift = Long.numberOfLeadingZeros(divisor);
4846         divisor <<= shift;
4847 
4848         final long v1 = divisor >>> 32;
4849         final long v0 = divisor & LONG_MASK;
4850 
4851         long tmp = dividendLo << shift;
4852         long u1 = tmp >>> 32;
4853         long u0 = tmp & LONG_MASK;
4854 
4855         tmp = (dividendHi << shift) | (dividendLo >>> 64 - shift);
4856         long u2 = tmp & LONG_MASK;
4857         long q1, r_tmp;
4858         if (v1 == 1) {
4859             q1 = tmp;
4860             r_tmp = 0;
4861         } else if (tmp >= 0) {
4862             q1 = tmp / v1;
4863             r_tmp = tmp - q1 * v1;
4864         } else {
4865             long[] rq = divRemNegativeLong(tmp, v1);
4866             q1 = rq[1];
4867             r_tmp = rq[0];
4868         }
4869 
4870         while(q1 >= DIV_NUM_BASE || unsignedLongCompare(q1*v0, make64(r_tmp, u1))) {
4871             q1--;
4872             r_tmp += v1;
4873             if (r_tmp >= DIV_NUM_BASE)
4874                 break;
4875         }
4876 
4877         tmp = mulsub(u2,u1,v1,v0,q1);
4878         u1 = tmp & LONG_MASK;
4879         long q0;
4880         if (v1 == 1) {
4881             q0 = tmp;
4882             r_tmp = 0;
4883         } else if (tmp >= 0) {
4884             q0 = tmp / v1;
4885             r_tmp = tmp - q0 * v1;
4886         } else {
4887             long[] rq = divRemNegativeLong(tmp, v1);
4888             q0 = rq[1];
4889             r_tmp = rq[0];
4890         }
4891 
4892         while(q0 >= DIV_NUM_BASE || unsignedLongCompare(q0*v0,make64(r_tmp,u0))) {
4893             q0--;
4894             r_tmp += v1;
4895             if (r_tmp >= DIV_NUM_BASE)
4896                 break;
4897         }
4898 
4899         if((int)q1 < 0) {
4900             // result (which is positive and unsigned here)
4901             // can't fit into long due to sign bit is used for value
4902             MutableBigInteger mq = new MutableBigInteger(new int[]{(int)q1, (int)q0});
4903             if (roundingMode == ROUND_DOWN && scale == preferredScale) {
4904                 return mq.toBigDecimal(sign, scale);
4905             }
4906             long r = mulsub(u1, u0, v1, v0, q0) >>> shift;
4907             if (r != 0) {
4908                 if(needIncrement(divisor >>> shift, roundingMode, sign, mq, r)){
4909                     mq.add(MutableBigInteger.ONE);
4910                 }
4911                 return mq.toBigDecimal(sign, scale);
4912             } else {
4913                 if (preferredScale != scale) {
4914                     BigInteger intVal =  mq.toBigInteger(sign);
4915                     return createAndStripZerosToMatchScale(intVal,scale, preferredScale);
4916                 } else {
4917                     return mq.toBigDecimal(sign, scale);
4918                 }
4919             }
4920         }
4921 
4922         long q = make64(q1,q0);
4923         q*=sign;
4924 
4925         if (roundingMode == ROUND_DOWN && scale == preferredScale)
4926             return valueOf(q, scale);
4927 
4928         long r = mulsub(u1, u0, v1, v0, q0) >>> shift;
4929         if (r != 0) {
4930             boolean increment = needIncrement(divisor >>> shift, roundingMode, sign, q, r);
4931             return valueOf((increment ? q + sign : q), scale);
4932         } else {
4933             if (preferredScale != scale) {
4934                 return createAndStripZerosToMatchScale(q, scale, preferredScale);
4935             } else {
4936                 return valueOf(q, scale);
4937             }
4938         }
4939     }
4940 
4941     /*
4942      * calculate divideAndRound for ldividend*10^raise / divisor
4943      * when abs(dividend)==abs(divisor);
4944      */
4945     private static BigDecimal roundedTenPower(int qsign, int raise, int scale, int preferredScale) {
4946         if (scale > preferredScale) {
4947             int diff = scale - preferredScale;
4948             if(diff < raise) {
4949                 return scaledTenPow(raise - diff, qsign, preferredScale);
4950             } else {
4951                 return valueOf(qsign,scale-raise);
4952             }
4953         } else {
4954             return scaledTenPow(raise, qsign, scale);
4955         }
4956     }
4957 
4958     static BigDecimal scaledTenPow(int n, int sign, int scale) {
4959         if (n < LONG_TEN_POWERS_TABLE.length)
4960             return valueOf(sign*LONG_TEN_POWERS_TABLE[n],scale);
4961         else {
4962             BigInteger unscaledVal = bigTenToThe(n);
4963             if(sign==-1) {
4964                 unscaledVal = unscaledVal.negate();
4965             }
4966             return new BigDecimal(unscaledVal, INFLATED, scale, n+1);
4967         }
4968     }
4969 
4970     /**
4971      * Calculate the quotient and remainder of dividing a negative long by
4972      * another long.
4973      *
4974      * @param n the numerator; must be negative
4975      * @param d the denominator; must not be unity
4976      * @return a two-element {@long} array with the remainder and quotient in
4977      *         the initial and final elements, respectively
4978      */
4979     private static long[] divRemNegativeLong(long n, long d) {
4980         assert n < 0 : "Non-negative numerator " + n;
4981         assert d != 1 : "Unity denominator";
4982 
4983         // Approximate the quotient and remainder
4984         long q = (n >>> 1) / (d >>> 1);
4985         long r = n - q * d;
4986 
4987         // Correct the approximation
4988         while (r < 0) {
4989             r += d;
4990             q--;
4991         }
4992         while (r >= d) {
4993             r -= d;
4994             q++;
4995         }
4996 
4997         // n - q*d == r && 0 <= r < d, hence we're done.
4998         return new long[] {r, q};
4999     }
5000 
5001     private static long make64(long hi, long lo) {
5002         return hi<<32 | lo;
5003     }
5004 
5005     private static long mulsub(long u1, long u0, final long v1, final long v0, long q0) {
5006         long tmp = u0 - q0*v0;
5007         return make64(u1 + (tmp>>>32) - q0*v1,tmp & LONG_MASK);
5008     }
5009 
5010     private static boolean unsignedLongCompare(long one, long two) {
5011         return (one+Long.MIN_VALUE) > (two+Long.MIN_VALUE);
5012     }
5013 
5014     private static boolean unsignedLongCompareEq(long one, long two) {
5015         return (one+Long.MIN_VALUE) >= (two+Long.MIN_VALUE);
5016     }
5017 
5018 
5019     // Compare Normalize dividend & divisor so that both fall into [0.1, 0.999...]
5020     private static int compareMagnitudeNormalized(long xs, int xscale, long ys, int yscale) {
5021         // assert xs!=0 && ys!=0
5022         int sdiff = xscale - yscale;
5023         if (sdiff != 0) {
5024             if (sdiff < 0) {
5025                 xs = longMultiplyPowerTen(xs, -sdiff);
5026             } else { // sdiff > 0
5027                 ys = longMultiplyPowerTen(ys, sdiff);
5028             }
5029         }
5030         if (xs != INFLATED)
5031             return (ys != INFLATED) ? longCompareMagnitude(xs, ys) : -1;
5032         else
5033             return 1;
5034     }
5035 
5036     // Compare Normalize dividend & divisor so that both fall into [0.1, 0.999...]
5037     private static int compareMagnitudeNormalized(long xs, int xscale, BigInteger ys, int yscale) {
5038         // assert "ys can't be represented as long"
5039         if (xs == 0)
5040             return -1;
5041         int sdiff = xscale - yscale;
5042         if (sdiff < 0) {
5043             if (longMultiplyPowerTen(xs, -sdiff) == INFLATED ) {
5044                 return bigMultiplyPowerTen(xs, -sdiff).compareMagnitude(ys);
5045             }
5046         }
5047         return -1;
5048     }
5049 
5050     // Compare Normalize dividend & divisor so that both fall into [0.1, 0.999...]
5051     private static int compareMagnitudeNormalized(BigInteger xs, int xscale, BigInteger ys, int yscale) {
5052         int sdiff = xscale - yscale;
5053         if (sdiff < 0) {
5054             return bigMultiplyPowerTen(xs, -sdiff).compareMagnitude(ys);
5055         } else { // sdiff >= 0
5056             return xs.compareMagnitude(bigMultiplyPowerTen(ys, sdiff));
5057         }
5058     }
5059 
5060     private static long multiply(long x, long y){
5061                 long product = x * y;
5062         long ax = Math.abs(x);
5063         long ay = Math.abs(y);
5064         if (((ax | ay) >>> 31 == 0) || (y == 0) || (product / y == x)){
5065                         return product;
5066                 }
5067         return INFLATED;
5068     }
5069 
5070     private static BigDecimal multiply(long x, long y, int scale) {
5071         long product = multiply(x, y);
5072         if(product!=INFLATED) {
5073             return valueOf(product,scale);
5074         }
5075         return new BigDecimal(BigInteger.valueOf(x).multiply(y),INFLATED,scale,0);
5076     }
5077 
5078     private static BigDecimal multiply(long x, BigInteger y, int scale) {
5079         if(x==0) {
5080             return zeroValueOf(scale);
5081         }
5082         return new BigDecimal(y.multiply(x),INFLATED,scale,0);
5083     }
5084 
5085     private static BigDecimal multiply(BigInteger x, BigInteger y, int scale) {
5086         return new BigDecimal(x.multiply(y),INFLATED,scale,0);
5087     }
5088 
5089     /**
5090      * Multiplies two long values and rounds according {@code MathContext}
5091      */
5092     private static BigDecimal multiplyAndRound(long x, long y, int scale, MathContext mc) {
5093         long product = multiply(x, y);
5094         if(product!=INFLATED) {
5095             return doRound(product, scale, mc);
5096         }
5097         // attempt to do it in 128 bits
5098         int rsign = 1;
5099         if(x < 0) {
5100             x = -x;
5101             rsign = -1;
5102         }
5103         if(y < 0) {
5104             y = -y;
5105             rsign *= -1;
5106         }
5107         // multiply dividend0 * dividend1
5108         long m0_hi = x >>> 32;
5109         long m0_lo = x & LONG_MASK;
5110         long m1_hi = y >>> 32;
5111         long m1_lo = y & LONG_MASK;
5112         product = m0_lo * m1_lo;
5113         long m0 = product & LONG_MASK;
5114         long m1 = product >>> 32;
5115         product = m0_hi * m1_lo + m1;
5116         m1 = product & LONG_MASK;
5117         long m2 = product >>> 32;
5118         product = m0_lo * m1_hi + m1;
5119         m1 = product & LONG_MASK;
5120         m2 += product >>> 32;
5121         long m3 = m2>>>32;
5122         m2 &= LONG_MASK;
5123         product = m0_hi*m1_hi + m2;
5124         m2 = product & LONG_MASK;
5125         m3 = ((product>>>32) + m3) & LONG_MASK;
5126         final long mHi = make64(m3,m2);
5127         final long mLo = make64(m1,m0);
5128         BigDecimal res = doRound128(mHi, mLo, rsign, scale, mc);
5129         if(res!=null) {
5130             return res;
5131         }
5132         res = new BigDecimal(BigInteger.valueOf(x).multiply(y*rsign), INFLATED, scale, 0);
5133         return doRound(res,mc);
5134     }
5135 
5136     private static BigDecimal multiplyAndRound(long x, BigInteger y, int scale, MathContext mc) {
5137         if(x==0) {
5138             return zeroValueOf(scale);
5139         }
5140         return doRound(y.multiply(x), scale, mc);
5141     }
5142 
5143     private static BigDecimal multiplyAndRound(BigInteger x, BigInteger y, int scale, MathContext mc) {
5144         return doRound(x.multiply(y), scale, mc);
5145     }
5146 
5147     /**
5148      * rounds 128-bit value according {@code MathContext}
5149      * returns null if result can't be repsented as compact BigDecimal.
5150      */
5151     private static BigDecimal doRound128(long hi, long lo, int sign, int scale, MathContext mc) {
5152         int mcp = mc.precision;
5153         int drop;
5154         BigDecimal res = null;
5155         if(((drop = precision(hi, lo) - mcp) > 0)&&(drop<LONG_TEN_POWERS_TABLE.length)) {
5156             scale = checkScaleNonZero((long)scale - drop);
5157             res = divideAndRound128(hi, lo, LONG_TEN_POWERS_TABLE[drop], sign, scale, mc.roundingMode.oldMode, scale);
5158         }
5159         if(res!=null) {
5160             return doRound(res,mc);
5161         }
5162         return null;
5163     }
5164 
5165     private static final long[][] LONGLONG_TEN_POWERS_TABLE = {
5166         {   0L, 0x8AC7230489E80000L },  //10^19
5167         {       0x5L, 0x6bc75e2d63100000L },  //10^20
5168         {       0x36L, 0x35c9adc5dea00000L },  //10^21
5169         {       0x21eL, 0x19e0c9bab2400000L  },  //10^22
5170         {       0x152dL, 0x02c7e14af6800000L  },  //10^23
5171         {       0xd3c2L, 0x1bcecceda1000000L  },  //10^24
5172         {       0x84595L, 0x161401484a000000L  },  //10^25
5173         {       0x52b7d2L, 0xdcc80cd2e4000000L  },  //10^26
5174         {       0x33b2e3cL, 0x9fd0803ce8000000L  },  //10^27
5175         {       0x204fce5eL, 0x3e25026110000000L  },  //10^28
5176         {       0x1431e0faeL, 0x6d7217caa0000000L  },  //10^29
5177         {       0xc9f2c9cd0L, 0x4674edea40000000L  },  //10^30
5178         {       0x7e37be2022L, 0xc0914b2680000000L  },  //10^31
5179         {       0x4ee2d6d415bL, 0x85acef8100000000L  },  //10^32
5180         {       0x314dc6448d93L, 0x38c15b0a00000000L  },  //10^33
5181         {       0x1ed09bead87c0L, 0x378d8e6400000000L  },  //10^34
5182         {       0x13426172c74d82L, 0x2b878fe800000000L  },  //10^35
5183         {       0xc097ce7bc90715L, 0xb34b9f1000000000L  },  //10^36
5184         {       0x785ee10d5da46d9L, 0x00f436a000000000L  },  //10^37
5185         {       0x4b3b4ca85a86c47aL, 0x098a224000000000L  },  //10^38
5186     };
5187 
5188     /*
5189      * returns precision of 128-bit value
5190      */
5191     private static int precision(long hi, long lo){
5192         if(hi==0) {
5193             if(lo>=0) {
5194                 return longDigitLength(lo);
5195             }
5196             return (unsignedLongCompareEq(lo, LONGLONG_TEN_POWERS_TABLE[0][1])) ? 20 : 19;
5197             // 0x8AC7230489E80000L  = unsigned 2^19
5198         }
5199         int r = ((128 - Long.numberOfLeadingZeros(hi) + 1) * 1233) >>> 12;
5200         int idx = r-19;
5201         return (idx >= LONGLONG_TEN_POWERS_TABLE.length || longLongCompareMagnitude(hi, lo,
5202                                                                                     LONGLONG_TEN_POWERS_TABLE[idx][0], LONGLONG_TEN_POWERS_TABLE[idx][1])) ? r : r + 1;
5203     }
5204 
5205     /*
5206      * returns true if 128 bit number <hi0,lo0> is less than <hi1,lo1>
5207      * hi0 & hi1 should be non-negative
5208      */
5209     private static boolean longLongCompareMagnitude(long hi0, long lo0, long hi1, long lo1) {
5210         if(hi0!=hi1) {
5211             return hi0<hi1;
5212         }
5213         return (lo0+Long.MIN_VALUE) <(lo1+Long.MIN_VALUE);
5214     }
5215 
5216     private static BigDecimal divide(long dividend, int dividendScale, long divisor, int divisorScale, int scale, int roundingMode) {
5217         if (checkScale(dividend,(long)scale + divisorScale) > dividendScale) {
5218             int newScale = scale + divisorScale;
5219             int raise = newScale - dividendScale;
5220             if(raise<LONG_TEN_POWERS_TABLE.length) {
5221                 long xs = dividend;
5222                 if ((xs = longMultiplyPowerTen(xs, raise)) != INFLATED) {
5223                     return divideAndRound(xs, divisor, scale, roundingMode, scale);
5224                 }
5225                 BigDecimal q = multiplyDivideAndRound(LONG_TEN_POWERS_TABLE[raise], dividend, divisor, scale, roundingMode, scale);
5226                 if(q!=null) {
5227                     return q;
5228                 }
5229             }
5230             BigInteger scaledDividend = bigMultiplyPowerTen(dividend, raise);
5231             return divideAndRound(scaledDividend, divisor, scale, roundingMode, scale);
5232         } else {
5233             int newScale = checkScale(divisor,(long)dividendScale - scale);
5234             int raise = newScale - divisorScale;
5235             if(raise<LONG_TEN_POWERS_TABLE.length) {
5236                 long ys = divisor;
5237                 if ((ys = longMultiplyPowerTen(ys, raise)) != INFLATED) {
5238                     return divideAndRound(dividend, ys, scale, roundingMode, scale);
5239                 }
5240             }
5241             BigInteger scaledDivisor = bigMultiplyPowerTen(divisor, raise);
5242             return divideAndRound(BigInteger.valueOf(dividend), scaledDivisor, scale, roundingMode, scale);
5243         }
5244     }
5245 
5246     private static BigDecimal divide(BigInteger dividend, int dividendScale, long divisor, int divisorScale, int scale, int roundingMode) {
5247         if (checkScale(dividend,(long)scale + divisorScale) > dividendScale) {
5248             int newScale = scale + divisorScale;
5249             int raise = newScale - dividendScale;
5250             BigInteger scaledDividend = bigMultiplyPowerTen(dividend, raise);
5251             return divideAndRound(scaledDividend, divisor, scale, roundingMode, scale);
5252         } else {
5253             int newScale = checkScale(divisor,(long)dividendScale - scale);
5254             int raise = newScale - divisorScale;
5255             if(raise<LONG_TEN_POWERS_TABLE.length) {
5256                 long ys = divisor;
5257                 if ((ys = longMultiplyPowerTen(ys, raise)) != INFLATED) {
5258                     return divideAndRound(dividend, ys, scale, roundingMode, scale);
5259                 }
5260             }
5261             BigInteger scaledDivisor = bigMultiplyPowerTen(divisor, raise);
5262             return divideAndRound(dividend, scaledDivisor, scale, roundingMode, scale);
5263         }
5264     }
5265 
5266     private static BigDecimal divide(long dividend, int dividendScale, BigInteger divisor, int divisorScale, int scale, int roundingMode) {
5267         if (checkScale(dividend,(long)scale + divisorScale) > dividendScale) {
5268             int newScale = scale + divisorScale;
5269             int raise = newScale - dividendScale;
5270             BigInteger scaledDividend = bigMultiplyPowerTen(dividend, raise);
5271             return divideAndRound(scaledDividend, divisor, scale, roundingMode, scale);
5272         } else {
5273             int newScale = checkScale(divisor,(long)dividendScale - scale);
5274             int raise = newScale - divisorScale;
5275             BigInteger scaledDivisor = bigMultiplyPowerTen(divisor, raise);
5276             return divideAndRound(BigInteger.valueOf(dividend), scaledDivisor, scale, roundingMode, scale);
5277         }
5278     }
5279 
5280     private static BigDecimal divide(BigInteger dividend, int dividendScale, BigInteger divisor, int divisorScale, int scale, int roundingMode) {
5281         if (checkScale(dividend,(long)scale + divisorScale) > dividendScale) {
5282             int newScale = scale + divisorScale;
5283             int raise = newScale - dividendScale;
5284             BigInteger scaledDividend = bigMultiplyPowerTen(dividend, raise);
5285             return divideAndRound(scaledDividend, divisor, scale, roundingMode, scale);
5286         } else {
5287             int newScale = checkScale(divisor,(long)dividendScale - scale);
5288             int raise = newScale - divisorScale;
5289             BigInteger scaledDivisor = bigMultiplyPowerTen(divisor, raise);
5290             return divideAndRound(dividend, scaledDivisor, scale, roundingMode, scale);
5291         }
5292     }
5293 
5294 }