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