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