1/*
2 *  Licensed to the Apache Software Foundation (ASF) under one or more
3 *  contributor license agreements.  See the NOTICE file distributed with
4 *  this work for additional information regarding copyright ownership.
5 *  The ASF licenses this file to You under the Apache License, Version 2.0
6 *  (the "License"); you may not use this file except in compliance with
7 *  the License.  You may obtain a copy of the License at
8 *
9 *     http://www.apache.org/licenses/LICENSE-2.0
10 *
11 *  Unless required by applicable law or agreed to in writing, software
12 *  distributed under the License is distributed on an "AS IS" BASIS,
13 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 *  See the License for the specific language governing permissions and
15 *  limitations under the License.
16 */
17
18package java.math;
19
20import java.io.IOException;
21import java.io.ObjectInputStream;
22import java.io.ObjectOutputStream;
23import java.io.Serializable;
24import java.util.Arrays;
25import libcore.math.MathUtils;
26
27/**
28 * This class represents immutable integer numbers of arbitrary length. Large
29 * numbers are typically used in security applications and therefore BigIntegers
30 * offer dedicated functionality like the generation of large prime numbers or
31 * the computation of modular inverse.
32 * <p>
33 * Since the class was modeled to offer all the functionality as the {@link Integer}
34 * class does, it provides even methods that operate bitwise on a two's
35 * complement representation of large integers. Note however that the
36 * implementations favors an internal representation where magnitude and sign
37 * are treated separately. Hence such operations are inefficient and should be
38 * discouraged. In simple words: Do NOT implement any bit fields based on
39 * BigInteger.
40 */
41public class BigDecimal extends Number implements Comparable<BigDecimal>, Serializable {
42
43    /**
44     * Rounding mode where positive values are rounded towards positive infinity
45     * and negative values towards negative infinity.
46     *
47     * @see RoundingMode#UP
48     */
49    public static final int ROUND_UP = 0;
50
51    /**
52     * Rounding mode where the values are rounded towards zero.
53     *
54     * @see RoundingMode#DOWN
55     */
56    public static final int ROUND_DOWN = 1;
57
58    /**
59     * Rounding mode to round towards positive infinity. For positive values
60     * this rounding mode behaves as {@link #ROUND_UP}, for negative values as
61     * {@link #ROUND_DOWN}.
62     *
63     * @see RoundingMode#CEILING
64     */
65    public static final int ROUND_CEILING = 2;
66
67    /**
68     * Rounding mode to round towards negative infinity. For positive values
69     * this rounding mode behaves as {@link #ROUND_DOWN}, for negative values as
70     * {@link #ROUND_UP}.
71     *
72     * @see RoundingMode#FLOOR
73     */
74    public static final int ROUND_FLOOR = 3;
75
76    /**
77     * Rounding mode where values are rounded towards the nearest neighbor.
78     * Ties are broken by rounding up.
79     *
80     * @see RoundingMode#HALF_UP
81     */
82    public static final int ROUND_HALF_UP = 4;
83
84    /**
85     * Rounding mode where values are rounded towards the nearest neighbor.
86     * Ties are broken by rounding down.
87     *
88     * @see RoundingMode#HALF_DOWN
89     */
90    public static final int ROUND_HALF_DOWN = 5;
91
92    /**
93     * Rounding mode where values are rounded towards the nearest neighbor.
94     * Ties are broken by rounding to the even neighbor.
95     *
96     * @see RoundingMode#HALF_EVEN
97     */
98    public static final int ROUND_HALF_EVEN = 6;
99
100    /**
101     * Rounding mode where the rounding operations throws an {@code
102     * ArithmeticException} for the case that rounding is necessary, i.e. for
103     * the case that the value cannot be represented exactly.
104     *
105     * @see RoundingMode#UNNECESSARY
106     */
107    public static final int ROUND_UNNECESSARY = 7;
108
109    /** This is the serialVersionUID used by the sun implementation. */
110    private static final long serialVersionUID = 6108874887143696463L;
111
112    /** The double closest to {@code Log10(2)}. */
113    private static final double LOG10_2 = 0.3010299956639812;
114
115    /** The <code>String</code> representation is cached. */
116    private transient String toStringImage = null;
117
118    /** Cache for the hash code. */
119    private transient int hashCode = 0;
120
121    /**
122     * An array with powers of five that fit in the type <code>long</code>
123     * (<code>5^0,5^1,...,5^27</code>).
124     */
125    private static final BigInteger[] FIVE_POW;
126
127    /**
128     * An array with powers of ten that fit in the type <code>long</code>
129     * (<code>10^0,10^1,...,10^18</code>).
130     */
131    private static final BigInteger[] TEN_POW;
132
133    private static final long[] LONG_FIVE_POW = new long[]
134    {   1L,
135        5L,
136        25L,
137        125L,
138        625L,
139        3125L,
140        15625L,
141        78125L,
142        390625L,
143        1953125L,
144        9765625L,
145        48828125L,
146        244140625L,
147        1220703125L,
148        6103515625L,
149        30517578125L,
150        152587890625L,
151        762939453125L,
152        3814697265625L,
153        19073486328125L,
154        95367431640625L,
155        476837158203125L,
156        2384185791015625L,
157        11920928955078125L,
158        59604644775390625L,
159        298023223876953125L,
160        1490116119384765625L,
161        7450580596923828125L, };
162
163    private static final int[] LONG_FIVE_POW_BIT_LENGTH = new int[LONG_FIVE_POW.length];
164    private static final int[] LONG_POWERS_OF_TEN_BIT_LENGTH = new int[MathUtils.LONG_POWERS_OF_TEN.length];
165
166    private static final int BI_SCALED_BY_ZERO_LENGTH = 11;
167
168    /**
169     * An array with the first <code>BigInteger</code> scaled by zero.
170     * (<code>[0,0],[1,0],...,[10,0]</code>).
171     */
172    private static final BigDecimal[] BI_SCALED_BY_ZERO = new BigDecimal[BI_SCALED_BY_ZERO_LENGTH];
173
174    /**
175     * An array with the zero number scaled by the first positive scales.
176     * (<code>0*10^0, 0*10^1, ..., 0*10^10</code>).
177     */
178    private static final BigDecimal[] ZERO_SCALED_BY = new BigDecimal[11];
179
180    /** An array filled with characters <code>'0'</code>. */
181    private static final char[] CH_ZEROS = new char[100];
182
183    static {
184        Arrays.fill(CH_ZEROS, '0');
185
186        for (int i = 0; i < ZERO_SCALED_BY.length; ++i) {
187            BI_SCALED_BY_ZERO[i] = new BigDecimal(i, 0);
188            ZERO_SCALED_BY[i] = new BigDecimal(0, i);
189        }
190        for (int i = 0; i < LONG_FIVE_POW_BIT_LENGTH.length; ++i) {
191            LONG_FIVE_POW_BIT_LENGTH[i] = bitLength(LONG_FIVE_POW[i]);
192        }
193        for (int i = 0; i < LONG_POWERS_OF_TEN_BIT_LENGTH.length; ++i) {
194            LONG_POWERS_OF_TEN_BIT_LENGTH[i] = bitLength(MathUtils.LONG_POWERS_OF_TEN[i]);
195        }
196
197        // Taking the references of useful powers.
198        TEN_POW = Multiplication.bigTenPows;
199        FIVE_POW = Multiplication.bigFivePows;
200    }
201
202    /**
203     * The constant zero as a {@code BigDecimal}.
204     */
205    public static final BigDecimal ZERO = new BigDecimal(0, 0);
206
207    /**
208     * The constant one as a {@code BigDecimal}.
209     */
210    public static final BigDecimal ONE = new BigDecimal(1, 0);
211
212    /**
213     * The constant ten as a {@code BigDecimal}.
214     */
215    public static final BigDecimal TEN = new BigDecimal(10, 0);
216
217    /**
218     * The arbitrary precision integer (unscaled value) in the internal
219     * representation of {@code BigDecimal}.
220     */
221    private BigInteger intVal;
222
223    private transient int bitLength;
224
225    private transient long smallValue;
226
227    /**
228     * The 32-bit integer scale in the internal representation of {@code BigDecimal}.
229     */
230    private int scale;
231
232    /**
233     * Represent the number of decimal digits in the unscaled value. This
234     * precision is calculated the first time, and used in the following calls
235     * of method <code>precision()</code>. Note that some call to the private
236     * method <code>inplaceRound()</code> could update this field.
237     *
238     * @see #precision()
239     * @see #inplaceRound(MathContext)
240     */
241    private transient int precision = 0;
242
243    private BigDecimal(long smallValue, int scale){
244        this.smallValue = smallValue;
245        this.scale = scale;
246        this.bitLength = bitLength(smallValue);
247    }
248
249    private BigDecimal(int smallValue, int scale){
250        this.smallValue = smallValue;
251        this.scale = scale;
252        this.bitLength = bitLength(smallValue);
253    }
254
255    /**
256     * Constructs a new {@code BigDecimal} instance from a string representation
257     * given as a character array.
258     *
259     * @param in
260     *            array of characters containing the string representation of
261     *            this {@code BigDecimal}.
262     * @param offset
263     *            first index to be copied.
264     * @param len
265     *            number of characters to be used.
266     * @throws NumberFormatException
267     *             if {@code offset < 0 || len <= 0 || offset+len-1 < 0 ||
268     *             offset+len-1 >= in.length}, or if {@code in} does not
269     *             contain a valid string representation of a big decimal.
270     */
271    public BigDecimal(char[] in, int offset, int len) {
272        int begin = offset; // first index to be copied
273        int last = offset + (len - 1); // last index to be copied
274        String scaleString; // buffer for scale
275        StringBuilder unscaledBuffer; // buffer for unscaled value
276        long newScale; // the new scale
277
278        if (in == null) {
279            throw new NullPointerException("in == null");
280        }
281        if ((last >= in.length) || (offset < 0) || (len <= 0) || (last < 0)) {
282            throw new NumberFormatException("Bad offset/length: offset=" + offset +
283                    " len=" + len + " in.length=" + in.length);
284        }
285        unscaledBuffer = new StringBuilder(len);
286        int bufLength = 0;
287        // To skip a possible '+' symbol
288        if ((offset <= last) && (in[offset] == '+')) {
289            offset++;
290            begin++;
291        }
292        int counter = 0;
293        boolean wasNonZero = false;
294        // Accumulating all digits until a possible decimal point
295        for (; (offset <= last) && (in[offset] != '.') && (in[offset] != 'e') && (in[offset] != 'E'); offset++) {
296            if (!wasNonZero) {
297                if (in[offset] == '0') {
298                    counter++;
299                } else {
300                    wasNonZero = true;
301                }
302            }
303
304        }
305        unscaledBuffer.append(in, begin, offset - begin);
306        bufLength += offset - begin;
307        // A decimal point was found
308        if ((offset <= last) && (in[offset] == '.')) {
309            offset++;
310            // Accumulating all digits until a possible exponent
311            begin = offset;
312            for (; (offset <= last) && (in[offset] != 'e')
313            && (in[offset] != 'E'); offset++) {
314                if (!wasNonZero) {
315                    if (in[offset] == '0') {
316                        counter++;
317                    } else {
318                        wasNonZero = true;
319                    }
320                }
321            }
322            scale = offset - begin;
323            bufLength +=scale;
324            unscaledBuffer.append(in, begin, scale);
325        } else {
326            scale = 0;
327        }
328        // An exponent was found
329        if ((offset <= last) && ((in[offset] == 'e') || (in[offset] == 'E'))) {
330            offset++;
331            // Checking for a possible sign of scale
332            begin = offset;
333            if ((offset <= last) && (in[offset] == '+')) {
334                offset++;
335                if ((offset <= last) && (in[offset] != '-')) {
336                    begin++;
337                }
338            }
339            // Accumulating all remaining digits
340            scaleString = String.valueOf(in, begin, last + 1 - begin);
341            // Checking if the scale is defined
342            newScale = (long)scale - Integer.parseInt(scaleString);
343            scale = (int)newScale;
344            if (newScale != scale) {
345                throw new NumberFormatException("Scale out of range");
346            }
347        }
348        // Parsing the unscaled value
349        if (bufLength < 19) {
350            smallValue = Long.parseLong(unscaledBuffer.toString());
351            bitLength = bitLength(smallValue);
352        } else {
353            setUnscaledValue(new BigInteger(unscaledBuffer.toString()));
354        }
355        precision = unscaledBuffer.length() - counter;
356        if (unscaledBuffer.charAt(0) == '-') {
357            precision --;
358        }
359    }
360
361    /**
362     * Constructs a new {@code BigDecimal} instance from a string representation
363     * given as a character array.
364     *
365     * @param in
366     *            array of characters containing the string representation of
367     *            this {@code BigDecimal}.
368     * @param offset
369     *            first index to be copied.
370     * @param len
371     *            number of characters to be used.
372     * @param mc
373     *            rounding mode and precision for the result of this operation.
374     * @throws NumberFormatException
375     *             if {@code offset < 0 || len <= 0 || offset+len-1 < 0 ||
376     *             offset+len-1 >= in.length}, or if {@code in} does not
377     *             contain a valid string representation of a big decimal.
378     * @throws ArithmeticException
379     *             if {@code mc.precision > 0} and {@code mc.roundingMode ==
380     *             UNNECESSARY} and the new big decimal cannot be represented
381     *             within the given precision without rounding.
382     */
383    public BigDecimal(char[] in, int offset, int len, MathContext mc) {
384        this(in, offset, len);
385        inplaceRound(mc);
386    }
387
388    /**
389     * Constructs a new {@code BigDecimal} instance from a string representation
390     * given as a character array.
391     *
392     * @param in
393     *            array of characters containing the string representation of
394     *            this {@code BigDecimal}.
395     * @throws NumberFormatException
396     *             if {@code in} does not contain a valid string representation
397     *             of a big decimal.
398     */
399    public BigDecimal(char[] in) {
400        this(in, 0, in.length);
401    }
402
403    /**
404     * Constructs a new {@code BigDecimal} instance from a string representation
405     * given as a character array. The result is rounded according to the
406     * specified math context.
407     *
408     * @param in
409     *            array of characters containing the string representation of
410     *            this {@code BigDecimal}.
411     * @param mc
412     *            rounding mode and precision for the result of this operation.
413     * @throws NumberFormatException
414     *             if {@code in} does not contain a valid string representation
415     *             of a big decimal.
416     * @throws ArithmeticException
417     *             if {@code mc.precision > 0} and {@code mc.roundingMode ==
418     *             UNNECESSARY} and the new big decimal cannot be represented
419     *             within the given precision without rounding.
420     */
421    public BigDecimal(char[] in, MathContext mc) {
422        this(in, 0, in.length);
423        inplaceRound(mc);
424    }
425
426    /**
427     * Constructs a new {@code BigDecimal} instance from a string
428     * representation.
429     *
430     * @param val
431     *            string containing the string representation of this {@code
432     *            BigDecimal}.
433     * @throws NumberFormatException
434     *             if {@code val} does not contain a valid string representation
435     *             of a big decimal.
436     */
437    public BigDecimal(String val) {
438        this(val.toCharArray(), 0, val.length());
439    }
440
441    /**
442     * Constructs a new {@code BigDecimal} instance from a string
443     * representation. The result is rounded according to the specified math
444     * context.
445     *
446     * @param val
447     *            string containing the string representation of this {@code
448     *            BigDecimal}.
449     * @param mc
450     *            rounding mode and precision for the result of this operation.
451     * @throws NumberFormatException
452     *             if {@code val} does not contain a valid string representation
453     *             of a big decimal.
454     * @throws ArithmeticException
455     *             if {@code mc.precision > 0} and {@code mc.roundingMode ==
456     *             UNNECESSARY} and the new big decimal cannot be represented
457     *             within the given precision without rounding.
458     */
459    public BigDecimal(String val, MathContext mc) {
460        this(val.toCharArray(), 0, val.length());
461        inplaceRound(mc);
462    }
463
464    /**
465     * Constructs a new {@code BigDecimal} instance from the 64bit double
466     * {@code val}. The constructed big decimal is equivalent to the given
467     * double. For example, {@code new BigDecimal(0.1)} is equal to {@code
468     * 0.1000000000000000055511151231257827021181583404541015625}. This happens
469     * as {@code 0.1} cannot be represented exactly in binary.
470     * <p>
471     * To generate a big decimal instance which is equivalent to {@code 0.1} use
472     * the {@code BigDecimal(String)} constructor.
473     *
474     * @param val
475     *            double value to be converted to a {@code BigDecimal} instance.
476     * @throws NumberFormatException
477     *             if {@code val} is infinity or not a number.
478     */
479    public BigDecimal(double val) {
480        if (Double.isInfinite(val) || Double.isNaN(val)) {
481            throw new NumberFormatException("Infinity or NaN: " + val);
482        }
483        long bits = Double.doubleToLongBits(val); // IEEE-754
484        long mantissa;
485        int trailingZeros;
486        // Extracting the exponent, note that the bias is 1023
487        scale = 1075 - (int)((bits >> 52) & 0x7FFL);
488        // Extracting the 52 bits of the mantissa.
489        mantissa = (scale == 1075) ? (bits & 0xFFFFFFFFFFFFFL) << 1
490                : (bits & 0xFFFFFFFFFFFFFL) | 0x10000000000000L;
491        if (mantissa == 0) {
492            scale = 0;
493            precision = 1;
494        }
495        // To simplify all factors '2' in the mantissa
496        if (scale > 0) {
497            trailingZeros = Math.min(scale, Long.numberOfTrailingZeros(mantissa));
498            mantissa >>>= trailingZeros;
499            scale -= trailingZeros;
500        }
501        // Calculating the new unscaled value and the new scale
502        if((bits >> 63) != 0) {
503            mantissa = -mantissa;
504        }
505        int mantissaBits = bitLength(mantissa);
506        if (scale < 0) {
507            bitLength = mantissaBits == 0 ? 0 : mantissaBits - scale;
508            if(bitLength < 64) {
509                smallValue = mantissa << (-scale);
510            } else {
511                BigInt bi = new BigInt();
512                bi.putLongInt(mantissa);
513                bi.shift(-scale);
514                intVal = new BigInteger(bi);
515            }
516            scale = 0;
517        } else if (scale > 0) {
518            // m * 2^e =  (m * 5^(-e)) * 10^e
519            if(scale < LONG_FIVE_POW.length
520                    && mantissaBits+LONG_FIVE_POW_BIT_LENGTH[scale] < 64) {
521                smallValue = mantissa * LONG_FIVE_POW[scale];
522                bitLength = bitLength(smallValue);
523            } else {
524                setUnscaledValue(Multiplication.multiplyByFivePow(BigInteger.valueOf(mantissa), scale));
525            }
526        } else { // scale == 0
527            smallValue = mantissa;
528            bitLength = mantissaBits;
529        }
530    }
531
532    /**
533     * Constructs a new {@code BigDecimal} instance from the 64bit double
534     * {@code val}. The constructed big decimal is equivalent to the given
535     * double. For example, {@code new BigDecimal(0.1)} is equal to {@code
536     * 0.1000000000000000055511151231257827021181583404541015625}. This happens
537     * as {@code 0.1} cannot be represented exactly in binary.
538     * <p>
539     * To generate a big decimal instance which is equivalent to {@code 0.1} use
540     * the {@code BigDecimal(String)} constructor.
541     *
542     * @param val
543     *            double value to be converted to a {@code BigDecimal} instance.
544     * @param mc
545     *            rounding mode and precision for the result of this operation.
546     * @throws NumberFormatException
547     *             if {@code val} is infinity or not a number.
548     * @throws ArithmeticException
549     *             if {@code mc.precision > 0} and {@code mc.roundingMode ==
550     *             UNNECESSARY} and the new big decimal cannot be represented
551     *             within the given precision without rounding.
552     */
553    public BigDecimal(double val, MathContext mc) {
554        this(val);
555        inplaceRound(mc);
556    }
557
558    /**
559     * Constructs a new {@code BigDecimal} instance from the given big integer
560     * {@code val}. The scale of the result is {@code 0}.
561     *
562     * @param val
563     *            {@code BigInteger} value to be converted to a {@code
564     *            BigDecimal} instance.
565     */
566    public BigDecimal(BigInteger val) {
567        this(val, 0);
568    }
569
570    /**
571     * Constructs a new {@code BigDecimal} instance from the given big integer
572     * {@code val}. The scale of the result is {@code 0}.
573     *
574     * @param val
575     *            {@code BigInteger} value to be converted to a {@code
576     *            BigDecimal} instance.
577     * @param mc
578     *            rounding mode and precision for the result of this operation.
579     * @throws ArithmeticException
580     *             if {@code mc.precision > 0} and {@code mc.roundingMode ==
581     *             UNNECESSARY} and the new big decimal cannot be represented
582     *             within the given precision without rounding.
583     */
584    public BigDecimal(BigInteger val, MathContext mc) {
585        this(val);
586        inplaceRound(mc);
587    }
588
589    /**
590     * Constructs a new {@code BigDecimal} instance from a given unscaled value
591     * {@code unscaledVal} and a given scale. The value of this instance is
592     * {@code unscaledVal} 10^(-{@code scale}).
593     *
594     * @param unscaledVal
595     *            {@code BigInteger} representing the unscaled value of this
596     *            {@code BigDecimal} instance.
597     * @param scale
598     *            scale of this {@code BigDecimal} instance.
599     * @throws NullPointerException
600     *             if {@code unscaledVal == null}.
601     */
602    public BigDecimal(BigInteger unscaledVal, int scale) {
603        if (unscaledVal == null) {
604            throw new NullPointerException("unscaledVal == null");
605        }
606        this.scale = scale;
607        setUnscaledValue(unscaledVal);
608    }
609
610    /**
611     * Constructs a new {@code BigDecimal} instance from a given unscaled value
612     * {@code unscaledVal} and a given scale. The value of this instance is
613     * {@code unscaledVal} 10^(-{@code scale}). The result is rounded according
614     * to the specified math context.
615     *
616     * @param unscaledVal
617     *            {@code BigInteger} representing the unscaled value of this
618     *            {@code BigDecimal} instance.
619     * @param scale
620     *            scale of this {@code BigDecimal} instance.
621     * @param mc
622     *            rounding mode and precision for the result of this operation.
623     * @throws ArithmeticException
624     *             if {@code mc.precision > 0} and {@code mc.roundingMode ==
625     *             UNNECESSARY} and the new big decimal cannot be represented
626     *             within the given precision without rounding.
627     * @throws NullPointerException
628     *             if {@code unscaledVal == null}.
629     */
630    public BigDecimal(BigInteger unscaledVal, int scale, MathContext mc) {
631        this(unscaledVal, scale);
632        inplaceRound(mc);
633    }
634
635    /**
636     * Constructs a new {@code BigDecimal} instance from the given int
637     * {@code val}. The scale of the result is 0.
638     *
639     * @param val
640     *            int value to be converted to a {@code BigDecimal} instance.
641     */
642    public BigDecimal(int val) {
643        this(val,0);
644    }
645
646    /**
647     * Constructs a new {@code BigDecimal} instance from the given int {@code
648     * val}. The scale of the result is {@code 0}. The result is rounded
649     * according to the specified math context.
650     *
651     * @param val
652     *            int value to be converted to a {@code BigDecimal} instance.
653     * @param mc
654     *            rounding mode and precision for the result of this operation.
655     * @throws ArithmeticException
656     *             if {@code mc.precision > 0} and {@code c.roundingMode ==
657     *             UNNECESSARY} and the new big decimal cannot be represented
658     *             within the given precision without rounding.
659     */
660    public BigDecimal(int val, MathContext mc) {
661        this(val,0);
662        inplaceRound(mc);
663    }
664
665    /**
666     * Constructs a new {@code BigDecimal} instance from the given long {@code
667     * val}. The scale of the result is {@code 0}.
668     *
669     * @param val
670     *            long value to be converted to a {@code BigDecimal} instance.
671     */
672    public BigDecimal(long val) {
673        this(val,0);
674    }
675
676    /**
677     * Constructs a new {@code BigDecimal} instance from the given long {@code
678     * val}. The scale of the result is {@code 0}. The result is rounded
679     * according to the specified math context.
680     *
681     * @param val
682     *            long value to be converted to a {@code BigDecimal} instance.
683     * @param mc
684     *            rounding mode and precision for the result of this operation.
685     * @throws ArithmeticException
686     *             if {@code mc.precision > 0} and {@code mc.roundingMode ==
687     *             UNNECESSARY} and the new big decimal cannot be represented
688     *             within the given precision without rounding.
689     */
690    public BigDecimal(long val, MathContext mc) {
691        this(val);
692        inplaceRound(mc);
693    }
694
695    /* Public Methods */
696
697    /**
698     * Returns a new {@code BigDecimal} instance whose value is equal to {@code
699     * unscaledVal} 10^(-{@code scale}). The scale of the result is {@code
700     * scale}, and its unscaled value is {@code unscaledVal}.
701     *
702     * @param unscaledVal
703     *            unscaled value to be used to construct the new {@code
704     *            BigDecimal}.
705     * @param scale
706     *            scale to be used to construct the new {@code BigDecimal}.
707     * @return {@code BigDecimal} instance with the value {@code unscaledVal}*
708     *         10^(-{@code unscaledVal}).
709     */
710    public static BigDecimal valueOf(long unscaledVal, int scale) {
711        if (scale == 0) {
712            return valueOf(unscaledVal);
713        }
714        if ((unscaledVal == 0) && (scale >= 0)
715                && (scale < ZERO_SCALED_BY.length)) {
716            return ZERO_SCALED_BY[scale];
717        }
718        return new BigDecimal(unscaledVal, scale);
719    }
720
721    /**
722     * Returns a new {@code BigDecimal} instance whose value is equal to {@code
723     * unscaledVal}. The scale of the result is {@code 0}, and its unscaled
724     * value is {@code unscaledVal}.
725     *
726     * @param unscaledVal
727     *            value to be converted to a {@code BigDecimal}.
728     * @return {@code BigDecimal} instance with the value {@code unscaledVal}.
729     */
730    public static BigDecimal valueOf(long unscaledVal) {
731        if ((unscaledVal >= 0) && (unscaledVal < BI_SCALED_BY_ZERO_LENGTH)) {
732            return BI_SCALED_BY_ZERO[(int)unscaledVal];
733        }
734        return new BigDecimal(unscaledVal,0);
735    }
736
737    /**
738     * Returns a new {@code BigDecimal} instance whose value is equal to {@code
739     * val}. The new decimal is constructed as if the {@code BigDecimal(String)}
740     * constructor is called with an argument which is equal to {@code
741     * Double.toString(val)}. For example, {@code valueOf("0.1")} is converted to
742     * (unscaled=1, scale=1), although the double {@code 0.1} cannot be
743     * represented exactly as a double value. In contrast to that, a new {@code
744     * BigDecimal(0.1)} instance has the value {@code
745     * 0.1000000000000000055511151231257827021181583404541015625} with an
746     * unscaled value {@code 1000000000000000055511151231257827021181583404541015625}
747     * and the scale {@code 55}.
748     *
749     * @param val
750     *            double value to be converted to a {@code BigDecimal}.
751     * @return {@code BigDecimal} instance with the value {@code val}.
752     * @throws NumberFormatException
753     *             if {@code val} is infinite or {@code val} is not a number
754     */
755    public static BigDecimal valueOf(double val) {
756        if (Double.isInfinite(val) || Double.isNaN(val)) {
757            throw new NumberFormatException("Infinity or NaN: " + val);
758        }
759        return new BigDecimal(Double.toString(val));
760    }
761
762    /**
763     * Returns a new {@code BigDecimal} whose value is {@code this + augend}.
764     * The scale of the result is the maximum of the scales of the two
765     * arguments.
766     *
767     * @param augend
768     *            value to be added to {@code this}.
769     * @return {@code this + augend}.
770     * @throws NullPointerException
771     *             if {@code augend == null}.
772     */
773    public BigDecimal add(BigDecimal augend) {
774        int diffScale = this.scale - augend.scale;
775        // Fast return when some operand is zero
776        if (this.isZero()) {
777            if (diffScale <= 0) {
778                return augend;
779            }
780            if (augend.isZero()) {
781                return this;
782            }
783        } else if (augend.isZero()) {
784            if (diffScale >= 0) {
785                return this;
786            }
787        }
788        // Let be:  this = [u1,s1]  and  augend = [u2,s2]
789        if (diffScale == 0) {
790            // case s1 == s2: [u1 + u2 , s1]
791            if (Math.max(this.bitLength, augend.bitLength) + 1 < 64) {
792                return valueOf(this.smallValue + augend.smallValue, this.scale);
793            }
794            return new BigDecimal(this.getUnscaledValue().add(augend.getUnscaledValue()), this.scale);
795        } else if (diffScale > 0) {
796            // case s1 > s2 : [(u1 + u2) * 10 ^ (s1 - s2) , s1]
797            return addAndMult10(this, augend, diffScale);
798        } else {// case s2 > s1 : [(u2 + u1) * 10 ^ (s2 - s1) , s2]
799            return addAndMult10(augend, this, -diffScale);
800        }
801    }
802
803    private static BigDecimal addAndMult10(BigDecimal thisValue,BigDecimal augend, int diffScale) {
804        if(diffScale < MathUtils.LONG_POWERS_OF_TEN.length &&
805                Math.max(thisValue.bitLength,augend.bitLength+LONG_POWERS_OF_TEN_BIT_LENGTH[diffScale])+1<64) {
806            return valueOf(thisValue.smallValue+augend.smallValue*MathUtils.LONG_POWERS_OF_TEN[diffScale],thisValue.scale);
807        } else {
808            BigInt bi = Multiplication.multiplyByTenPow(augend.getUnscaledValue(),diffScale).getBigInt();
809            bi.add(thisValue.getUnscaledValue().getBigInt());
810            return new BigDecimal(new BigInteger(bi), thisValue.scale);
811        }
812    }
813
814    /**
815     * Returns a new {@code BigDecimal} whose value is {@code this + augend}.
816     * The result is rounded according to the passed context {@code mc}.
817     *
818     * @param augend
819     *            value to be added to {@code this}.
820     * @param mc
821     *            rounding mode and precision for the result of this operation.
822     * @return {@code this + augend}.
823     * @throws NullPointerException
824     *             if {@code augend == null} or {@code mc == null}.
825     */
826    public BigDecimal add(BigDecimal augend, MathContext mc) {
827        BigDecimal larger; // operand with the largest unscaled value
828        BigDecimal smaller; // operand with the smallest unscaled value
829        BigInteger tempBI;
830        long diffScale = (long)this.scale - augend.scale;
831        int largerSignum;
832        // Some operand is zero or the precision is infinity
833        if ((augend.isZero()) || (this.isZero())
834                || (mc.getPrecision() == 0)) {
835            return add(augend).round(mc);
836        }
837        // Cases where there is room for optimizations
838        if (this.approxPrecision() < diffScale - 1) {
839            larger = augend;
840            smaller = this;
841        } else if (augend.approxPrecision() < -diffScale - 1) {
842            larger = this;
843            smaller = augend;
844        } else {// No optimization is done
845            return add(augend).round(mc);
846        }
847        if (mc.getPrecision() >= larger.approxPrecision()) {
848            // No optimization is done
849            return add(augend).round(mc);
850        }
851        // Cases where it's unnecessary to add two numbers with very different scales
852        largerSignum = larger.signum();
853        if (largerSignum == smaller.signum()) {
854            tempBI = Multiplication.multiplyByPositiveInt(larger.getUnscaledValue(),10)
855            .add(BigInteger.valueOf(largerSignum));
856        } else {
857            tempBI = larger.getUnscaledValue().subtract(
858                    BigInteger.valueOf(largerSignum));
859            tempBI = Multiplication.multiplyByPositiveInt(tempBI,10)
860            .add(BigInteger.valueOf(largerSignum * 9));
861        }
862        // Rounding the improved adding
863        larger = new BigDecimal(tempBI, larger.scale + 1);
864        return larger.round(mc);
865    }
866
867    /**
868     * Returns a new {@code BigDecimal} whose value is {@code this - subtrahend}.
869     * The scale of the result is the maximum of the scales of the two arguments.
870     *
871     * @param subtrahend
872     *            value to be subtracted from {@code this}.
873     * @return {@code this - subtrahend}.
874     * @throws NullPointerException
875     *             if {@code subtrahend == null}.
876     */
877    public BigDecimal subtract(BigDecimal subtrahend) {
878        int diffScale = this.scale - subtrahend.scale;
879        // Fast return when some operand is zero
880        if (this.isZero()) {
881            if (diffScale <= 0) {
882                return subtrahend.negate();
883            }
884            if (subtrahend.isZero()) {
885                return this;
886            }
887        } else if (subtrahend.isZero()) {
888            if (diffScale >= 0) {
889                return this;
890            }
891        }
892        // Let be: this = [u1,s1] and subtrahend = [u2,s2] so:
893        if (diffScale == 0) {
894            // case s1 = s2 : [u1 - u2 , s1]
895            if (Math.max(this.bitLength, subtrahend.bitLength) + 1 < 64) {
896                return valueOf(this.smallValue - subtrahend.smallValue,this.scale);
897            }
898            return new BigDecimal(this.getUnscaledValue().subtract(subtrahend.getUnscaledValue()), this.scale);
899        } else if (diffScale > 0) {
900            // case s1 > s2 : [ u1 - u2 * 10 ^ (s1 - s2) , s1 ]
901            if(diffScale < MathUtils.LONG_POWERS_OF_TEN.length &&
902                    Math.max(this.bitLength,subtrahend.bitLength+LONG_POWERS_OF_TEN_BIT_LENGTH[diffScale])+1<64) {
903                return valueOf(this.smallValue-subtrahend.smallValue*MathUtils.LONG_POWERS_OF_TEN[diffScale],this.scale);
904            }
905            return new BigDecimal(this.getUnscaledValue().subtract(
906                    Multiplication.multiplyByTenPow(subtrahend.getUnscaledValue(),diffScale)), this.scale);
907        } else {// case s2 > s1 : [ u1 * 10 ^ (s2 - s1) - u2 , s2 ]
908            diffScale = -diffScale;
909            if(diffScale < MathUtils.LONG_POWERS_OF_TEN.length &&
910                    Math.max(this.bitLength+LONG_POWERS_OF_TEN_BIT_LENGTH[diffScale],subtrahend.bitLength)+1<64) {
911                return valueOf(this.smallValue*MathUtils.LONG_POWERS_OF_TEN[diffScale]-subtrahend.smallValue,subtrahend.scale);
912            }
913            return new BigDecimal(Multiplication.multiplyByTenPow(this.getUnscaledValue(),diffScale)
914            .subtract(subtrahend.getUnscaledValue()), subtrahend.scale);
915        }
916    }
917
918    /**
919     * Returns a new {@code BigDecimal} whose value is {@code this - subtrahend}.
920     * The result is rounded according to the passed context {@code mc}.
921     *
922     * @param subtrahend
923     *            value to be subtracted from {@code this}.
924     * @param mc
925     *            rounding mode and precision for the result of this operation.
926     * @return {@code this - subtrahend}.
927     * @throws NullPointerException
928     *             if {@code subtrahend == null} or {@code mc == null}.
929     */
930    public BigDecimal subtract(BigDecimal subtrahend, MathContext mc) {
931        long diffScale = subtrahend.scale - (long)this.scale;
932        int thisSignum;
933        BigDecimal leftOperand; // it will be only the left operand (this)
934        BigInteger tempBI;
935        // Some operand is zero or the precision is infinity
936        if ((subtrahend.isZero()) || (this.isZero())
937                || (mc.getPrecision() == 0)) {
938            return subtract(subtrahend).round(mc);
939        }
940        // Now:   this != 0   and   subtrahend != 0
941        if (subtrahend.approxPrecision() < diffScale - 1) {
942            // Cases where it is unnecessary to subtract two numbers with very different scales
943            if (mc.getPrecision() < this.approxPrecision()) {
944                thisSignum = this.signum();
945                if (thisSignum != subtrahend.signum()) {
946                    tempBI = Multiplication.multiplyByPositiveInt(this.getUnscaledValue(), 10)
947                    .add(BigInteger.valueOf(thisSignum));
948                } else {
949                    tempBI = this.getUnscaledValue().subtract(BigInteger.valueOf(thisSignum));
950                    tempBI = Multiplication.multiplyByPositiveInt(tempBI, 10)
951                    .add(BigInteger.valueOf(thisSignum * 9));
952                }
953                // Rounding the improved subtracting
954                leftOperand = new BigDecimal(tempBI, this.scale + 1);
955                return leftOperand.round(mc);
956            }
957        }
958        // No optimization is done
959        return subtract(subtrahend).round(mc);
960    }
961
962    /**
963     * Returns a new {@code BigDecimal} whose value is {@code this *
964     * multiplicand}. The scale of the result is the sum of the scales of the
965     * two arguments.
966     *
967     * @param multiplicand
968     *            value to be multiplied with {@code this}.
969     * @return {@code this * multiplicand}.
970     * @throws NullPointerException
971     *             if {@code multiplicand == null}.
972     */
973    public BigDecimal multiply(BigDecimal multiplicand) {
974        long newScale = (long)this.scale + multiplicand.scale;
975
976        if ((this.isZero()) || (multiplicand.isZero())) {
977            return zeroScaledBy(newScale);
978        }
979        /* Let be: this = [u1,s1] and multiplicand = [u2,s2] so:
980         * this x multiplicand = [ s1 * s2 , s1 + s2 ] */
981        if(this.bitLength + multiplicand.bitLength < 64) {
982            return valueOf(this.smallValue*multiplicand.smallValue, safeLongToInt(newScale));
983        }
984        return new BigDecimal(this.getUnscaledValue().multiply(
985                multiplicand.getUnscaledValue()), safeLongToInt(newScale));
986    }
987
988    /**
989     * Returns a new {@code BigDecimal} whose value is {@code this *
990     * multiplicand}. The result is rounded according to the passed context
991     * {@code mc}.
992     *
993     * @param multiplicand
994     *            value to be multiplied with {@code this}.
995     * @param mc
996     *            rounding mode and precision for the result of this operation.
997     * @return {@code this * multiplicand}.
998     * @throws NullPointerException
999     *             if {@code multiplicand == null} or {@code mc == null}.
1000     */
1001    public BigDecimal multiply(BigDecimal multiplicand, MathContext mc) {
1002        BigDecimal result = multiply(multiplicand);
1003
1004        result.inplaceRound(mc);
1005        return result;
1006    }
1007
1008    /**
1009     * Returns a new {@code BigDecimal} whose value is {@code this / divisor}.
1010     * As scale of the result the parameter {@code scale} is used. If rounding
1011     * is required to meet the specified scale, then the specified rounding mode
1012     * {@code roundingMode} is applied.
1013     *
1014     * @param divisor
1015     *            value by which {@code this} is divided.
1016     * @param scale
1017     *            the scale of the result returned.
1018     * @param roundingMode
1019     *            rounding mode to be used to round the result.
1020     * @return {@code this / divisor} rounded according to the given rounding
1021     *         mode.
1022     * @throws NullPointerException
1023     *             if {@code divisor == null}.
1024     * @throws IllegalArgumentException
1025     *             if {@code roundingMode} is not a valid rounding mode.
1026     * @throws ArithmeticException
1027     *             if {@code divisor == 0}.
1028     * @throws ArithmeticException
1029     *             if {@code roundingMode == ROUND_UNNECESSARY} and rounding is
1030     *             necessary according to the given scale.
1031     */
1032    public BigDecimal divide(BigDecimal divisor, int scale, int roundingMode) {
1033        return divide(divisor, scale, RoundingMode.valueOf(roundingMode));
1034    }
1035
1036    /**
1037     * Returns a new {@code BigDecimal} whose value is {@code this / divisor}.
1038     * As scale of the result the parameter {@code scale} is used. If rounding
1039     * is required to meet the specified scale, then the specified rounding mode
1040     * {@code roundingMode} is applied.
1041     *
1042     * @param divisor
1043     *            value by which {@code this} is divided.
1044     * @param scale
1045     *            the scale of the result returned.
1046     * @param roundingMode
1047     *            rounding mode to be used to round the result.
1048     * @return {@code this / divisor} rounded according to the given rounding
1049     *         mode.
1050     * @throws NullPointerException
1051     *             if {@code divisor == null} or {@code roundingMode == null}.
1052     * @throws ArithmeticException
1053     *             if {@code divisor == 0}.
1054     * @throws ArithmeticException
1055     *             if {@code roundingMode == RoundingMode.UNNECESSAR}Y and
1056     *             rounding is necessary according to the given scale and given
1057     *             precision.
1058     */
1059    public BigDecimal divide(BigDecimal divisor, int scale, RoundingMode roundingMode) {
1060        // Let be: this = [u1,s1]  and  divisor = [u2,s2]
1061        if (roundingMode == null) {
1062            throw new NullPointerException("roundingMode == null");
1063        }
1064        if (divisor.isZero()) {
1065            throw new ArithmeticException("Division by zero");
1066        }
1067
1068        long diffScale = ((long)this.scale - divisor.scale) - scale;
1069        if(this.bitLength < 64 && divisor.bitLength < 64 ) {
1070            if(diffScale == 0) {
1071                return dividePrimitiveLongs(this.smallValue,
1072                        divisor.smallValue,
1073                        scale,
1074                        roundingMode );
1075            } else if(diffScale > 0) {
1076                if(diffScale < MathUtils.LONG_POWERS_OF_TEN.length &&
1077                        divisor.bitLength + LONG_POWERS_OF_TEN_BIT_LENGTH[(int)diffScale] < 64) {
1078                    return dividePrimitiveLongs(this.smallValue,
1079                            divisor.smallValue*MathUtils.LONG_POWERS_OF_TEN[(int)diffScale],
1080                            scale,
1081                            roundingMode);
1082                }
1083            } else { // diffScale < 0
1084                if(-diffScale < MathUtils.LONG_POWERS_OF_TEN.length &&
1085                        this.bitLength + LONG_POWERS_OF_TEN_BIT_LENGTH[(int)-diffScale] < 64) {
1086                    return dividePrimitiveLongs(this.smallValue*MathUtils.LONG_POWERS_OF_TEN[(int)-diffScale],
1087                            divisor.smallValue,
1088                            scale,
1089                            roundingMode);
1090                }
1091
1092            }
1093        }
1094        BigInteger scaledDividend = this.getUnscaledValue();
1095        BigInteger scaledDivisor = divisor.getUnscaledValue(); // for scaling of 'u2'
1096
1097        if (diffScale > 0) {
1098            // Multiply 'u2'  by:  10^((s1 - s2) - scale)
1099            scaledDivisor = Multiplication.multiplyByTenPow(scaledDivisor, (int)diffScale);
1100        } else if (diffScale < 0) {
1101            // Multiply 'u1'  by:  10^(scale - (s1 - s2))
1102            scaledDividend  = Multiplication.multiplyByTenPow(scaledDividend, (int)-diffScale);
1103        }
1104        return divideBigIntegers(scaledDividend, scaledDivisor, scale, roundingMode);
1105        }
1106
1107    private static BigDecimal divideBigIntegers(BigInteger scaledDividend, BigInteger scaledDivisor, int scale, RoundingMode roundingMode) {
1108
1109        BigInteger[] quotAndRem = scaledDividend.divideAndRemainder(scaledDivisor);  // quotient and remainder
1110        // If after division there is a remainder...
1111        BigInteger quotient = quotAndRem[0];
1112        BigInteger remainder = quotAndRem[1];
1113        if (remainder.signum() == 0) {
1114            return new BigDecimal(quotient, scale);
1115        }
1116        int sign = scaledDividend.signum() * scaledDivisor.signum();
1117        int compRem;                                      // 'compare to remainder'
1118        if(scaledDivisor.bitLength() < 63) { // 63 in order to avoid out of long after *2
1119            long rem = remainder.longValue();
1120            long divisor = scaledDivisor.longValue();
1121            compRem = longCompareTo(Math.abs(rem) * 2,Math.abs(divisor));
1122            // To look if there is a carry
1123            compRem = roundingBehavior(quotient.testBit(0) ? 1 : 0,
1124                    sign * (5 + compRem), roundingMode);
1125
1126        } else {
1127            // Checking if:  remainder * 2 >= scaledDivisor
1128            compRem = remainder.abs().shiftLeftOneBit().compareTo(scaledDivisor.abs());
1129            compRem = roundingBehavior(quotient.testBit(0) ? 1 : 0,
1130                    sign * (5 + compRem), roundingMode);
1131        }
1132            if (compRem != 0) {
1133            if(quotient.bitLength() < 63) {
1134                return valueOf(quotient.longValue() + compRem,scale);
1135            }
1136            quotient = quotient.add(BigInteger.valueOf(compRem));
1137            return new BigDecimal(quotient, scale);
1138        }
1139        // Constructing the result with the appropriate unscaled value
1140        return new BigDecimal(quotient, scale);
1141    }
1142
1143    private static BigDecimal dividePrimitiveLongs(long scaledDividend, long scaledDivisor, int scale, RoundingMode roundingMode) {
1144        long quotient = scaledDividend / scaledDivisor;
1145        long remainder = scaledDividend % scaledDivisor;
1146        int sign = Long.signum( scaledDividend ) * Long.signum( scaledDivisor );
1147        if (remainder != 0) {
1148            // Checking if:  remainder * 2 >= scaledDivisor
1149            int compRem;                                      // 'compare to remainder'
1150            compRem = longCompareTo(Math.abs(remainder) * 2,Math.abs(scaledDivisor));
1151            // To look if there is a carry
1152            quotient += roundingBehavior(((int)quotient) & 1,
1153                    sign * (5 + compRem),
1154                    roundingMode);
1155        }
1156        // Constructing the result with the appropriate unscaled value
1157        return valueOf(quotient, scale);
1158    }
1159
1160    /**
1161     * Returns a new {@code BigDecimal} whose value is {@code this / divisor}.
1162     * The scale of the result is the scale of {@code this}. If rounding is
1163     * required to meet the specified scale, then the specified rounding mode
1164     * {@code roundingMode} is applied.
1165     *
1166     * @param divisor
1167     *            value by which {@code this} is divided.
1168     * @param roundingMode
1169     *            rounding mode to be used to round the result.
1170     * @return {@code this / divisor} rounded according to the given rounding
1171     *         mode.
1172     * @throws NullPointerException
1173     *             if {@code divisor == null}.
1174     * @throws IllegalArgumentException
1175     *             if {@code roundingMode} is not a valid rounding mode.
1176     * @throws ArithmeticException
1177     *             if {@code divisor == 0}.
1178     * @throws ArithmeticException
1179     *             if {@code roundingMode == ROUND_UNNECESSARY} and rounding is
1180     *             necessary according to the scale of this.
1181     */
1182    public BigDecimal divide(BigDecimal divisor, int roundingMode) {
1183        return divide(divisor, scale, RoundingMode.valueOf(roundingMode));
1184    }
1185
1186    /**
1187     * Returns a new {@code BigDecimal} whose value is {@code this / divisor}.
1188     * The scale of the result is the scale of {@code this}. If rounding is
1189     * required to meet the specified scale, then the specified rounding mode
1190     * {@code roundingMode} is applied.
1191     *
1192     * @param divisor
1193     *            value by which {@code this} is divided.
1194     * @param roundingMode
1195     *            rounding mode to be used to round the result.
1196     * @return {@code this / divisor} rounded according to the given rounding
1197     *         mode.
1198     * @throws NullPointerException
1199     *             if {@code divisor == null} or {@code roundingMode == null}.
1200     * @throws ArithmeticException
1201     *             if {@code divisor == 0}.
1202     * @throws ArithmeticException
1203     *             if {@code roundingMode == RoundingMode.UNNECESSARY} and
1204     *             rounding is necessary according to the scale of this.
1205     */
1206    public BigDecimal divide(BigDecimal divisor, RoundingMode roundingMode) {
1207        return divide(divisor, scale, roundingMode);
1208    }
1209
1210    /**
1211     * Returns a new {@code BigDecimal} whose value is {@code this / divisor}.
1212     * The scale of the result is the difference of the scales of {@code this}
1213     * and {@code divisor}. If the exact result requires more digits, then the
1214     * scale is adjusted accordingly. For example, {@code 1/128 = 0.0078125}
1215     * which has a scale of {@code 7} and precision {@code 5}.
1216     *
1217     * @param divisor
1218     *            value by which {@code this} is divided.
1219     * @return {@code this / divisor}.
1220     * @throws NullPointerException
1221     *             if {@code divisor == null}.
1222     * @throws ArithmeticException
1223     *             if {@code divisor == 0}.
1224     * @throws ArithmeticException
1225     *             if the result cannot be represented exactly.
1226     */
1227    public BigDecimal divide(BigDecimal divisor) {
1228        BigInteger p = this.getUnscaledValue();
1229        BigInteger q = divisor.getUnscaledValue();
1230        BigInteger gcd; // greatest common divisor between 'p' and 'q'
1231        BigInteger quotAndRem[];
1232        long diffScale = (long)scale - divisor.scale;
1233        int newScale; // the new scale for final quotient
1234        int k; // number of factors "2" in 'q'
1235        int l = 0; // number of factors "5" in 'q'
1236        int i = 1;
1237        int lastPow = FIVE_POW.length - 1;
1238
1239        if (divisor.isZero()) {
1240            throw new ArithmeticException("Division by zero");
1241        }
1242        if (p.signum() == 0) {
1243            return zeroScaledBy(diffScale);
1244        }
1245        // To divide both by the GCD
1246        gcd = p.gcd(q);
1247        p = p.divide(gcd);
1248        q = q.divide(gcd);
1249        // To simplify all "2" factors of q, dividing by 2^k
1250        k = q.getLowestSetBit();
1251        q = q.shiftRight(k);
1252        // To simplify all "5" factors of q, dividing by 5^l
1253        do {
1254            quotAndRem = q.divideAndRemainder(FIVE_POW[i]);
1255            if (quotAndRem[1].signum() == 0) {
1256                l += i;
1257                if (i < lastPow) {
1258                    i++;
1259                }
1260                q = quotAndRem[0];
1261            } else {
1262                if (i == 1) {
1263                    break;
1264                }
1265                i = 1;
1266            }
1267        } while (true);
1268        // If  abs(q) != 1  then the quotient is periodic
1269        if (!q.abs().equals(BigInteger.ONE)) {
1270            throw new ArithmeticException("Non-terminating decimal expansion; no exact representable decimal result");
1271        }
1272        // The sign of the is fixed and the quotient will be saved in 'p'
1273        if (q.signum() < 0) {
1274            p = p.negate();
1275        }
1276        // Checking if the new scale is out of range
1277        newScale = safeLongToInt(diffScale + Math.max(k, l));
1278        // k >= 0  and  l >= 0  implies that  k - l  is in the 32-bit range
1279        i = k - l;
1280
1281        p = (i > 0) ? Multiplication.multiplyByFivePow(p, i)
1282        : p.shiftLeft(-i);
1283        return new BigDecimal(p, newScale);
1284    }
1285
1286    /**
1287     * Returns a new {@code BigDecimal} whose value is {@code this / divisor}.
1288     * The result is rounded according to the passed context {@code mc}. If the
1289     * passed math context specifies precision {@code 0}, then this call is
1290     * equivalent to {@code this.divide(divisor)}.
1291     *
1292     * @param divisor
1293     *            value by which {@code this} is divided.
1294     * @param mc
1295     *            rounding mode and precision for the result of this operation.
1296     * @return {@code this / divisor}.
1297     * @throws NullPointerException
1298     *             if {@code divisor == null} or {@code mc == null}.
1299     * @throws ArithmeticException
1300     *             if {@code divisor == 0}.
1301     * @throws ArithmeticException
1302     *             if {@code mc.getRoundingMode() == UNNECESSARY} and rounding
1303     *             is necessary according {@code mc.getPrecision()}.
1304     */
1305    public BigDecimal divide(BigDecimal divisor, MathContext mc) {
1306        /* Calculating how many zeros must be append to 'dividend'
1307         * to obtain a  quotient with at least 'mc.precision()' digits */
1308        long trailingZeros = mc.getPrecision() + 2L
1309                + divisor.approxPrecision() - approxPrecision();
1310        long diffScale = (long)scale - divisor.scale;
1311        long newScale = diffScale; // scale of the final quotient
1312        int compRem; // to compare the remainder
1313        int i = 1; // index
1314        int lastPow = TEN_POW.length - 1; // last power of ten
1315        BigInteger integerQuot; // for temporal results
1316        BigInteger quotAndRem[] = {getUnscaledValue()};
1317        // In special cases it reduces the problem to call the dual method
1318        if ((mc.getPrecision() == 0) || (this.isZero())
1319        || (divisor.isZero())) {
1320            return this.divide(divisor);
1321        }
1322        if (trailingZeros > 0) {
1323            // To append trailing zeros at end of dividend
1324            quotAndRem[0] = getUnscaledValue().multiply( Multiplication.powerOf10(trailingZeros) );
1325            newScale += trailingZeros;
1326        }
1327        quotAndRem = quotAndRem[0].divideAndRemainder( divisor.getUnscaledValue() );
1328        integerQuot = quotAndRem[0];
1329        // Calculating the exact quotient with at least 'mc.precision()' digits
1330        if (quotAndRem[1].signum() != 0) {
1331            // Checking if:   2 * remainder >= divisor ?
1332            compRem = quotAndRem[1].shiftLeftOneBit().compareTo( divisor.getUnscaledValue() );
1333            // quot := quot * 10 + r;     with 'r' in {-6,-5,-4, 0,+4,+5,+6}
1334            integerQuot = integerQuot.multiply(BigInteger.TEN)
1335            .add(BigInteger.valueOf(quotAndRem[0].signum() * (5 + compRem)));
1336            newScale++;
1337        } else {
1338            // To strip trailing zeros until the preferred scale is reached
1339            while (!integerQuot.testBit(0)) {
1340                quotAndRem = integerQuot.divideAndRemainder(TEN_POW[i]);
1341                if ((quotAndRem[1].signum() == 0)
1342                        && (newScale - i >= diffScale)) {
1343                    newScale -= i;
1344                    if (i < lastPow) {
1345                        i++;
1346                    }
1347                    integerQuot = quotAndRem[0];
1348                } else {
1349                    if (i == 1) {
1350                        break;
1351                    }
1352                    i = 1;
1353                }
1354            }
1355        }
1356        // To perform rounding
1357        return new BigDecimal(integerQuot, safeLongToInt(newScale), mc);
1358    }
1359
1360    /**
1361     * Returns a new {@code BigDecimal} whose value is the integral part of
1362     * {@code this / divisor}. The quotient is rounded down towards zero to the
1363     * next integer. For example, {@code 0.5/0.2 = 2}.
1364     *
1365     * @param divisor
1366     *            value by which {@code this} is divided.
1367     * @return integral part of {@code this / divisor}.
1368     * @throws NullPointerException
1369     *             if {@code divisor == null}.
1370     * @throws ArithmeticException
1371     *             if {@code divisor == 0}.
1372     */
1373    public BigDecimal divideToIntegralValue(BigDecimal divisor) {
1374        BigInteger integralValue; // the integer of result
1375        BigInteger powerOfTen; // some power of ten
1376        BigInteger quotAndRem[] = {getUnscaledValue()};
1377        long newScale = (long)this.scale - divisor.scale;
1378        long tempScale = 0;
1379        int i = 1;
1380        int lastPow = TEN_POW.length - 1;
1381
1382        if (divisor.isZero()) {
1383            throw new ArithmeticException("Division by zero");
1384        }
1385        if ((divisor.approxPrecision() + newScale > this.approxPrecision() + 1L)
1386        || (this.isZero())) {
1387            /* If the divisor's integer part is greater than this's integer part,
1388             * the result must be zero with the appropriate scale */
1389            integralValue = BigInteger.ZERO;
1390        } else if (newScale == 0) {
1391            integralValue = getUnscaledValue().divide( divisor.getUnscaledValue() );
1392        } else if (newScale > 0) {
1393            powerOfTen = Multiplication.powerOf10(newScale);
1394            integralValue = getUnscaledValue().divide( divisor.getUnscaledValue().multiply(powerOfTen) );
1395            integralValue = integralValue.multiply(powerOfTen);
1396        } else {// (newScale < 0)
1397            powerOfTen = Multiplication.powerOf10(-newScale);
1398            integralValue = getUnscaledValue().multiply(powerOfTen).divide( divisor.getUnscaledValue() );
1399            // To strip trailing zeros approximating to the preferred scale
1400            while (!integralValue.testBit(0)) {
1401                quotAndRem = integralValue.divideAndRemainder(TEN_POW[i]);
1402                if ((quotAndRem[1].signum() == 0)
1403                        && (tempScale - i >= newScale)) {
1404                    tempScale -= i;
1405                    if (i < lastPow) {
1406                        i++;
1407                    }
1408                    integralValue = quotAndRem[0];
1409                } else {
1410                    if (i == 1) {
1411                        break;
1412                    }
1413                    i = 1;
1414                }
1415            }
1416            newScale = tempScale;
1417        }
1418        return ((integralValue.signum() == 0)
1419        ? zeroScaledBy(newScale)
1420                : new BigDecimal(integralValue, safeLongToInt(newScale)));
1421    }
1422
1423    /**
1424     * Returns a new {@code BigDecimal} whose value is the integral part of
1425     * {@code this / divisor}. The quotient is rounded down towards zero to the
1426     * next integer. The rounding mode passed with the parameter {@code mc} is
1427     * not considered. But if the precision of {@code mc > 0} and the integral
1428     * part requires more digits, then an {@code ArithmeticException} is thrown.
1429     *
1430     * @param divisor
1431     *            value by which {@code this} is divided.
1432     * @param mc
1433     *            math context which determines the maximal precision of the
1434     *            result.
1435     * @return integral part of {@code this / divisor}.
1436     * @throws NullPointerException
1437     *             if {@code divisor == null} or {@code mc == null}.
1438     * @throws ArithmeticException
1439     *             if {@code divisor == 0}.
1440     * @throws ArithmeticException
1441     *             if {@code mc.getPrecision() > 0} and the result requires more
1442     *             digits to be represented.
1443     */
1444    public BigDecimal divideToIntegralValue(BigDecimal divisor, MathContext mc) {
1445        int mcPrecision = mc.getPrecision();
1446        int diffPrecision = this.precision() - divisor.precision();
1447        int lastPow = TEN_POW.length - 1;
1448        long diffScale = (long)this.scale - divisor.scale;
1449        long newScale = diffScale;
1450        long quotPrecision = diffPrecision - diffScale + 1;
1451        BigInteger quotAndRem[] = new BigInteger[2];
1452        // In special cases it call the dual method
1453        if ((mcPrecision == 0) || (this.isZero()) || (divisor.isZero())) {
1454            return this.divideToIntegralValue(divisor);
1455        }
1456        // Let be:   this = [u1,s1]   and   divisor = [u2,s2]
1457        if (quotPrecision <= 0) {
1458            quotAndRem[0] = BigInteger.ZERO;
1459        } else if (diffScale == 0) {
1460            // CASE s1 == s2:  to calculate   u1 / u2
1461            quotAndRem[0] = this.getUnscaledValue().divide( divisor.getUnscaledValue() );
1462        } else if (diffScale > 0) {
1463            // CASE s1 >= s2:  to calculate   u1 / (u2 * 10^(s1-s2)
1464            quotAndRem[0] = this.getUnscaledValue().divide(
1465                    divisor.getUnscaledValue().multiply(Multiplication.powerOf10(diffScale)) );
1466            // To chose  10^newScale  to get a quotient with at least 'mc.precision()' digits
1467            newScale = Math.min(diffScale, Math.max(mcPrecision - quotPrecision + 1, 0));
1468            // To calculate: (u1 / (u2 * 10^(s1-s2)) * 10^newScale
1469            quotAndRem[0] = quotAndRem[0].multiply(Multiplication.powerOf10(newScale));
1470        } else {// CASE s2 > s1:
1471            /* To calculate the minimum power of ten, such that the quotient
1472             *   (u1 * 10^exp) / u2   has at least 'mc.precision()' digits. */
1473            long exp = Math.min(-diffScale, Math.max((long)mcPrecision - diffPrecision, 0));
1474            long compRemDiv;
1475            // Let be:   (u1 * 10^exp) / u2 = [q,r]
1476            quotAndRem = this.getUnscaledValue().multiply(Multiplication.powerOf10(exp)).
1477                    divideAndRemainder(divisor.getUnscaledValue());
1478            newScale += exp; // To fix the scale
1479            exp = -newScale; // The remaining power of ten
1480            // If after division there is a remainder...
1481            if ((quotAndRem[1].signum() != 0) && (exp > 0)) {
1482                // Log10(r) + ((s2 - s1) - exp) > mc.precision ?
1483                compRemDiv = (new BigDecimal(quotAndRem[1])).precision()
1484                + exp - divisor.precision();
1485                if (compRemDiv == 0) {
1486                    // To calculate:  (r * 10^exp2) / u2
1487                    quotAndRem[1] = quotAndRem[1].multiply(Multiplication.powerOf10(exp)).
1488                            divide(divisor.getUnscaledValue());
1489                    compRemDiv = Math.abs(quotAndRem[1].signum());
1490                }
1491                if (compRemDiv > 0) {
1492                    throw new ArithmeticException("Division impossible");
1493                }
1494            }
1495        }
1496        // Fast return if the quotient is zero
1497        if (quotAndRem[0].signum() == 0) {
1498            return zeroScaledBy(diffScale);
1499        }
1500        BigInteger strippedBI = quotAndRem[0];
1501        BigDecimal integralValue = new BigDecimal(quotAndRem[0]);
1502        long resultPrecision = integralValue.precision();
1503        int i = 1;
1504        // To strip trailing zeros until the specified precision is reached
1505        while (!strippedBI.testBit(0)) {
1506            quotAndRem = strippedBI.divideAndRemainder(TEN_POW[i]);
1507            if ((quotAndRem[1].signum() == 0) &&
1508                    ((resultPrecision - i >= mcPrecision)
1509                    || (newScale - i >= diffScale)) ) {
1510                resultPrecision -= i;
1511                newScale -= i;
1512                if (i < lastPow) {
1513                    i++;
1514                }
1515                strippedBI = quotAndRem[0];
1516            } else {
1517                if (i == 1) {
1518                    break;
1519                }
1520                i = 1;
1521            }
1522        }
1523        // To check if the result fit in 'mc.precision()' digits
1524        if (resultPrecision > mcPrecision) {
1525            throw new ArithmeticException("Division impossible");
1526        }
1527        integralValue.scale = safeLongToInt(newScale);
1528        integralValue.setUnscaledValue(strippedBI);
1529        return integralValue;
1530    }
1531
1532    /**
1533     * Returns a new {@code BigDecimal} whose value is {@code this % divisor}.
1534     * <p>
1535     * The remainder is defined as {@code this -
1536     * this.divideToIntegralValue(divisor) * divisor}.
1537     *
1538     * @param divisor
1539     *            value by which {@code this} is divided.
1540     * @return {@code this % divisor}.
1541     * @throws NullPointerException
1542     *             if {@code divisor == null}.
1543     * @throws ArithmeticException
1544     *             if {@code divisor == 0}.
1545     */
1546    public BigDecimal remainder(BigDecimal divisor) {
1547        return divideAndRemainder(divisor)[1];
1548    }
1549
1550    /**
1551     * Returns a new {@code BigDecimal} whose value is {@code this % divisor}.
1552     * <p>
1553     * The remainder is defined as {@code this -
1554     * this.divideToIntegralValue(divisor) * divisor}.
1555     * <p>
1556     * The specified rounding mode {@code mc} is used for the division only.
1557     *
1558     * @param divisor
1559     *            value by which {@code this} is divided.
1560     * @param mc
1561     *            rounding mode and precision to be used.
1562     * @return {@code this % divisor}.
1563     * @throws NullPointerException
1564     *             if {@code divisor == null}.
1565     * @throws ArithmeticException
1566     *             if {@code divisor == 0}.
1567     * @throws ArithmeticException
1568     *             if {@code mc.getPrecision() > 0} and the result of {@code
1569     *             this.divideToIntegralValue(divisor, mc)} requires more digits
1570     *             to be represented.
1571     */
1572    public BigDecimal remainder(BigDecimal divisor, MathContext mc) {
1573        return divideAndRemainder(divisor, mc)[1];
1574    }
1575
1576    /**
1577     * Returns a {@code BigDecimal} array which contains the integral part of
1578     * {@code this / divisor} at index 0 and the remainder {@code this %
1579     * divisor} at index 1. The quotient is rounded down towards zero to the
1580     * next integer.
1581     *
1582     * @param divisor
1583     *            value by which {@code this} is divided.
1584     * @return {@code [this.divideToIntegralValue(divisor),
1585     *         this.remainder(divisor)]}.
1586     * @throws NullPointerException
1587     *             if {@code divisor == null}.
1588     * @throws ArithmeticException
1589     *             if {@code divisor == 0}.
1590     * @see #divideToIntegralValue
1591     * @see #remainder
1592     */
1593    public BigDecimal[] divideAndRemainder(BigDecimal divisor) {
1594        BigDecimal quotAndRem[] = new BigDecimal[2];
1595
1596        quotAndRem[0] = this.divideToIntegralValue(divisor);
1597        quotAndRem[1] = this.subtract( quotAndRem[0].multiply(divisor) );
1598        return quotAndRem;
1599    }
1600
1601    /**
1602     * Returns a {@code BigDecimal} array which contains the integral part of
1603     * {@code this / divisor} at index 0 and the remainder {@code this %
1604     * divisor} at index 1. The quotient is rounded down towards zero to the
1605     * next integer. The rounding mode passed with the parameter {@code mc} is
1606     * not considered. But if the precision of {@code mc > 0} and the integral
1607     * part requires more digits, then an {@code ArithmeticException} is thrown.
1608     *
1609     * @param divisor
1610     *            value by which {@code this} is divided.
1611     * @param mc
1612     *            math context which determines the maximal precision of the
1613     *            result.
1614     * @return {@code [this.divideToIntegralValue(divisor),
1615     *         this.remainder(divisor)]}.
1616     * @throws NullPointerException
1617     *             if {@code divisor == null}.
1618     * @throws ArithmeticException
1619     *             if {@code divisor == 0}.
1620     * @see #divideToIntegralValue
1621     * @see #remainder
1622     */
1623    public BigDecimal[] divideAndRemainder(BigDecimal divisor, MathContext mc) {
1624        BigDecimal quotAndRem[] = new BigDecimal[2];
1625
1626        quotAndRem[0] = this.divideToIntegralValue(divisor, mc);
1627        quotAndRem[1] = this.subtract( quotAndRem[0].multiply(divisor) );
1628        return quotAndRem;
1629    }
1630
1631    /**
1632     * Returns a new {@code BigDecimal} whose value is {@code this ^ n}. The
1633     * scale of the result is {@code n} times the scales of {@code this}.
1634     * <p>
1635     * {@code x.pow(0)} returns {@code 1}, even if {@code x == 0}.
1636     * <p>
1637     * Implementation Note: The implementation is based on the ANSI standard
1638     * X3.274-1996 algorithm.
1639     *
1640     * @param n
1641     *            exponent to which {@code this} is raised.
1642     * @return {@code this ^ n}.
1643     * @throws ArithmeticException
1644     *             if {@code n < 0} or {@code n > 999999999}.
1645     */
1646    public BigDecimal pow(int n) {
1647        if (n == 0) {
1648            return ONE;
1649        }
1650        if ((n < 0) || (n > 999999999)) {
1651            throw new ArithmeticException("Invalid operation");
1652        }
1653        long newScale = scale * (long)n;
1654        // Let be: this = [u,s]   so:  this^n = [u^n, s*n]
1655        return isZero() ? zeroScaledBy(newScale)
1656                : new BigDecimal(getUnscaledValue().pow(n), safeLongToInt(newScale));
1657    }
1658
1659    /**
1660     * Returns a new {@code BigDecimal} whose value is {@code this ^ n}. The
1661     * result is rounded according to the passed context {@code mc}.
1662     * <p>
1663     * Implementation Note: The implementation is based on the ANSI standard
1664     * X3.274-1996 algorithm.
1665     *
1666     * @param n
1667     *            exponent to which {@code this} is raised.
1668     * @param mc
1669     *            rounding mode and precision for the result of this operation.
1670     * @return {@code this ^ n}.
1671     * @throws ArithmeticException
1672     *             if {@code n < 0} or {@code n > 999999999}.
1673     */
1674    public BigDecimal pow(int n, MathContext mc) {
1675        // The ANSI standard X3.274-1996 algorithm
1676        int m = Math.abs(n);
1677        int mcPrecision = mc.getPrecision();
1678        int elength = (int)Math.log10(m) + 1;   // decimal digits in 'n'
1679        int oneBitMask; // mask of bits
1680        BigDecimal accum; // the single accumulator
1681        MathContext newPrecision = mc; // MathContext by default
1682
1683        // In particular cases, it reduces the problem to call the other 'pow()'
1684        if ((n == 0) || ((isZero()) && (n > 0))) {
1685            return pow(n);
1686        }
1687        if ((m > 999999999) || ((mcPrecision == 0) && (n < 0))
1688                || ((mcPrecision > 0) && (elength > mcPrecision))) {
1689            throw new ArithmeticException("Invalid operation");
1690        }
1691        if (mcPrecision > 0) {
1692            newPrecision = new MathContext( mcPrecision + elength + 1,
1693                    mc.getRoundingMode());
1694        }
1695        // The result is calculated as if 'n' were positive
1696        accum = round(newPrecision);
1697        oneBitMask = Integer.highestOneBit(m) >> 1;
1698
1699        while (oneBitMask > 0) {
1700            accum = accum.multiply(accum, newPrecision);
1701            if ((m & oneBitMask) == oneBitMask) {
1702                accum = accum.multiply(this, newPrecision);
1703            }
1704            oneBitMask >>= 1;
1705        }
1706        // If 'n' is negative, the value is divided into 'ONE'
1707        if (n < 0) {
1708            accum = ONE.divide(accum, newPrecision);
1709        }
1710        // The final value is rounded to the destination precision
1711        accum.inplaceRound(mc);
1712        return accum;
1713    }
1714
1715    /**
1716     * Returns a new {@code BigDecimal} whose value is the absolute value of
1717     * {@code this}. The scale of the result is the same as the scale of this.
1718     *
1719     * @return {@code abs(this)}
1720     */
1721    public BigDecimal abs() {
1722        return ((signum() < 0) ? negate() : this);
1723    }
1724
1725    /**
1726     * Returns a new {@code BigDecimal} whose value is the absolute value of
1727     * {@code this}. The result is rounded according to the passed context
1728     * {@code mc}.
1729     *
1730     * @param mc
1731     *            rounding mode and precision for the result of this operation.
1732     * @return {@code abs(this)}
1733     */
1734    public BigDecimal abs(MathContext mc) {
1735        BigDecimal result = abs();
1736        result.inplaceRound(mc);
1737        return result;
1738    }
1739
1740    /**
1741     * Returns a new {@code BigDecimal} whose value is the {@code -this}. The
1742     * scale of the result is the same as the scale of this.
1743     *
1744     * @return {@code -this}
1745     */
1746    public BigDecimal negate() {
1747        if(bitLength < 63 || (bitLength == 63 && smallValue!=Long.MIN_VALUE)) {
1748            return valueOf(-smallValue,scale);
1749        }
1750        return new BigDecimal(getUnscaledValue().negate(), scale);
1751    }
1752
1753    /**
1754     * Returns a new {@code BigDecimal} whose value is the {@code -this}. The
1755     * result is rounded according to the passed context {@code mc}.
1756     *
1757     * @param mc
1758     *            rounding mode and precision for the result of this operation.
1759     * @return {@code -this}
1760     */
1761    public BigDecimal negate(MathContext mc) {
1762        BigDecimal result = negate();
1763        result.inplaceRound(mc);
1764        return result;
1765    }
1766
1767    /**
1768     * Returns a new {@code BigDecimal} whose value is {@code +this}. The scale
1769     * of the result is the same as the scale of this.
1770     *
1771     * @return {@code this}
1772     */
1773    public BigDecimal plus() {
1774        return this;
1775    }
1776
1777    /**
1778     * Returns a new {@code BigDecimal} whose value is {@code +this}. The result
1779     * is rounded according to the passed context {@code mc}.
1780     *
1781     * @param mc
1782     *            rounding mode and precision for the result of this operation.
1783     * @return {@code this}, rounded
1784     */
1785    public BigDecimal plus(MathContext mc) {
1786        return round(mc);
1787    }
1788
1789    /**
1790     * Returns the sign of this {@code BigDecimal}.
1791     *
1792     * @return {@code -1} if {@code this < 0},
1793     *         {@code 0} if {@code this == 0},
1794     *         {@code 1} if {@code this > 0}.     */
1795    public int signum() {
1796        if( bitLength < 64) {
1797            return Long.signum( this.smallValue );
1798        }
1799        return getUnscaledValue().signum();
1800    }
1801
1802    private boolean isZero() {
1803        //Watch out: -1 has a bitLength=0
1804        return bitLength == 0 && this.smallValue != -1;
1805    }
1806
1807    /**
1808     * Returns the scale of this {@code BigDecimal}. The scale is the number of
1809     * digits behind the decimal point. The value of this {@code BigDecimal} is
1810     * the unsignedValue * 10^(-scale). If the scale is negative, then this
1811     * {@code BigDecimal} represents a big integer.
1812     *
1813     * @return the scale of this {@code BigDecimal}.
1814     */
1815    public int scale() {
1816        return scale;
1817    }
1818
1819    /**
1820     * Returns the precision of this {@code BigDecimal}. The precision is the
1821     * number of decimal digits used to represent this decimal. It is equivalent
1822     * to the number of digits of the unscaled value. The precision of {@code 0}
1823     * is {@code 1} (independent of the scale).
1824     *
1825     * @return the precision of this {@code BigDecimal}.
1826     */
1827    public int precision() {
1828        // Checking if the precision already was calculated
1829        if (precision > 0) {
1830            return precision;
1831        }
1832
1833        int bitLength = this.bitLength;
1834
1835        if (bitLength == 0) {
1836            precision = 1;
1837        } else if (bitLength < 64) {
1838            precision = decimalDigitsInLong(smallValue);
1839        } else {
1840            int decimalDigits = 1 + (int) ((bitLength - 1) * LOG10_2);
1841            // If after division the number isn't zero, there exists an additional digit
1842            if (getUnscaledValue().divide(Multiplication.powerOf10(decimalDigits)).signum() != 0) {
1843                decimalDigits++;
1844            }
1845            precision = decimalDigits;
1846        }
1847        return precision;
1848    }
1849
1850    private int decimalDigitsInLong(long value) {
1851        if (value == Long.MIN_VALUE) {
1852            return 19; // special case required because abs(MIN_VALUE) == MIN_VALUE
1853        } else {
1854            int index = Arrays.binarySearch(MathUtils.LONG_POWERS_OF_TEN, Math.abs(value));
1855            return (index < 0) ? (-index - 1) : (index + 1);
1856        }
1857    }
1858
1859    /**
1860     * Returns the unscaled value (mantissa) of this {@code BigDecimal} instance
1861     * as a {@code BigInteger}. The unscaled value can be computed as {@code
1862     * this} 10^(scale).
1863     *
1864     * @return unscaled value (this * 10^(scale)).
1865     */
1866    public BigInteger unscaledValue() {
1867        return getUnscaledValue();
1868    }
1869
1870    /**
1871     * Returns a new {@code BigDecimal} whose value is {@code this}, rounded
1872     * according to the passed context {@code mc}.
1873     * <p>
1874     * If {@code mc.precision = 0}, then no rounding is performed.
1875     * <p>
1876     * If {@code mc.precision > 0} and {@code mc.roundingMode == UNNECESSARY},
1877     * then an {@code ArithmeticException} is thrown if the result cannot be
1878     * represented exactly within the given precision.
1879     *
1880     * @param mc
1881     *            rounding mode and precision for the result of this operation.
1882     * @return {@code this} rounded according to the passed context.
1883     * @throws ArithmeticException
1884     *             if {@code mc.precision > 0} and {@code mc.roundingMode ==
1885     *             UNNECESSARY} and this cannot be represented within the given
1886     *             precision.
1887     */
1888    public BigDecimal round(MathContext mc) {
1889        BigDecimal thisBD = new BigDecimal(getUnscaledValue(), scale);
1890
1891        thisBD.inplaceRound(mc);
1892        return thisBD;
1893    }
1894
1895    /**
1896     * Returns a new {@code BigDecimal} instance with the specified scale.
1897     * <p>
1898     * If the new scale is greater than the old scale, then additional zeros are
1899     * added to the unscaled value. In this case no rounding is necessary.
1900     * <p>
1901     * If the new scale is smaller than the old scale, then trailing digits are
1902     * removed. If these trailing digits are not zero, then the remaining
1903     * unscaled value has to be rounded. For this rounding operation the
1904     * specified rounding mode is used.
1905     *
1906     * @param newScale
1907     *            scale of the result returned.
1908     * @param roundingMode
1909     *            rounding mode to be used to round the result.
1910     * @return a new {@code BigDecimal} instance with the specified scale.
1911     * @throws NullPointerException
1912     *             if {@code roundingMode == null}.
1913     * @throws ArithmeticException
1914     *             if {@code roundingMode == ROUND_UNNECESSARY} and rounding is
1915     *             necessary according to the given scale.
1916     */
1917    public BigDecimal setScale(int newScale, RoundingMode roundingMode) {
1918        if (roundingMode == null) {
1919            throw new NullPointerException("roundingMode == null");
1920        }
1921        long diffScale = newScale - (long)scale;
1922        // Let be:  'this' = [u,s]
1923        if(diffScale == 0) {
1924            return this;
1925        }
1926        if(diffScale > 0) {
1927        // return  [u * 10^(s2 - s), newScale]
1928            if(diffScale < MathUtils.LONG_POWERS_OF_TEN.length &&
1929                    (this.bitLength + LONG_POWERS_OF_TEN_BIT_LENGTH[(int)diffScale]) < 64 ) {
1930                return valueOf(this.smallValue*MathUtils.LONG_POWERS_OF_TEN[(int)diffScale],newScale);
1931            }
1932            return new BigDecimal(Multiplication.multiplyByTenPow(getUnscaledValue(),(int)diffScale), newScale);
1933        }
1934        // diffScale < 0
1935        // return  [u,s] / [1,newScale]  with the appropriate scale and rounding
1936        if(this.bitLength < 64 && -diffScale < MathUtils.LONG_POWERS_OF_TEN.length) {
1937            return dividePrimitiveLongs(this.smallValue, MathUtils.LONG_POWERS_OF_TEN[(int)-diffScale], newScale,roundingMode);
1938        }
1939        return divideBigIntegers(this.getUnscaledValue(),Multiplication.powerOf10(-diffScale),newScale,roundingMode);
1940    }
1941
1942    /**
1943     * Returns a new {@code BigDecimal} instance with the specified scale.
1944     * <p>
1945     * If the new scale is greater than the old scale, then additional zeros are
1946     * added to the unscaled value. In this case no rounding is necessary.
1947     * <p>
1948     * If the new scale is smaller than the old scale, then trailing digits are
1949     * removed. If these trailing digits are not zero, then the remaining
1950     * unscaled value has to be rounded. For this rounding operation the
1951     * specified rounding mode is used.
1952     *
1953     * @param newScale
1954     *            scale of the result returned.
1955     * @param roundingMode
1956     *            rounding mode to be used to round the result.
1957     * @return a new {@code BigDecimal} instance with the specified scale.
1958     * @throws IllegalArgumentException
1959     *             if {@code roundingMode} is not a valid rounding mode.
1960     * @throws ArithmeticException
1961     *             if {@code roundingMode == ROUND_UNNECESSARY} and rounding is
1962     *             necessary according to the given scale.
1963     */
1964    public BigDecimal setScale(int newScale, int roundingMode) {
1965        return setScale(newScale, RoundingMode.valueOf(roundingMode));
1966    }
1967
1968    /**
1969     * Returns a new {@code BigDecimal} instance with the specified scale. If
1970     * the new scale is greater than the old scale, then additional zeros are
1971     * added to the unscaled value. If the new scale is smaller than the old
1972     * scale, then trailing zeros are removed. If the trailing digits are not
1973     * zeros then an ArithmeticException is thrown.
1974     * <p>
1975     * If no exception is thrown, then the following equation holds: {@code
1976     * x.setScale(s).compareTo(x) == 0}.
1977     *
1978     * @param newScale
1979     *            scale of the result returned.
1980     * @return a new {@code BigDecimal} instance with the specified scale.
1981     * @throws ArithmeticException
1982     *             if rounding would be necessary.
1983     */
1984    public BigDecimal setScale(int newScale) {
1985        return setScale(newScale, RoundingMode.UNNECESSARY);
1986    }
1987
1988    /**
1989     * Returns a new {@code BigDecimal} instance where the decimal point has
1990     * been moved {@code n} places to the left. If {@code n < 0} then the
1991     * decimal point is moved {@code -n} places to the right.
1992     * <p>
1993     * The result is obtained by changing its scale. If the scale of the result
1994     * becomes negative, then its precision is increased such that the scale is
1995     * zero.
1996     * <p>
1997     * Note, that {@code movePointLeft(0)} returns a result which is
1998     * mathematically equivalent, but which has {@code scale >= 0}.
1999     *
2000     * @param n
2001     *            number of placed the decimal point has to be moved.
2002     * @return {@code this * 10^(-n}).
2003     */
2004    public BigDecimal movePointLeft(int n) {
2005        return movePoint(scale + (long)n);
2006    }
2007
2008    private BigDecimal movePoint(long newScale) {
2009        if (isZero()) {
2010            return zeroScaledBy(Math.max(newScale, 0));
2011        }
2012        /*
2013         * When: 'n'== Integer.MIN_VALUE isn't possible to call to
2014         * movePointRight(-n) since -Integer.MIN_VALUE == Integer.MIN_VALUE
2015         */
2016        if(newScale >= 0) {
2017            if(bitLength < 64) {
2018                return valueOf(smallValue, safeLongToInt(newScale));
2019            }
2020            return new BigDecimal(getUnscaledValue(), safeLongToInt(newScale));
2021        }
2022        if(-newScale < MathUtils.LONG_POWERS_OF_TEN.length &&
2023                bitLength + LONG_POWERS_OF_TEN_BIT_LENGTH[(int)-newScale] < 64 ) {
2024            return valueOf(smallValue*MathUtils.LONG_POWERS_OF_TEN[(int)-newScale],0);
2025        }
2026        return new BigDecimal(Multiplication.multiplyByTenPow(
2027                getUnscaledValue(), safeLongToInt(-newScale)), 0);
2028    }
2029
2030    /**
2031     * Returns a new {@code BigDecimal} instance where the decimal point has
2032     * been moved {@code n} places to the right. If {@code n < 0} then the
2033     * decimal point is moved {@code -n} places to the left.
2034     * <p>
2035     * The result is obtained by changing its scale. If the scale of the result
2036     * becomes negative, then its precision is increased such that the scale is
2037     * zero.
2038     * <p>
2039     * Note, that {@code movePointRight(0)} returns a result which is
2040     * mathematically equivalent, but which has scale >= 0.
2041     *
2042     * @param n
2043     *            number of placed the decimal point has to be moved.
2044     * @return {@code this * 10^n}.
2045     */
2046    public BigDecimal movePointRight(int n) {
2047        return movePoint(scale - (long)n);
2048    }
2049
2050    /**
2051     * Returns a new {@code BigDecimal} whose value is {@code this} 10^{@code n}.
2052     * The scale of the result is {@code this.scale()} - {@code n}.
2053     * The precision of the result is the precision of {@code this}.
2054     * <p>
2055     * This method has the same effect as {@link #movePointRight}, except that
2056     * the precision is not changed.
2057     *
2058     * @param n
2059     *            number of places the decimal point has to be moved.
2060     * @return {@code this * 10^n}
2061     */
2062    public BigDecimal scaleByPowerOfTen(int n) {
2063        long newScale = scale - (long)n;
2064        if(bitLength < 64) {
2065            //Taking care when a 0 is to be scaled
2066            if( smallValue==0  ){
2067                return zeroScaledBy( newScale );
2068            }
2069            return valueOf(smallValue, safeLongToInt(newScale));
2070        }
2071        return new BigDecimal(getUnscaledValue(), safeLongToInt(newScale));
2072    }
2073
2074    /**
2075     * Returns a new {@code BigDecimal} instance with the same value as {@code
2076     * this} but with a unscaled value where the trailing zeros have been
2077     * removed. If the unscaled value of {@code this} has n trailing zeros, then
2078     * the scale and the precision of the result has been reduced by n.
2079     *
2080     * @return a new {@code BigDecimal} instance equivalent to this where the
2081     *         trailing zeros of the unscaled value have been removed.
2082     */
2083    public BigDecimal stripTrailingZeros() {
2084        int i = 1; // 1 <= i <= 18
2085        int lastPow = TEN_POW.length - 1;
2086        long newScale = scale;
2087
2088        if (isZero()) {
2089            // Preserve RI compatibility, so BigDecimal.equals (which checks
2090            // value *and* scale) continues to work.
2091            return this;
2092        }
2093        BigInteger strippedBI = getUnscaledValue();
2094        BigInteger[] quotAndRem;
2095
2096        // while the number is even...
2097        while (!strippedBI.testBit(0)) {
2098            // To divide by 10^i
2099            quotAndRem = strippedBI.divideAndRemainder(TEN_POW[i]);
2100            // To look the remainder
2101            if (quotAndRem[1].signum() == 0) {
2102                // To adjust the scale
2103                newScale -= i;
2104                if (i < lastPow) {
2105                    // To set to the next power
2106                    i++;
2107                }
2108                strippedBI = quotAndRem[0];
2109            } else {
2110                if (i == 1) {
2111                    // 'this' has no more trailing zeros
2112                    break;
2113                }
2114                // To set to the smallest power of ten
2115                i = 1;
2116            }
2117        }
2118        return new BigDecimal(strippedBI, safeLongToInt(newScale));
2119    }
2120
2121    /**
2122     * Compares this {@code BigDecimal} with {@code val}. Returns one of the
2123     * three values {@code 1}, {@code 0}, or {@code -1}. The method behaves as
2124     * if {@code this.subtract(val)} is computed. If this difference is > 0 then
2125     * 1 is returned, if the difference is < 0 then -1 is returned, and if the
2126     * difference is 0 then 0 is returned. This means, that if two decimal
2127     * instances are compared which are equal in value but differ in scale, then
2128     * these two instances are considered as equal.
2129     *
2130     * @param val
2131     *            value to be compared with {@code this}.
2132     * @return {@code 1} if {@code this > val}, {@code -1} if {@code this < val},
2133     *         {@code 0} if {@code this == val}.
2134     * @throws NullPointerException
2135     *             if {@code val == null}.
2136     */
2137    public int compareTo(BigDecimal val) {
2138        int thisSign = signum();
2139        int valueSign = val.signum();
2140
2141        if( thisSign == valueSign) {
2142            if(this.scale == val.scale && this.bitLength<64 && val.bitLength<64 ) {
2143                return (smallValue < val.smallValue) ? -1 : (smallValue > val.smallValue) ? 1 : 0;
2144            }
2145            long diffScale = (long)this.scale - val.scale;
2146            int diffPrecision = this.approxPrecision() - val.approxPrecision();
2147            if (diffPrecision > diffScale + 1) {
2148                return thisSign;
2149            } else if (diffPrecision < diffScale - 1) {
2150                return -thisSign;
2151            } else {// thisSign == val.signum()  and  diffPrecision is aprox. diffScale
2152                BigInteger thisUnscaled = this.getUnscaledValue();
2153                BigInteger valUnscaled = val.getUnscaledValue();
2154                // If any of both precision is bigger, append zeros to the shorter one
2155                if (diffScale < 0) {
2156                    thisUnscaled = thisUnscaled.multiply(Multiplication.powerOf10(-diffScale));
2157                } else if (diffScale > 0) {
2158                    valUnscaled = valUnscaled.multiply(Multiplication.powerOf10(diffScale));
2159                }
2160                return thisUnscaled.compareTo(valUnscaled);
2161            }
2162        } else if (thisSign < valueSign) {
2163            return -1;
2164        } else  {
2165            return 1;
2166        }
2167    }
2168
2169    /**
2170     * Returns {@code true} if {@code x} is a {@code BigDecimal} instance and if
2171     * this instance is equal to this big decimal. Two big decimals are equal if
2172     * their unscaled value and their scale is equal. For example, 1.0
2173     * (10*10^(-1)) is not equal to 1.00 (100*10^(-2)). Similarly, zero
2174     * instances are not equal if their scale differs.
2175     *
2176     * @param x
2177     *            object to be compared with {@code this}.
2178     * @return true if {@code x} is a {@code BigDecimal} and {@code this == x}.
2179     */
2180    @Override
2181    public boolean equals(Object x) {
2182        if (this == x) {
2183            return true;
2184        }
2185        if (x instanceof BigDecimal) {
2186            BigDecimal x1 = (BigDecimal) x;
2187            return x1.scale == scale
2188                   && (bitLength < 64 ? (x1.smallValue == smallValue)
2189                    : intVal.equals(x1.intVal));
2190
2191
2192        }
2193        return false;
2194    }
2195
2196    /**
2197     * Returns the minimum of this {@code BigDecimal} and {@code val}.
2198     *
2199     * @param val
2200     *            value to be used to compute the minimum with this.
2201     * @return {@code min(this, val}.
2202     * @throws NullPointerException
2203     *             if {@code val == null}.
2204     */
2205    public BigDecimal min(BigDecimal val) {
2206        return ((compareTo(val) <= 0) ? this : val);
2207    }
2208
2209    /**
2210     * Returns the maximum of this {@code BigDecimal} and {@code val}.
2211     *
2212     * @param val
2213     *            value to be used to compute the maximum with this.
2214     * @return {@code max(this, val}.
2215     * @throws NullPointerException
2216     *             if {@code val == null}.
2217     */
2218    public BigDecimal max(BigDecimal val) {
2219        return ((compareTo(val) >= 0) ? this : val);
2220    }
2221
2222    /**
2223     * Returns a hash code for this {@code BigDecimal}.
2224     *
2225     * @return hash code for {@code this}.
2226     */
2227    @Override
2228    public int hashCode() {
2229        if (hashCode != 0) {
2230            return hashCode;
2231        }
2232        if (bitLength < 64) {
2233            hashCode = (int)(smallValue & 0xffffffff);
2234            hashCode = 33 * hashCode +  (int)((smallValue >> 32) & 0xffffffff);
2235            hashCode = 17 * hashCode + scale;
2236            return hashCode;
2237        }
2238        hashCode = 17 * intVal.hashCode() + scale;
2239        return hashCode;
2240    }
2241
2242    /**
2243     * Returns a canonical string representation of this {@code BigDecimal}. If
2244     * necessary, scientific notation is used. This representation always prints
2245     * all significant digits of this value.
2246     * <p>
2247     * If the scale is negative or if {@code scale - precision >= 6} then
2248     * scientific notation is used.
2249     *
2250     * @return a string representation of {@code this} in scientific notation if
2251     *         necessary.
2252     */
2253    @Override
2254    public String toString() {
2255        if (toStringImage != null) {
2256            return toStringImage;
2257        }
2258        if(bitLength < 32) {
2259            toStringImage = Conversion.toDecimalScaledString(smallValue,scale);
2260            return toStringImage;
2261        }
2262        String intString = getUnscaledValue().toString();
2263        if (scale == 0) {
2264            return intString;
2265        }
2266        int begin = (getUnscaledValue().signum() < 0) ? 2 : 1;
2267        int end = intString.length();
2268        long exponent = -(long)scale + end - begin;
2269        StringBuilder result = new StringBuilder();
2270
2271        result.append(intString);
2272        if ((scale > 0) && (exponent >= -6)) {
2273            if (exponent >= 0) {
2274                result.insert(end - scale, '.');
2275            } else {
2276                result.insert(begin - 1, "0.");
2277                result.insert(begin + 1, CH_ZEROS, 0, -(int)exponent - 1);
2278            }
2279        } else {
2280            if (end - begin >= 1) {
2281                result.insert(begin, '.');
2282                end++;
2283            }
2284            result.insert(end, 'E');
2285            if (exponent > 0) {
2286                result.insert(++end, '+');
2287            }
2288            result.insert(++end, Long.toString(exponent));
2289        }
2290        toStringImage = result.toString();
2291        return toStringImage;
2292    }
2293
2294    /**
2295     * Returns a string representation of this {@code BigDecimal}. This
2296     * representation always prints all significant digits of this value.
2297     * <p>
2298     * If the scale is negative or if {@code scale - precision >= 6} then
2299     * engineering notation is used. Engineering notation is similar to the
2300     * scientific notation except that the exponent is made to be a multiple of
2301     * 3 such that the integer part is >= 1 and < 1000.
2302     *
2303     * @return a string representation of {@code this} in engineering notation
2304     *         if necessary.
2305     */
2306    public String toEngineeringString() {
2307        String intString = getUnscaledValue().toString();
2308        if (scale == 0) {
2309            return intString;
2310        }
2311        int begin = (getUnscaledValue().signum() < 0) ? 2 : 1;
2312        int end = intString.length();
2313        long exponent = -(long)scale + end - begin;
2314        StringBuilder result = new StringBuilder(intString);
2315
2316        if ((scale > 0) && (exponent >= -6)) {
2317            if (exponent >= 0) {
2318                result.insert(end - scale, '.');
2319            } else {
2320                result.insert(begin - 1, "0.");
2321                result.insert(begin + 1, CH_ZEROS, 0, -(int)exponent - 1);
2322            }
2323        } else {
2324            int delta = end - begin;
2325            int rem = (int)(exponent % 3);
2326
2327            if (rem != 0) {
2328                // adjust exponent so it is a multiple of three
2329                if (getUnscaledValue().signum() == 0) {
2330                    // zero value
2331                    rem = (rem < 0) ? -rem : 3 - rem;
2332                    exponent += rem;
2333                } else {
2334                    // nonzero value
2335                    rem = (rem < 0) ? rem + 3 : rem;
2336                    exponent -= rem;
2337                    begin += rem;
2338                }
2339                if (delta < 3) {
2340                    for (int i = rem - delta; i > 0; i--) {
2341                        result.insert(end++, '0');
2342                    }
2343                }
2344            }
2345            if (end - begin >= 1) {
2346                result.insert(begin, '.');
2347                end++;
2348            }
2349            if (exponent != 0) {
2350                result.insert(end, 'E');
2351                if (exponent > 0) {
2352                    result.insert(++end, '+');
2353                }
2354                result.insert(++end, Long.toString(exponent));
2355            }
2356        }
2357        return result.toString();
2358    }
2359
2360    /**
2361     * Returns a string representation of this {@code BigDecimal}. No scientific
2362     * notation is used. This methods adds zeros where necessary.
2363     * <p>
2364     * If this string representation is used to create a new instance, this
2365     * instance is generally not identical to {@code this} as the precision
2366     * changes.
2367     * <p>
2368     * {@code x.equals(new BigDecimal(x.toPlainString())} usually returns
2369     * {@code false}.
2370     * <p>
2371     * {@code x.compareTo(new BigDecimal(x.toPlainString())} returns {@code 0}.
2372     *
2373     * @return a string representation of {@code this} without exponent part.
2374     */
2375    public String toPlainString() {
2376        String intStr = getUnscaledValue().toString();
2377        if ((scale == 0) || ((isZero()) && (scale < 0))) {
2378            return intStr;
2379        }
2380        int begin = (signum() < 0) ? 1 : 0;
2381        int delta = scale;
2382        // We take space for all digits, plus a possible decimal point, plus 'scale'
2383        StringBuilder result = new StringBuilder(intStr.length() + 1 + Math.abs(scale));
2384
2385        if (begin == 1) {
2386            // If the number is negative, we insert a '-' character at front
2387            result.append('-');
2388        }
2389        if (scale > 0) {
2390            delta -= (intStr.length() - begin);
2391            if (delta >= 0) {
2392                result.append("0.");
2393                // To append zeros after the decimal point
2394                for (; delta > CH_ZEROS.length; delta -= CH_ZEROS.length) {
2395                    result.append(CH_ZEROS);
2396                }
2397                result.append(CH_ZEROS, 0, delta);
2398                result.append(intStr.substring(begin));
2399            } else {
2400                delta = begin - delta;
2401                result.append(intStr.substring(begin, delta));
2402                result.append('.');
2403                result.append(intStr.substring(delta));
2404            }
2405        } else {// (scale <= 0)
2406            result.append(intStr.substring(begin));
2407            // To append trailing zeros
2408            for (; delta < -CH_ZEROS.length; delta += CH_ZEROS.length) {
2409                result.append(CH_ZEROS);
2410            }
2411            result.append(CH_ZEROS, 0, -delta);
2412        }
2413        return result.toString();
2414    }
2415
2416    /**
2417     * Returns this {@code BigDecimal} as a big integer instance. A fractional
2418     * part is discarded.
2419     *
2420     * @return this {@code BigDecimal} as a big integer instance.
2421     */
2422    public BigInteger toBigInteger() {
2423        if ((scale == 0) || (isZero())) {
2424            return getUnscaledValue();
2425        } else if (scale < 0) {
2426            return getUnscaledValue().multiply(Multiplication.powerOf10(-(long)scale));
2427        } else {// (scale > 0)
2428            return getUnscaledValue().divide(Multiplication.powerOf10(scale));
2429        }
2430    }
2431
2432    /**
2433     * Returns this {@code BigDecimal} as a big integer instance if it has no
2434     * fractional part. If this {@code BigDecimal} has a fractional part, i.e.
2435     * if rounding would be necessary, an {@code ArithmeticException} is thrown.
2436     *
2437     * @return this {@code BigDecimal} as a big integer value.
2438     * @throws ArithmeticException
2439     *             if rounding is necessary.
2440     */
2441    public BigInteger toBigIntegerExact() {
2442        if ((scale == 0) || (isZero())) {
2443            return getUnscaledValue();
2444        } else if (scale < 0) {
2445            return getUnscaledValue().multiply(Multiplication.powerOf10(-(long)scale));
2446        } else {// (scale > 0)
2447            BigInteger[] integerAndFraction;
2448            // An optimization before do a heavy division
2449            if ((scale > approxPrecision()) || (scale > getUnscaledValue().getLowestSetBit())) {
2450                throw new ArithmeticException("Rounding necessary");
2451            }
2452            integerAndFraction = getUnscaledValue().divideAndRemainder(Multiplication.powerOf10(scale));
2453            if (integerAndFraction[1].signum() != 0) {
2454                // It exists a non-zero fractional part
2455                throw new ArithmeticException("Rounding necessary");
2456            }
2457            return integerAndFraction[0];
2458        }
2459    }
2460
2461    /**
2462     * Returns this {@code BigDecimal} as an long value. Any fractional part is
2463     * discarded. If the integral part of {@code this} is too big to be
2464     * represented as an long, then {@code this} % 2^64 is returned.
2465     *
2466     * @return this {@code BigDecimal} as a long value.
2467     */
2468    @Override
2469    public long longValue() {
2470        /*
2471         * If scale <= -64 there are at least 64 trailing bits zero in
2472         * 10^(-scale). If the scale is positive and very large the long value
2473         * could be zero.
2474         */
2475        return ((scale <= -64) || (scale > approxPrecision()) ? 0L
2476                : toBigInteger().longValue());
2477    }
2478
2479    /**
2480     * Returns this {@code BigDecimal} as a long value if it has no fractional
2481     * part and if its value fits to the int range ([-2^{63}..2^{63}-1]). If
2482     * these conditions are not met, an {@code ArithmeticException} is thrown.
2483     *
2484     * @return this {@code BigDecimal} as a long value.
2485     * @throws ArithmeticException
2486     *             if rounding is necessary or the number doesn't fit in a long.
2487     */
2488    public long longValueExact() {
2489        return valueExact(64);
2490    }
2491
2492    /**
2493     * Returns this {@code BigDecimal} as an int value. Any fractional part is
2494     * discarded. If the integral part of {@code this} is too big to be
2495     * represented as an int, then {@code this} % 2^32 is returned.
2496     *
2497     * @return this {@code BigDecimal} as a int value.
2498     */
2499    @Override
2500    public int intValue() {
2501        /*
2502         * If scale <= -32 there are at least 32 trailing bits zero in
2503         * 10^(-scale). If the scale is positive and very large the long value
2504         * could be zero.
2505         */
2506        return ((scale <= -32) || (scale > approxPrecision())
2507        ? 0
2508                : toBigInteger().intValue());
2509    }
2510
2511    /**
2512     * Returns this {@code BigDecimal} as a int value if it has no fractional
2513     * part and if its value fits to the int range ([-2^{31}..2^{31}-1]). If
2514     * these conditions are not met, an {@code ArithmeticException} is thrown.
2515     *
2516     * @return this {@code BigDecimal} as a int value.
2517     * @throws ArithmeticException
2518     *             if rounding is necessary or the number doesn't fit in a int.
2519     */
2520    public int intValueExact() {
2521        return (int)valueExact(32);
2522    }
2523
2524    /**
2525     * Returns this {@code BigDecimal} as a short value if it has no fractional
2526     * part and if its value fits to the short range ([-2^{15}..2^{15}-1]). If
2527     * these conditions are not met, an {@code ArithmeticException} is thrown.
2528     *
2529     * @return this {@code BigDecimal} as a short value.
2530     * @throws ArithmeticException
2531     *             if rounding is necessary of the number doesn't fit in a
2532     *             short.
2533     */
2534    public short shortValueExact() {
2535        return (short)valueExact(16);
2536    }
2537
2538    /**
2539     * Returns this {@code BigDecimal} as a byte value if it has no fractional
2540     * part and if its value fits to the byte range ([-128..127]). If these
2541     * conditions are not met, an {@code ArithmeticException} is thrown.
2542     *
2543     * @return this {@code BigDecimal} as a byte value.
2544     * @throws ArithmeticException
2545     *             if rounding is necessary or the number doesn't fit in a byte.
2546     */
2547    public byte byteValueExact() {
2548        return (byte)valueExact(8);
2549    }
2550
2551    /**
2552     * Returns this {@code BigDecimal} as a float value. If {@code this} is too
2553     * big to be represented as an float, then {@code Float.POSITIVE_INFINITY}
2554     * or {@code Float.NEGATIVE_INFINITY} is returned.
2555     * <p>
2556     * Note, that if the unscaled value has more than 24 significant digits,
2557     * then this decimal cannot be represented exactly in a float variable. In
2558     * this case the result is rounded.
2559     * <p>
2560     * For example, if the instance {@code x1 = new BigDecimal("0.1")} cannot be
2561     * represented exactly as a float, and thus {@code x1.equals(new
2562     * BigDecimal(x1.folatValue())} returns {@code false} for this case.
2563     * <p>
2564     * Similarly, if the instance {@code new BigDecimal(16777217)} is converted
2565     * to a float, the result is {@code 1.6777216E}7.
2566     *
2567     * @return this {@code BigDecimal} as a float value.
2568     */
2569    @Override
2570    public float floatValue() {
2571        /* A similar code like in doubleValue() could be repeated here,
2572         * but this simple implementation is quite efficient. */
2573        float floatResult = signum();
2574        long powerOfTwo = this.bitLength - (long)(scale / LOG10_2);
2575        if ((powerOfTwo < -149) || (floatResult == 0.0f)) {
2576            // Cases which 'this' is very small
2577            floatResult *= 0.0f;
2578        } else if (powerOfTwo > 129) {
2579            // Cases which 'this' is very large
2580            floatResult *= Float.POSITIVE_INFINITY;
2581        } else {
2582            floatResult = (float)doubleValue();
2583        }
2584        return floatResult;
2585    }
2586
2587    /**
2588     * Returns this {@code BigDecimal} as a double value. If {@code this} is too
2589     * big to be represented as an float, then {@code Double.POSITIVE_INFINITY}
2590     * or {@code Double.NEGATIVE_INFINITY} is returned.
2591     * <p>
2592     * Note, that if the unscaled value has more than 53 significant digits,
2593     * then this decimal cannot be represented exactly in a double variable. In
2594     * this case the result is rounded.
2595     * <p>
2596     * For example, if the instance {@code x1 = new BigDecimal("0.1")} cannot be
2597     * represented exactly as a double, and thus {@code x1.equals(new
2598     * BigDecimal(x1.doubleValue())} returns {@code false} for this case.
2599     * <p>
2600     * Similarly, if the instance {@code new BigDecimal(9007199254740993L)} is
2601     * converted to a double, the result is {@code 9.007199254740992E15}.
2602     * <p>
2603     *
2604     * @return this {@code BigDecimal} as a double value.
2605     */
2606    @Override
2607    public double doubleValue() {
2608        int sign = signum();
2609        int exponent = 1076; // bias + 53
2610        int lowestSetBit;
2611        int discardedSize;
2612        long powerOfTwo = this.bitLength - (long)(scale / LOG10_2);
2613        long bits; // IEEE-754 Standard
2614        long tempBits; // for temporal calculations
2615        BigInteger mantissa;
2616
2617        if ((powerOfTwo < -1074) || (sign == 0)) {
2618            // Cases which 'this' is very small
2619            return (sign * 0.0d);
2620        } else if (powerOfTwo > 1025) {
2621            // Cases which 'this' is very large
2622            return (sign * Double.POSITIVE_INFINITY);
2623        }
2624        mantissa = getUnscaledValue().abs();
2625        // Let be:  this = [u,s], with s > 0
2626        if (scale <= 0) {
2627            // mantissa = abs(u) * 10^s
2628            mantissa = mantissa.multiply(Multiplication.powerOf10(-scale));
2629        } else {// (scale > 0)
2630            BigInteger quotAndRem[];
2631            BigInteger powerOfTen = Multiplication.powerOf10(scale);
2632            int k = 100 - (int)powerOfTwo;
2633            int compRem;
2634
2635            if (k > 0) {
2636                /* Computing (mantissa * 2^k) , where 'k' is a enough big
2637                 * power of '2' to can divide by 10^s */
2638                mantissa = mantissa.shiftLeft(k);
2639                exponent -= k;
2640            }
2641            // Computing (mantissa * 2^k) / 10^s
2642            quotAndRem = mantissa.divideAndRemainder(powerOfTen);
2643            // To check if the fractional part >= 0.5
2644            compRem = quotAndRem[1].shiftLeftOneBit().compareTo(powerOfTen);
2645            // To add two rounded bits at end of mantissa
2646            mantissa = quotAndRem[0].shiftLeft(2).add(
2647                    BigInteger.valueOf((compRem * (compRem + 3)) / 2 + 1));
2648            exponent -= 2;
2649        }
2650        lowestSetBit = mantissa.getLowestSetBit();
2651        discardedSize = mantissa.bitLength() - 54;
2652        if (discardedSize > 0) {// (n > 54)
2653            // mantissa = (abs(u) * 10^s) >> (n - 54)
2654            bits = mantissa.shiftRight(discardedSize).longValue();
2655            tempBits = bits;
2656            // #bits = 54, to check if the discarded fraction produces a carry
2657            if ((((bits & 1) == 1) && (lowestSetBit < discardedSize))
2658                    || ((bits & 3) == 3)) {
2659                bits += 2;
2660            }
2661        } else {// (n <= 54)
2662            // mantissa = (abs(u) * 10^s) << (54 - n)
2663            bits = mantissa.longValue() << -discardedSize;
2664            tempBits = bits;
2665            // #bits = 54, to check if the discarded fraction produces a carry:
2666            if ((bits & 3) == 3) {
2667                bits += 2;
2668            }
2669        }
2670        // Testing bit 54 to check if the carry creates a new binary digit
2671        if ((bits & 0x40000000000000L) == 0) {
2672            // To drop the last bit of mantissa (first discarded)
2673            bits >>= 1;
2674            // exponent = 2^(s-n+53+bias)
2675            exponent += discardedSize;
2676        } else {// #bits = 54
2677            bits >>= 2;
2678            exponent += discardedSize + 1;
2679        }
2680        // To test if the 53-bits number fits in 'double'
2681        if (exponent > 2046) {// (exponent - bias > 1023)
2682            return (sign * Double.POSITIVE_INFINITY);
2683        } else if (exponent <= 0) {// (exponent - bias <= -1023)
2684            // Denormalized numbers (having exponent == 0)
2685            if (exponent < -53) {// exponent - bias < -1076
2686                return (sign * 0.0d);
2687            }
2688            // -1076 <= exponent - bias <= -1023
2689            // To discard '- exponent + 1' bits
2690            bits = tempBits >> 1;
2691            tempBits = bits & (-1L >>> (63 + exponent));
2692            bits >>= (-exponent );
2693            // To test if after discard bits, a new carry is generated
2694            if (((bits & 3) == 3) || (((bits & 1) == 1) && (tempBits != 0)
2695            && (lowestSetBit < discardedSize))) {
2696                bits += 1;
2697            }
2698            exponent = 0;
2699            bits >>= 1;
2700        }
2701        // Construct the 64 double bits: [sign(1), exponent(11), mantissa(52)]
2702        bits = (sign & 0x8000000000000000L) | ((long)exponent << 52)
2703                | (bits & 0xFFFFFFFFFFFFFL);
2704        return Double.longBitsToDouble(bits);
2705    }
2706
2707    /**
2708     * Returns the unit in the last place (ULP) of this {@code BigDecimal}
2709     * instance. An ULP is the distance to the nearest big decimal with the same
2710     * precision.
2711     * <p>
2712     * The amount of a rounding error in the evaluation of a floating-point
2713     * operation is often expressed in ULPs. An error of 1 ULP is often seen as
2714     * a tolerable error.
2715     * <p>
2716     * For class {@code BigDecimal}, the ULP of a number is simply 10^(-scale).
2717     * <p>
2718     * For example, {@code new BigDecimal(0.1).ulp()} returns {@code 1E-55}.
2719     *
2720     * @return unit in the last place (ULP) of this {@code BigDecimal} instance.
2721     */
2722    public BigDecimal ulp() {
2723        return valueOf(1, scale);
2724    }
2725
2726    /* Private Methods */
2727
2728    /**
2729     * It does all rounding work of the public method
2730     * {@code round(MathContext)}, performing an inplace rounding
2731     * without creating a new object.
2732     *
2733     * @param mc
2734     *            the {@code MathContext} for perform the rounding.
2735     * @see #round(MathContext)
2736     */
2737    private void inplaceRound(MathContext mc) {
2738        int mcPrecision = mc.getPrecision();
2739        if (approxPrecision() < mcPrecision || mcPrecision == 0) {
2740            return;
2741        }
2742        int discardedPrecision = precision() - mcPrecision;
2743        // If no rounding is necessary it returns immediately
2744        if ((discardedPrecision <= 0)) {
2745            return;
2746        }
2747        // When the number is small perform an efficient rounding
2748        if (this.bitLength < 64) {
2749            smallRound(mc, discardedPrecision);
2750            return;
2751        }
2752        // Getting the integer part and the discarded fraction
2753        BigInteger sizeOfFraction = Multiplication.powerOf10(discardedPrecision);
2754        BigInteger[] integerAndFraction = getUnscaledValue().divideAndRemainder(sizeOfFraction);
2755        long newScale = (long)scale - discardedPrecision;
2756        int compRem;
2757        BigDecimal tempBD;
2758        // If the discarded fraction is non-zero, perform rounding
2759        if (integerAndFraction[1].signum() != 0) {
2760            // To check if the discarded fraction >= 0.5
2761            compRem = (integerAndFraction[1].abs().shiftLeftOneBit().compareTo(sizeOfFraction));
2762            // To look if there is a carry
2763            compRem =  roundingBehavior( integerAndFraction[0].testBit(0) ? 1 : 0,
2764                    integerAndFraction[1].signum() * (5 + compRem),
2765                    mc.getRoundingMode());
2766            if (compRem != 0) {
2767                integerAndFraction[0] = integerAndFraction[0].add(BigInteger.valueOf(compRem));
2768            }
2769            tempBD = new BigDecimal(integerAndFraction[0]);
2770            // If after to add the increment the precision changed, we normalize the size
2771            if (tempBD.precision() > mcPrecision) {
2772                integerAndFraction[0] = integerAndFraction[0].divide(BigInteger.TEN);
2773                newScale--;
2774            }
2775        }
2776        // To update all internal fields
2777        scale = safeLongToInt(newScale);
2778        precision = mcPrecision;
2779        setUnscaledValue(integerAndFraction[0]);
2780    }
2781
2782    private static int longCompareTo(long value1, long value2) {
2783        return value1 > value2 ? 1 : (value1 < value2 ? -1 : 0);
2784    }
2785    /**
2786     * This method implements an efficient rounding for numbers which unscaled
2787     * value fits in the type {@code long}.
2788     *
2789     * @param mc
2790     *            the context to use
2791     * @param discardedPrecision
2792     *            the number of decimal digits that are discarded
2793     * @see #round(MathContext)
2794     */
2795    private void smallRound(MathContext mc, int discardedPrecision) {
2796        long sizeOfFraction = MathUtils.LONG_POWERS_OF_TEN[discardedPrecision];
2797        long newScale = (long)scale - discardedPrecision;
2798        long unscaledVal = smallValue;
2799        // Getting the integer part and the discarded fraction
2800        long integer = unscaledVal / sizeOfFraction;
2801        long fraction = unscaledVal % sizeOfFraction;
2802        int compRem;
2803        // If the discarded fraction is non-zero perform rounding
2804        if (fraction != 0) {
2805            // To check if the discarded fraction >= 0.5
2806            compRem = longCompareTo(Math.abs(fraction) * 2, sizeOfFraction);
2807            // To look if there is a carry
2808            integer += roundingBehavior( ((int)integer) & 1,
2809                    Long.signum(fraction) * (5 + compRem),
2810                    mc.getRoundingMode());
2811            // If after to add the increment the precision changed, we normalize the size
2812            if (Math.log10(Math.abs(integer)) >= mc.getPrecision()) {
2813                integer /= 10;
2814                newScale--;
2815            }
2816        }
2817        // To update all internal fields
2818        scale = safeLongToInt(newScale);
2819        precision = mc.getPrecision();
2820        smallValue = integer;
2821        bitLength = bitLength(integer);
2822        intVal = null;
2823    }
2824
2825    /**
2826     * Return an increment that can be -1,0 or 1, depending of
2827     * {@code roundingMode}.
2828     *
2829     * @param parityBit
2830     *            can be 0 or 1, it's only used in the case
2831     *            {@code HALF_EVEN}
2832     * @param fraction
2833     *            the mantissa to be analyzed
2834     * @param roundingMode
2835     *            the type of rounding
2836     * @return the carry propagated after rounding
2837     */
2838    private static int roundingBehavior(int parityBit, int fraction, RoundingMode roundingMode) {
2839        int increment = 0; // the carry after rounding
2840
2841        switch (roundingMode) {
2842            case UNNECESSARY:
2843                if (fraction != 0) {
2844                    throw new ArithmeticException("Rounding necessary");
2845                }
2846                break;
2847            case UP:
2848                increment = Integer.signum(fraction);
2849                break;
2850            case DOWN:
2851                break;
2852            case CEILING:
2853                increment = Math.max(Integer.signum(fraction), 0);
2854                break;
2855            case FLOOR:
2856                increment = Math.min(Integer.signum(fraction), 0);
2857                break;
2858            case HALF_UP:
2859                if (Math.abs(fraction) >= 5) {
2860                    increment = Integer.signum(fraction);
2861                }
2862                break;
2863            case HALF_DOWN:
2864                if (Math.abs(fraction) > 5) {
2865                    increment = Integer.signum(fraction);
2866                }
2867                break;
2868            case HALF_EVEN:
2869                if (Math.abs(fraction) + parityBit > 5) {
2870                    increment = Integer.signum(fraction);
2871                }
2872                break;
2873        }
2874        return increment;
2875    }
2876
2877    /**
2878     * If {@code intVal} has a fractional part throws an exception,
2879     * otherwise it counts the number of bits of value and checks if it's out of
2880     * the range of the primitive type. If the number fits in the primitive type
2881     * returns this number as {@code long}, otherwise throws an
2882     * exception.
2883     *
2884     * @param bitLengthOfType
2885     *            number of bits of the type whose value will be calculated
2886     *            exactly
2887     * @return the exact value of the integer part of {@code BigDecimal}
2888     *         when is possible
2889     * @throws ArithmeticException when rounding is necessary or the
2890     *             number don't fit in the primitive type
2891     */
2892    private long valueExact(int bitLengthOfType) {
2893        BigInteger bigInteger = toBigIntegerExact();
2894
2895        if (bigInteger.bitLength() < bitLengthOfType) {
2896            // It fits in the primitive type
2897            return bigInteger.longValue();
2898        }
2899        throw new ArithmeticException("Rounding necessary");
2900    }
2901
2902    /**
2903     * If the precision already was calculated it returns that value, otherwise
2904     * it calculates a very good approximation efficiently . Note that this
2905     * value will be {@code precision()} or {@code precision()-1}
2906     * in the worst case.
2907     *
2908     * @return an approximation of {@code precision()} value
2909     */
2910    private int approxPrecision() {
2911        return precision > 0
2912                ? precision
2913                : (int) ((this.bitLength - 1) * LOG10_2) + 1;
2914    }
2915
2916    private static int safeLongToInt(long longValue) {
2917        if (longValue < Integer.MIN_VALUE || longValue > Integer.MAX_VALUE) {
2918            throw new ArithmeticException("Out of int range: " + longValue);
2919        }
2920        return (int) longValue;
2921    }
2922
2923    /**
2924     * It returns the value 0 with the most approximated scale of type
2925     * {@code int}. if {@code longScale > Integer.MAX_VALUE} the
2926     * scale will be {@code Integer.MAX_VALUE}; if
2927     * {@code longScale < Integer.MIN_VALUE} the scale will be
2928     * {@code Integer.MIN_VALUE}; otherwise {@code longScale} is
2929     * casted to the type {@code int}.
2930     *
2931     * @param longScale
2932     *            the scale to which the value 0 will be scaled.
2933     * @return the value 0 scaled by the closer scale of type {@code int}.
2934     * @see #scale
2935     */
2936    private static BigDecimal zeroScaledBy(long longScale) {
2937        if (longScale == (int) longScale) {
2938            return valueOf(0,(int)longScale);
2939            }
2940        if (longScale >= 0) {
2941            return new BigDecimal( 0, Integer.MAX_VALUE);
2942        }
2943        return new BigDecimal( 0, Integer.MIN_VALUE);
2944    }
2945
2946    /**
2947     * Assigns all transient fields upon deserialization of a
2948     * {@code BigDecimal} instance (bitLength and smallValue). The transient
2949     * field precision is assigned lazily.
2950     */
2951    private void readObject(ObjectInputStream in) throws IOException,
2952            ClassNotFoundException {
2953        in.defaultReadObject();
2954
2955        this.bitLength = intVal.bitLength();
2956        if (this.bitLength < 64) {
2957            this.smallValue = intVal.longValue();
2958        }
2959    }
2960
2961    /**
2962     * Prepares this {@code BigDecimal} for serialization, i.e. the
2963     * non-transient field {@code intVal} is assigned.
2964     */
2965    private void writeObject(ObjectOutputStream out) throws IOException {
2966        getUnscaledValue();
2967        out.defaultWriteObject();
2968    }
2969
2970    private BigInteger getUnscaledValue() {
2971        if(intVal == null) {
2972            intVal = BigInteger.valueOf(smallValue);
2973        }
2974        return intVal;
2975    }
2976
2977    private void setUnscaledValue(BigInteger unscaledValue) {
2978        this.intVal = unscaledValue;
2979        this.bitLength = unscaledValue.bitLength();
2980        if(this.bitLength < 64) {
2981            this.smallValue = unscaledValue.longValue();
2982        }
2983    }
2984
2985    private static int bitLength(long smallValue) {
2986        if(smallValue < 0) {
2987            smallValue = ~smallValue;
2988        }
2989        return 64 - Long.numberOfLeadingZeros(smallValue);
2990    }
2991
2992    private static int bitLength(int smallValue) {
2993        if(smallValue < 0) {
2994            smallValue = ~smallValue;
2995        }
2996        return 32 - Integer.numberOfLeadingZeros(smallValue);
2997    }
2998
2999}
3000