jdk/src/share/classes/java/math/BigInteger.java
author darcy
Tue, 20 Oct 2009 09:51:28 -0700
changeset 4151 db7d59c0b0e6
parent 2922 dd6d609861f0
child 4160 bda0a85afcb7
permissions -rw-r--r--
6371401: java.math.BigInteger.shift(Integer.MIN_VALUE) throws StackOverflowError Reviewed-by: alanb
Ignore whitespace changes - Everywhere: Within whitespace: At end of lines:
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
     1
/*
90ce3da70b43 Initial load
duke
parents:
diff changeset
     2
 * Portions Copyright 1996-2007 Sun Microsystems, Inc.  All Rights Reserved.
90ce3da70b43 Initial load
duke
parents:
diff changeset
     3
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
90ce3da70b43 Initial load
duke
parents:
diff changeset
     4
 *
90ce3da70b43 Initial load
duke
parents:
diff changeset
     5
 * This code is free software; you can redistribute it and/or modify it
90ce3da70b43 Initial load
duke
parents:
diff changeset
     6
 * under the terms of the GNU General Public License version 2 only, as
90ce3da70b43 Initial load
duke
parents:
diff changeset
     7
 * published by the Free Software Foundation.  Sun designates this
90ce3da70b43 Initial load
duke
parents:
diff changeset
     8
 * particular file as subject to the "Classpath" exception as provided
90ce3da70b43 Initial load
duke
parents:
diff changeset
     9
 * by Sun in the LICENSE file that accompanied this code.
90ce3da70b43 Initial load
duke
parents:
diff changeset
    10
 *
90ce3da70b43 Initial load
duke
parents:
diff changeset
    11
 * This code is distributed in the hope that it will be useful, but WITHOUT
90ce3da70b43 Initial load
duke
parents:
diff changeset
    12
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
90ce3da70b43 Initial load
duke
parents:
diff changeset
    13
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
90ce3da70b43 Initial load
duke
parents:
diff changeset
    14
 * version 2 for more details (a copy is included in the LICENSE file that
90ce3da70b43 Initial load
duke
parents:
diff changeset
    15
 * accompanied this code).
90ce3da70b43 Initial load
duke
parents:
diff changeset
    16
 *
90ce3da70b43 Initial load
duke
parents:
diff changeset
    17
 * You should have received a copy of the GNU General Public License version
90ce3da70b43 Initial load
duke
parents:
diff changeset
    18
 * 2 along with this work; if not, write to the Free Software Foundation,
90ce3da70b43 Initial load
duke
parents:
diff changeset
    19
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
90ce3da70b43 Initial load
duke
parents:
diff changeset
    20
 *
90ce3da70b43 Initial load
duke
parents:
diff changeset
    21
 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
90ce3da70b43 Initial load
duke
parents:
diff changeset
    22
 * CA 95054 USA or visit www.sun.com if you need additional information or
90ce3da70b43 Initial load
duke
parents:
diff changeset
    23
 * have any questions.
90ce3da70b43 Initial load
duke
parents:
diff changeset
    24
 */
90ce3da70b43 Initial load
duke
parents:
diff changeset
    25
90ce3da70b43 Initial load
duke
parents:
diff changeset
    26
/*
90ce3da70b43 Initial load
duke
parents:
diff changeset
    27
 * Portions Copyright (c) 1995  Colin Plumb.  All rights reserved.
90ce3da70b43 Initial load
duke
parents:
diff changeset
    28
 */
90ce3da70b43 Initial load
duke
parents:
diff changeset
    29
90ce3da70b43 Initial load
duke
parents:
diff changeset
    30
package java.math;
90ce3da70b43 Initial load
duke
parents:
diff changeset
    31
90ce3da70b43 Initial load
duke
parents:
diff changeset
    32
import java.util.Random;
90ce3da70b43 Initial load
duke
parents:
diff changeset
    33
import java.io.*;
90ce3da70b43 Initial load
duke
parents:
diff changeset
    34
90ce3da70b43 Initial load
duke
parents:
diff changeset
    35
/**
90ce3da70b43 Initial load
duke
parents:
diff changeset
    36
 * Immutable arbitrary-precision integers.  All operations behave as if
90ce3da70b43 Initial load
duke
parents:
diff changeset
    37
 * BigIntegers were represented in two's-complement notation (like Java's
90ce3da70b43 Initial load
duke
parents:
diff changeset
    38
 * primitive integer types).  BigInteger provides analogues to all of Java's
90ce3da70b43 Initial load
duke
parents:
diff changeset
    39
 * primitive integer operators, and all relevant methods from java.lang.Math.
90ce3da70b43 Initial load
duke
parents:
diff changeset
    40
 * Additionally, BigInteger provides operations for modular arithmetic, GCD
90ce3da70b43 Initial load
duke
parents:
diff changeset
    41
 * calculation, primality testing, prime generation, bit manipulation,
90ce3da70b43 Initial load
duke
parents:
diff changeset
    42
 * and a few other miscellaneous operations.
90ce3da70b43 Initial load
duke
parents:
diff changeset
    43
 *
90ce3da70b43 Initial load
duke
parents:
diff changeset
    44
 * <p>Semantics of arithmetic operations exactly mimic those of Java's integer
90ce3da70b43 Initial load
duke
parents:
diff changeset
    45
 * arithmetic operators, as defined in <i>The Java Language Specification</i>.
90ce3da70b43 Initial load
duke
parents:
diff changeset
    46
 * For example, division by zero throws an {@code ArithmeticException}, and
90ce3da70b43 Initial load
duke
parents:
diff changeset
    47
 * division of a negative by a positive yields a negative (or zero) remainder.
90ce3da70b43 Initial load
duke
parents:
diff changeset
    48
 * All of the details in the Spec concerning overflow are ignored, as
90ce3da70b43 Initial load
duke
parents:
diff changeset
    49
 * BigIntegers are made as large as necessary to accommodate the results of an
90ce3da70b43 Initial load
duke
parents:
diff changeset
    50
 * operation.
90ce3da70b43 Initial load
duke
parents:
diff changeset
    51
 *
90ce3da70b43 Initial load
duke
parents:
diff changeset
    52
 * <p>Semantics of shift operations extend those of Java's shift operators
90ce3da70b43 Initial load
duke
parents:
diff changeset
    53
 * to allow for negative shift distances.  A right-shift with a negative
90ce3da70b43 Initial load
duke
parents:
diff changeset
    54
 * shift distance results in a left shift, and vice-versa.  The unsigned
90ce3da70b43 Initial load
duke
parents:
diff changeset
    55
 * right shift operator ({@code >>>}) is omitted, as this operation makes
90ce3da70b43 Initial load
duke
parents:
diff changeset
    56
 * little sense in combination with the "infinite word size" abstraction
90ce3da70b43 Initial load
duke
parents:
diff changeset
    57
 * provided by this class.
90ce3da70b43 Initial load
duke
parents:
diff changeset
    58
 *
90ce3da70b43 Initial load
duke
parents:
diff changeset
    59
 * <p>Semantics of bitwise logical operations exactly mimic those of Java's
90ce3da70b43 Initial load
duke
parents:
diff changeset
    60
 * bitwise integer operators.  The binary operators ({@code and},
90ce3da70b43 Initial load
duke
parents:
diff changeset
    61
 * {@code or}, {@code xor}) implicitly perform sign extension on the shorter
90ce3da70b43 Initial load
duke
parents:
diff changeset
    62
 * of the two operands prior to performing the operation.
90ce3da70b43 Initial load
duke
parents:
diff changeset
    63
 *
90ce3da70b43 Initial load
duke
parents:
diff changeset
    64
 * <p>Comparison operations perform signed integer comparisons, analogous to
90ce3da70b43 Initial load
duke
parents:
diff changeset
    65
 * those performed by Java's relational and equality operators.
90ce3da70b43 Initial load
duke
parents:
diff changeset
    66
 *
90ce3da70b43 Initial load
duke
parents:
diff changeset
    67
 * <p>Modular arithmetic operations are provided to compute residues, perform
90ce3da70b43 Initial load
duke
parents:
diff changeset
    68
 * exponentiation, and compute multiplicative inverses.  These methods always
90ce3da70b43 Initial load
duke
parents:
diff changeset
    69
 * return a non-negative result, between {@code 0} and {@code (modulus - 1)},
90ce3da70b43 Initial load
duke
parents:
diff changeset
    70
 * inclusive.
90ce3da70b43 Initial load
duke
parents:
diff changeset
    71
 *
90ce3da70b43 Initial load
duke
parents:
diff changeset
    72
 * <p>Bit operations operate on a single bit of the two's-complement
90ce3da70b43 Initial load
duke
parents:
diff changeset
    73
 * representation of their operand.  If necessary, the operand is sign-
90ce3da70b43 Initial load
duke
parents:
diff changeset
    74
 * extended so that it contains the designated bit.  None of the single-bit
90ce3da70b43 Initial load
duke
parents:
diff changeset
    75
 * operations can produce a BigInteger with a different sign from the
90ce3da70b43 Initial load
duke
parents:
diff changeset
    76
 * BigInteger being operated on, as they affect only a single bit, and the
90ce3da70b43 Initial load
duke
parents:
diff changeset
    77
 * "infinite word size" abstraction provided by this class ensures that there
90ce3da70b43 Initial load
duke
parents:
diff changeset
    78
 * are infinitely many "virtual sign bits" preceding each BigInteger.
90ce3da70b43 Initial load
duke
parents:
diff changeset
    79
 *
90ce3da70b43 Initial load
duke
parents:
diff changeset
    80
 * <p>For the sake of brevity and clarity, pseudo-code is used throughout the
90ce3da70b43 Initial load
duke
parents:
diff changeset
    81
 * descriptions of BigInteger methods.  The pseudo-code expression
90ce3da70b43 Initial load
duke
parents:
diff changeset
    82
 * {@code (i + j)} is shorthand for "a BigInteger whose value is
90ce3da70b43 Initial load
duke
parents:
diff changeset
    83
 * that of the BigInteger {@code i} plus that of the BigInteger {@code j}."
90ce3da70b43 Initial load
duke
parents:
diff changeset
    84
 * The pseudo-code expression {@code (i == j)} is shorthand for
90ce3da70b43 Initial load
duke
parents:
diff changeset
    85
 * "{@code true} if and only if the BigInteger {@code i} represents the same
90ce3da70b43 Initial load
duke
parents:
diff changeset
    86
 * value as the BigInteger {@code j}."  Other pseudo-code expressions are
90ce3da70b43 Initial load
duke
parents:
diff changeset
    87
 * interpreted similarly.
90ce3da70b43 Initial load
duke
parents:
diff changeset
    88
 *
90ce3da70b43 Initial load
duke
parents:
diff changeset
    89
 * <p>All methods and constructors in this class throw
90ce3da70b43 Initial load
duke
parents:
diff changeset
    90
 * {@code NullPointerException} when passed
90ce3da70b43 Initial load
duke
parents:
diff changeset
    91
 * a null object reference for any input parameter.
90ce3da70b43 Initial load
duke
parents:
diff changeset
    92
 *
90ce3da70b43 Initial load
duke
parents:
diff changeset
    93
 * @see     BigDecimal
90ce3da70b43 Initial load
duke
parents:
diff changeset
    94
 * @author  Josh Bloch
90ce3da70b43 Initial load
duke
parents:
diff changeset
    95
 * @author  Michael McCloskey
90ce3da70b43 Initial load
duke
parents:
diff changeset
    96
 * @since JDK1.1
90ce3da70b43 Initial load
duke
parents:
diff changeset
    97
 */
90ce3da70b43 Initial load
duke
parents:
diff changeset
    98
90ce3da70b43 Initial load
duke
parents:
diff changeset
    99
public class BigInteger extends Number implements Comparable<BigInteger> {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   100
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
   101
     * The signum of this BigInteger: -1 for negative, 0 for zero, or
90ce3da70b43 Initial load
duke
parents:
diff changeset
   102
     * 1 for positive.  Note that the BigInteger zero <i>must</i> have
90ce3da70b43 Initial load
duke
parents:
diff changeset
   103
     * a signum of 0.  This is necessary to ensures that there is exactly one
90ce3da70b43 Initial load
duke
parents:
diff changeset
   104
     * representation for each BigInteger value.
90ce3da70b43 Initial load
duke
parents:
diff changeset
   105
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
   106
     * @serial
90ce3da70b43 Initial load
duke
parents:
diff changeset
   107
     */
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
   108
    final int signum;
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   109
90ce3da70b43 Initial load
duke
parents:
diff changeset
   110
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
   111
     * The magnitude of this BigInteger, in <i>big-endian</i> order: the
90ce3da70b43 Initial load
duke
parents:
diff changeset
   112
     * zeroth element of this array is the most-significant int of the
90ce3da70b43 Initial load
duke
parents:
diff changeset
   113
     * magnitude.  The magnitude must be "minimal" in that the most-significant
90ce3da70b43 Initial load
duke
parents:
diff changeset
   114
     * int ({@code mag[0]}) must be non-zero.  This is necessary to
90ce3da70b43 Initial load
duke
parents:
diff changeset
   115
     * ensure that there is exactly one representation for each BigInteger
90ce3da70b43 Initial load
duke
parents:
diff changeset
   116
     * value.  Note that this implies that the BigInteger zero has a
90ce3da70b43 Initial load
duke
parents:
diff changeset
   117
     * zero-length mag array.
90ce3da70b43 Initial load
duke
parents:
diff changeset
   118
     */
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
   119
    final int[] mag;
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   120
90ce3da70b43 Initial load
duke
parents:
diff changeset
   121
    // These "redundant fields" are initialized with recognizable nonsense
90ce3da70b43 Initial load
duke
parents:
diff changeset
   122
    // values, and cached the first time they are needed (or never, if they
90ce3da70b43 Initial load
duke
parents:
diff changeset
   123
    // aren't needed).
90ce3da70b43 Initial load
duke
parents:
diff changeset
   124
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
   125
     /**
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
   126
     * One plus the bitCount of this BigInteger. Zeros means unitialized.
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   127
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
   128
     * @serial
90ce3da70b43 Initial load
duke
parents:
diff changeset
   129
     * @see #bitCount
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
   130
     * @deprecated Deprecated since logical value is offset from stored
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
   131
     * value and correction factor is applied in accessor method.
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   132
     */
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
   133
    @Deprecated
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
   134
    private int bitCount;
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   135
90ce3da70b43 Initial load
duke
parents:
diff changeset
   136
    /**
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
   137
     * One plus the bitLength of this BigInteger. Zeros means unitialized.
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   138
     * (either value is acceptable).
90ce3da70b43 Initial load
duke
parents:
diff changeset
   139
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
   140
     * @serial
90ce3da70b43 Initial load
duke
parents:
diff changeset
   141
     * @see #bitLength()
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
   142
     * @deprecated Deprecated since logical value is offset from stored
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
   143
     * value and correction factor is applied in accessor method.
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   144
     */
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
   145
    @Deprecated
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
   146
    private int bitLength;
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   147
90ce3da70b43 Initial load
duke
parents:
diff changeset
   148
    /**
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
   149
     * Two plus the lowest set bit of this BigInteger, as returned by
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
   150
     * getLowestSetBit().
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   151
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
   152
     * @serial
90ce3da70b43 Initial load
duke
parents:
diff changeset
   153
     * @see #getLowestSetBit
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
   154
     * @deprecated Deprecated since logical value is offset from stored
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
   155
     * value and correction factor is applied in accessor method.
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   156
     */
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
   157
    @Deprecated
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
   158
    private int lowestSetBit;
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   159
90ce3da70b43 Initial load
duke
parents:
diff changeset
   160
    /**
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
   161
     * Two plus the index of the lowest-order int in the magnitude of this
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
   162
     * BigInteger that contains a nonzero int, or -2 (either value is acceptable).
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
   163
     * The least significant int has int-number 0, the next int in order of
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
   164
     * increasing significance has int-number 1, and so forth.
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
   165
     * @deprecated Deprecated since logical value is offset from stored
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
   166
     * value and correction factor is applied in accessor method.
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   167
     */
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
   168
    @Deprecated
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
   169
    private int firstNonzeroIntNum;
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   170
90ce3da70b43 Initial load
duke
parents:
diff changeset
   171
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
   172
     * This mask is used to obtain the value of an int as if it were unsigned.
90ce3da70b43 Initial load
duke
parents:
diff changeset
   173
     */
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
   174
    final static long LONG_MASK = 0xffffffffL;
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   175
90ce3da70b43 Initial load
duke
parents:
diff changeset
   176
    //Constructors
90ce3da70b43 Initial load
duke
parents:
diff changeset
   177
90ce3da70b43 Initial load
duke
parents:
diff changeset
   178
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
   179
     * Translates a byte array containing the two's-complement binary
90ce3da70b43 Initial load
duke
parents:
diff changeset
   180
     * representation of a BigInteger into a BigInteger.  The input array is
90ce3da70b43 Initial load
duke
parents:
diff changeset
   181
     * assumed to be in <i>big-endian</i> byte-order: the most significant
90ce3da70b43 Initial load
duke
parents:
diff changeset
   182
     * byte is in the zeroth element.
90ce3da70b43 Initial load
duke
parents:
diff changeset
   183
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
   184
     * @param  val big-endian two's-complement binary representation of
90ce3da70b43 Initial load
duke
parents:
diff changeset
   185
     *         BigInteger.
90ce3da70b43 Initial load
duke
parents:
diff changeset
   186
     * @throws NumberFormatException {@code val} is zero bytes long.
90ce3da70b43 Initial load
duke
parents:
diff changeset
   187
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
   188
    public BigInteger(byte[] val) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   189
        if (val.length == 0)
90ce3da70b43 Initial load
duke
parents:
diff changeset
   190
            throw new NumberFormatException("Zero length BigInteger");
90ce3da70b43 Initial load
duke
parents:
diff changeset
   191
90ce3da70b43 Initial load
duke
parents:
diff changeset
   192
        if (val[0] < 0) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   193
            mag = makePositive(val);
90ce3da70b43 Initial load
duke
parents:
diff changeset
   194
            signum = -1;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   195
        } else {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   196
            mag = stripLeadingZeroBytes(val);
90ce3da70b43 Initial load
duke
parents:
diff changeset
   197
            signum = (mag.length == 0 ? 0 : 1);
90ce3da70b43 Initial load
duke
parents:
diff changeset
   198
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   199
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   200
90ce3da70b43 Initial load
duke
parents:
diff changeset
   201
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
   202
     * This private constructor translates an int array containing the
90ce3da70b43 Initial load
duke
parents:
diff changeset
   203
     * two's-complement binary representation of a BigInteger into a
90ce3da70b43 Initial load
duke
parents:
diff changeset
   204
     * BigInteger. The input array is assumed to be in <i>big-endian</i>
90ce3da70b43 Initial load
duke
parents:
diff changeset
   205
     * int-order: the most significant int is in the zeroth element.
90ce3da70b43 Initial load
duke
parents:
diff changeset
   206
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
   207
    private BigInteger(int[] val) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   208
        if (val.length == 0)
90ce3da70b43 Initial load
duke
parents:
diff changeset
   209
            throw new NumberFormatException("Zero length BigInteger");
90ce3da70b43 Initial load
duke
parents:
diff changeset
   210
90ce3da70b43 Initial load
duke
parents:
diff changeset
   211
        if (val[0] < 0) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   212
            mag = makePositive(val);
90ce3da70b43 Initial load
duke
parents:
diff changeset
   213
            signum = -1;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   214
        } else {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   215
            mag = trustedStripLeadingZeroInts(val);
90ce3da70b43 Initial load
duke
parents:
diff changeset
   216
            signum = (mag.length == 0 ? 0 : 1);
90ce3da70b43 Initial load
duke
parents:
diff changeset
   217
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   218
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   219
90ce3da70b43 Initial load
duke
parents:
diff changeset
   220
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
   221
     * Translates the sign-magnitude representation of a BigInteger into a
90ce3da70b43 Initial load
duke
parents:
diff changeset
   222
     * BigInteger.  The sign is represented as an integer signum value: -1 for
90ce3da70b43 Initial load
duke
parents:
diff changeset
   223
     * negative, 0 for zero, or 1 for positive.  The magnitude is a byte array
90ce3da70b43 Initial load
duke
parents:
diff changeset
   224
     * in <i>big-endian</i> byte-order: the most significant byte is in the
90ce3da70b43 Initial load
duke
parents:
diff changeset
   225
     * zeroth element.  A zero-length magnitude array is permissible, and will
90ce3da70b43 Initial load
duke
parents:
diff changeset
   226
     * result in a BigInteger value of 0, whether signum is -1, 0 or 1.
90ce3da70b43 Initial load
duke
parents:
diff changeset
   227
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
   228
     * @param  signum signum of the number (-1 for negative, 0 for zero, 1
90ce3da70b43 Initial load
duke
parents:
diff changeset
   229
     *         for positive).
90ce3da70b43 Initial load
duke
parents:
diff changeset
   230
     * @param  magnitude big-endian binary representation of the magnitude of
90ce3da70b43 Initial load
duke
parents:
diff changeset
   231
     *         the number.
90ce3da70b43 Initial load
duke
parents:
diff changeset
   232
     * @throws NumberFormatException {@code signum} is not one of the three
90ce3da70b43 Initial load
duke
parents:
diff changeset
   233
     *         legal values (-1, 0, and 1), or {@code signum} is 0 and
90ce3da70b43 Initial load
duke
parents:
diff changeset
   234
     *         {@code magnitude} contains one or more non-zero bytes.
90ce3da70b43 Initial load
duke
parents:
diff changeset
   235
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
   236
    public BigInteger(int signum, byte[] magnitude) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   237
        this.mag = stripLeadingZeroBytes(magnitude);
90ce3da70b43 Initial load
duke
parents:
diff changeset
   238
90ce3da70b43 Initial load
duke
parents:
diff changeset
   239
        if (signum < -1 || signum > 1)
90ce3da70b43 Initial load
duke
parents:
diff changeset
   240
            throw(new NumberFormatException("Invalid signum value"));
90ce3da70b43 Initial load
duke
parents:
diff changeset
   241
90ce3da70b43 Initial load
duke
parents:
diff changeset
   242
        if (this.mag.length==0) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   243
            this.signum = 0;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   244
        } else {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   245
            if (signum == 0)
90ce3da70b43 Initial load
duke
parents:
diff changeset
   246
                throw(new NumberFormatException("signum-magnitude mismatch"));
90ce3da70b43 Initial load
duke
parents:
diff changeset
   247
            this.signum = signum;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   248
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   249
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   250
90ce3da70b43 Initial load
duke
parents:
diff changeset
   251
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
   252
     * A constructor for internal use that translates the sign-magnitude
90ce3da70b43 Initial load
duke
parents:
diff changeset
   253
     * representation of a BigInteger into a BigInteger. It checks the
90ce3da70b43 Initial load
duke
parents:
diff changeset
   254
     * arguments and copies the magnitude so this constructor would be
90ce3da70b43 Initial load
duke
parents:
diff changeset
   255
     * safe for external use.
90ce3da70b43 Initial load
duke
parents:
diff changeset
   256
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
   257
    private BigInteger(int signum, int[] magnitude) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   258
        this.mag = stripLeadingZeroInts(magnitude);
90ce3da70b43 Initial load
duke
parents:
diff changeset
   259
90ce3da70b43 Initial load
duke
parents:
diff changeset
   260
        if (signum < -1 || signum > 1)
90ce3da70b43 Initial load
duke
parents:
diff changeset
   261
            throw(new NumberFormatException("Invalid signum value"));
90ce3da70b43 Initial load
duke
parents:
diff changeset
   262
90ce3da70b43 Initial load
duke
parents:
diff changeset
   263
        if (this.mag.length==0) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   264
            this.signum = 0;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   265
        } else {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   266
            if (signum == 0)
90ce3da70b43 Initial load
duke
parents:
diff changeset
   267
                throw(new NumberFormatException("signum-magnitude mismatch"));
90ce3da70b43 Initial load
duke
parents:
diff changeset
   268
            this.signum = signum;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   269
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   270
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   271
90ce3da70b43 Initial load
duke
parents:
diff changeset
   272
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
   273
     * Translates the String representation of a BigInteger in the
90ce3da70b43 Initial load
duke
parents:
diff changeset
   274
     * specified radix into a BigInteger.  The String representation
90ce3da70b43 Initial load
duke
parents:
diff changeset
   275
     * consists of an optional minus or plus sign followed by a
90ce3da70b43 Initial load
duke
parents:
diff changeset
   276
     * sequence of one or more digits in the specified radix.  The
90ce3da70b43 Initial load
duke
parents:
diff changeset
   277
     * character-to-digit mapping is provided by {@code
90ce3da70b43 Initial load
duke
parents:
diff changeset
   278
     * Character.digit}.  The String may not contain any extraneous
90ce3da70b43 Initial load
duke
parents:
diff changeset
   279
     * characters (whitespace, for example).
90ce3da70b43 Initial load
duke
parents:
diff changeset
   280
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
   281
     * @param val String representation of BigInteger.
90ce3da70b43 Initial load
duke
parents:
diff changeset
   282
     * @param radix radix to be used in interpreting {@code val}.
90ce3da70b43 Initial load
duke
parents:
diff changeset
   283
     * @throws NumberFormatException {@code val} is not a valid representation
90ce3da70b43 Initial load
duke
parents:
diff changeset
   284
     *         of a BigInteger in the specified radix, or {@code radix} is
90ce3da70b43 Initial load
duke
parents:
diff changeset
   285
     *         outside the range from {@link Character#MIN_RADIX} to
90ce3da70b43 Initial load
duke
parents:
diff changeset
   286
     *         {@link Character#MAX_RADIX}, inclusive.
90ce3da70b43 Initial load
duke
parents:
diff changeset
   287
     * @see    Character#digit
90ce3da70b43 Initial load
duke
parents:
diff changeset
   288
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
   289
    public BigInteger(String val, int radix) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   290
        int cursor = 0, numDigits;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   291
        int len = val.length();
90ce3da70b43 Initial load
duke
parents:
diff changeset
   292
90ce3da70b43 Initial load
duke
parents:
diff changeset
   293
        if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX)
90ce3da70b43 Initial load
duke
parents:
diff changeset
   294
            throw new NumberFormatException("Radix out of range");
90ce3da70b43 Initial load
duke
parents:
diff changeset
   295
        if (val.length() == 0)
90ce3da70b43 Initial load
duke
parents:
diff changeset
   296
            throw new NumberFormatException("Zero length BigInteger");
90ce3da70b43 Initial load
duke
parents:
diff changeset
   297
90ce3da70b43 Initial load
duke
parents:
diff changeset
   298
        // Check for at most one leading sign
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
   299
        int sign = 1;
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   300
        int index1 = val.lastIndexOf('-');
90ce3da70b43 Initial load
duke
parents:
diff changeset
   301
        int index2 = val.lastIndexOf('+');
90ce3da70b43 Initial load
duke
parents:
diff changeset
   302
        if ((index1 + index2) <= -1) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   303
            // No leading sign character or at most one leading sign character
90ce3da70b43 Initial load
duke
parents:
diff changeset
   304
            if (index1 == 0 || index2 == 0) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   305
                cursor = 1;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   306
                if (val.length() == 1)
90ce3da70b43 Initial load
duke
parents:
diff changeset
   307
                    throw new NumberFormatException("Zero length BigInteger");
90ce3da70b43 Initial load
duke
parents:
diff changeset
   308
            }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   309
            if (index1 == 0)
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
   310
                sign = -1;
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   311
        } else
90ce3da70b43 Initial load
duke
parents:
diff changeset
   312
            throw new NumberFormatException("Illegal embedded sign character");
90ce3da70b43 Initial load
duke
parents:
diff changeset
   313
90ce3da70b43 Initial load
duke
parents:
diff changeset
   314
        // Skip leading zeros and compute number of digits in magnitude
90ce3da70b43 Initial load
duke
parents:
diff changeset
   315
        while (cursor < len &&
90ce3da70b43 Initial load
duke
parents:
diff changeset
   316
               Character.digit(val.charAt(cursor), radix) == 0)
90ce3da70b43 Initial load
duke
parents:
diff changeset
   317
            cursor++;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   318
        if (cursor == len) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   319
            signum = 0;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   320
            mag = ZERO.mag;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   321
            return;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   322
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   323
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
   324
        numDigits = len - cursor;
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
   325
        signum = sign;
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
   326
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   327
        // Pre-allocate array of expected size. May be too large but can
90ce3da70b43 Initial load
duke
parents:
diff changeset
   328
        // never be too small. Typically exact.
90ce3da70b43 Initial load
duke
parents:
diff changeset
   329
        int numBits = (int)(((numDigits * bitsPerDigit[radix]) >>> 10) + 1);
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
   330
        int numWords = (numBits + 31) >>> 5;
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
   331
        int[] magnitude = new int[numWords];
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   332
90ce3da70b43 Initial load
duke
parents:
diff changeset
   333
        // Process first (potentially short) digit group
90ce3da70b43 Initial load
duke
parents:
diff changeset
   334
        int firstGroupLen = numDigits % digitsPerInt[radix];
90ce3da70b43 Initial load
duke
parents:
diff changeset
   335
        if (firstGroupLen == 0)
90ce3da70b43 Initial load
duke
parents:
diff changeset
   336
            firstGroupLen = digitsPerInt[radix];
90ce3da70b43 Initial load
duke
parents:
diff changeset
   337
        String group = val.substring(cursor, cursor += firstGroupLen);
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
   338
        magnitude[numWords - 1] = Integer.parseInt(group, radix);
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
   339
        if (magnitude[numWords - 1] < 0)
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   340
            throw new NumberFormatException("Illegal digit");
90ce3da70b43 Initial load
duke
parents:
diff changeset
   341
90ce3da70b43 Initial load
duke
parents:
diff changeset
   342
        // Process remaining digit groups
90ce3da70b43 Initial load
duke
parents:
diff changeset
   343
        int superRadix = intRadix[radix];
90ce3da70b43 Initial load
duke
parents:
diff changeset
   344
        int groupVal = 0;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   345
        while (cursor < val.length()) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   346
            group = val.substring(cursor, cursor += digitsPerInt[radix]);
90ce3da70b43 Initial load
duke
parents:
diff changeset
   347
            groupVal = Integer.parseInt(group, radix);
90ce3da70b43 Initial load
duke
parents:
diff changeset
   348
            if (groupVal < 0)
90ce3da70b43 Initial load
duke
parents:
diff changeset
   349
                throw new NumberFormatException("Illegal digit");
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
   350
            destructiveMulAdd(magnitude, superRadix, groupVal);
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   351
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   352
        // Required for cases where the array was overallocated.
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
   353
        mag = trustedStripLeadingZeroInts(magnitude);
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   354
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   355
90ce3da70b43 Initial load
duke
parents:
diff changeset
   356
    // Constructs a new BigInteger using a char array with radix=10
90ce3da70b43 Initial load
duke
parents:
diff changeset
   357
    BigInteger(char[] val) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   358
        int cursor = 0, numDigits;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   359
        int len = val.length;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   360
90ce3da70b43 Initial load
duke
parents:
diff changeset
   361
        // Check for leading minus sign
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
   362
        int sign = 1;
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   363
        if (val[0] == '-') {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   364
            if (len == 1)
90ce3da70b43 Initial load
duke
parents:
diff changeset
   365
                throw new NumberFormatException("Zero length BigInteger");
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
   366
            sign = -1;
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   367
            cursor = 1;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   368
        } else if (val[0] == '+') {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   369
            if (len == 1)
90ce3da70b43 Initial load
duke
parents:
diff changeset
   370
                throw new NumberFormatException("Zero length BigInteger");
90ce3da70b43 Initial load
duke
parents:
diff changeset
   371
            cursor = 1;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   372
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   373
90ce3da70b43 Initial load
duke
parents:
diff changeset
   374
        // Skip leading zeros and compute number of digits in magnitude
90ce3da70b43 Initial load
duke
parents:
diff changeset
   375
        while (cursor < len && Character.digit(val[cursor], 10) == 0)
90ce3da70b43 Initial load
duke
parents:
diff changeset
   376
            cursor++;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   377
        if (cursor == len) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   378
            signum = 0;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   379
            mag = ZERO.mag;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   380
            return;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   381
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   382
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
   383
        numDigits = len - cursor;
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
   384
        signum = sign;
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
   385
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   386
        // Pre-allocate array of expected size
90ce3da70b43 Initial load
duke
parents:
diff changeset
   387
        int numWords;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   388
        if (len < 10) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   389
            numWords = 1;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   390
        } else {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   391
            int numBits = (int)(((numDigits * bitsPerDigit[10]) >>> 10) + 1);
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
   392
            numWords = (numBits + 31) >>> 5;
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   393
        }
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
   394
        int[] magnitude = new int[numWords];
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   395
90ce3da70b43 Initial load
duke
parents:
diff changeset
   396
        // Process first (potentially short) digit group
90ce3da70b43 Initial load
duke
parents:
diff changeset
   397
        int firstGroupLen = numDigits % digitsPerInt[10];
90ce3da70b43 Initial load
duke
parents:
diff changeset
   398
        if (firstGroupLen == 0)
90ce3da70b43 Initial load
duke
parents:
diff changeset
   399
            firstGroupLen = digitsPerInt[10];
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
   400
        magnitude[numWords - 1] = parseInt(val, cursor,  cursor += firstGroupLen);
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   401
90ce3da70b43 Initial load
duke
parents:
diff changeset
   402
        // Process remaining digit groups
90ce3da70b43 Initial load
duke
parents:
diff changeset
   403
        while (cursor < len) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   404
            int groupVal = parseInt(val, cursor, cursor += digitsPerInt[10]);
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
   405
            destructiveMulAdd(magnitude, intRadix[10], groupVal);
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   406
        }
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
   407
        mag = trustedStripLeadingZeroInts(magnitude);
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   408
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   409
90ce3da70b43 Initial load
duke
parents:
diff changeset
   410
    // Create an integer with the digits between the two indexes
90ce3da70b43 Initial load
duke
parents:
diff changeset
   411
    // Assumes start < end. The result may be negative, but it
90ce3da70b43 Initial load
duke
parents:
diff changeset
   412
    // is to be treated as an unsigned value.
90ce3da70b43 Initial load
duke
parents:
diff changeset
   413
    private int parseInt(char[] source, int start, int end) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   414
        int result = Character.digit(source[start++], 10);
90ce3da70b43 Initial load
duke
parents:
diff changeset
   415
        if (result == -1)
90ce3da70b43 Initial load
duke
parents:
diff changeset
   416
            throw new NumberFormatException(new String(source));
90ce3da70b43 Initial load
duke
parents:
diff changeset
   417
90ce3da70b43 Initial load
duke
parents:
diff changeset
   418
        for (int index = start; index<end; index++) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   419
            int nextVal = Character.digit(source[index], 10);
90ce3da70b43 Initial load
duke
parents:
diff changeset
   420
            if (nextVal == -1)
90ce3da70b43 Initial load
duke
parents:
diff changeset
   421
                throw new NumberFormatException(new String(source));
90ce3da70b43 Initial load
duke
parents:
diff changeset
   422
            result = 10*result + nextVal;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   423
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   424
90ce3da70b43 Initial load
duke
parents:
diff changeset
   425
        return result;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   426
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   427
90ce3da70b43 Initial load
duke
parents:
diff changeset
   428
    // bitsPerDigit in the given radix times 1024
90ce3da70b43 Initial load
duke
parents:
diff changeset
   429
    // Rounded up to avoid underallocation.
90ce3da70b43 Initial load
duke
parents:
diff changeset
   430
    private static long bitsPerDigit[] = { 0, 0,
90ce3da70b43 Initial load
duke
parents:
diff changeset
   431
        1024, 1624, 2048, 2378, 2648, 2875, 3072, 3247, 3402, 3543, 3672,
90ce3da70b43 Initial load
duke
parents:
diff changeset
   432
        3790, 3899, 4001, 4096, 4186, 4271, 4350, 4426, 4498, 4567, 4633,
90ce3da70b43 Initial load
duke
parents:
diff changeset
   433
        4696, 4756, 4814, 4870, 4923, 4975, 5025, 5074, 5120, 5166, 5210,
90ce3da70b43 Initial load
duke
parents:
diff changeset
   434
                                           5253, 5295};
90ce3da70b43 Initial load
duke
parents:
diff changeset
   435
90ce3da70b43 Initial load
duke
parents:
diff changeset
   436
    // Multiply x array times word y in place, and add word z
90ce3da70b43 Initial load
duke
parents:
diff changeset
   437
    private static void destructiveMulAdd(int[] x, int y, int z) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   438
        // Perform the multiplication word by word
90ce3da70b43 Initial load
duke
parents:
diff changeset
   439
        long ylong = y & LONG_MASK;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   440
        long zlong = z & LONG_MASK;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   441
        int len = x.length;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   442
90ce3da70b43 Initial load
duke
parents:
diff changeset
   443
        long product = 0;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   444
        long carry = 0;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   445
        for (int i = len-1; i >= 0; i--) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   446
            product = ylong * (x[i] & LONG_MASK) + carry;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   447
            x[i] = (int)product;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   448
            carry = product >>> 32;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   449
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   450
90ce3da70b43 Initial load
duke
parents:
diff changeset
   451
        // Perform the addition
90ce3da70b43 Initial load
duke
parents:
diff changeset
   452
        long sum = (x[len-1] & LONG_MASK) + zlong;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   453
        x[len-1] = (int)sum;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   454
        carry = sum >>> 32;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   455
        for (int i = len-2; i >= 0; i--) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   456
            sum = (x[i] & LONG_MASK) + carry;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   457
            x[i] = (int)sum;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   458
            carry = sum >>> 32;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   459
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   460
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   461
90ce3da70b43 Initial load
duke
parents:
diff changeset
   462
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
   463
     * Translates the decimal String representation of a BigInteger into a
90ce3da70b43 Initial load
duke
parents:
diff changeset
   464
     * BigInteger.  The String representation consists of an optional minus
90ce3da70b43 Initial load
duke
parents:
diff changeset
   465
     * sign followed by a sequence of one or more decimal digits.  The
90ce3da70b43 Initial load
duke
parents:
diff changeset
   466
     * character-to-digit mapping is provided by {@code Character.digit}.
90ce3da70b43 Initial load
duke
parents:
diff changeset
   467
     * The String may not contain any extraneous characters (whitespace, for
90ce3da70b43 Initial load
duke
parents:
diff changeset
   468
     * example).
90ce3da70b43 Initial load
duke
parents:
diff changeset
   469
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
   470
     * @param val decimal String representation of BigInteger.
90ce3da70b43 Initial load
duke
parents:
diff changeset
   471
     * @throws NumberFormatException {@code val} is not a valid representation
90ce3da70b43 Initial load
duke
parents:
diff changeset
   472
     *         of a BigInteger.
90ce3da70b43 Initial load
duke
parents:
diff changeset
   473
     * @see    Character#digit
90ce3da70b43 Initial load
duke
parents:
diff changeset
   474
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
   475
    public BigInteger(String val) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   476
        this(val, 10);
90ce3da70b43 Initial load
duke
parents:
diff changeset
   477
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   478
90ce3da70b43 Initial load
duke
parents:
diff changeset
   479
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
   480
     * Constructs a randomly generated BigInteger, uniformly distributed over
90ce3da70b43 Initial load
duke
parents:
diff changeset
   481
     * the range {@code 0} to (2<sup>{@code numBits}</sup> - 1), inclusive.
90ce3da70b43 Initial load
duke
parents:
diff changeset
   482
     * The uniformity of the distribution assumes that a fair source of random
90ce3da70b43 Initial load
duke
parents:
diff changeset
   483
     * bits is provided in {@code rnd}.  Note that this constructor always
90ce3da70b43 Initial load
duke
parents:
diff changeset
   484
     * constructs a non-negative BigInteger.
90ce3da70b43 Initial load
duke
parents:
diff changeset
   485
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
   486
     * @param  numBits maximum bitLength of the new BigInteger.
90ce3da70b43 Initial load
duke
parents:
diff changeset
   487
     * @param  rnd source of randomness to be used in computing the new
90ce3da70b43 Initial load
duke
parents:
diff changeset
   488
     *         BigInteger.
90ce3da70b43 Initial load
duke
parents:
diff changeset
   489
     * @throws IllegalArgumentException {@code numBits} is negative.
90ce3da70b43 Initial load
duke
parents:
diff changeset
   490
     * @see #bitLength()
90ce3da70b43 Initial load
duke
parents:
diff changeset
   491
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
   492
    public BigInteger(int numBits, Random rnd) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   493
        this(1, randomBits(numBits, rnd));
90ce3da70b43 Initial load
duke
parents:
diff changeset
   494
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   495
90ce3da70b43 Initial load
duke
parents:
diff changeset
   496
    private static byte[] randomBits(int numBits, Random rnd) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   497
        if (numBits < 0)
90ce3da70b43 Initial load
duke
parents:
diff changeset
   498
            throw new IllegalArgumentException("numBits must be non-negative");
90ce3da70b43 Initial load
duke
parents:
diff changeset
   499
        int numBytes = (int)(((long)numBits+7)/8); // avoid overflow
90ce3da70b43 Initial load
duke
parents:
diff changeset
   500
        byte[] randomBits = new byte[numBytes];
90ce3da70b43 Initial load
duke
parents:
diff changeset
   501
90ce3da70b43 Initial load
duke
parents:
diff changeset
   502
        // Generate random bytes and mask out any excess bits
90ce3da70b43 Initial load
duke
parents:
diff changeset
   503
        if (numBytes > 0) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   504
            rnd.nextBytes(randomBits);
90ce3da70b43 Initial load
duke
parents:
diff changeset
   505
            int excessBits = 8*numBytes - numBits;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   506
            randomBits[0] &= (1 << (8-excessBits)) - 1;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   507
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   508
        return randomBits;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   509
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   510
90ce3da70b43 Initial load
duke
parents:
diff changeset
   511
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
   512
     * Constructs a randomly generated positive BigInteger that is probably
90ce3da70b43 Initial load
duke
parents:
diff changeset
   513
     * prime, with the specified bitLength.
90ce3da70b43 Initial load
duke
parents:
diff changeset
   514
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
   515
     * <p>It is recommended that the {@link #probablePrime probablePrime}
90ce3da70b43 Initial load
duke
parents:
diff changeset
   516
     * method be used in preference to this constructor unless there
90ce3da70b43 Initial load
duke
parents:
diff changeset
   517
     * is a compelling need to specify a certainty.
90ce3da70b43 Initial load
duke
parents:
diff changeset
   518
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
   519
     * @param  bitLength bitLength of the returned BigInteger.
90ce3da70b43 Initial load
duke
parents:
diff changeset
   520
     * @param  certainty a measure of the uncertainty that the caller is
90ce3da70b43 Initial load
duke
parents:
diff changeset
   521
     *         willing to tolerate.  The probability that the new BigInteger
90ce3da70b43 Initial load
duke
parents:
diff changeset
   522
     *         represents a prime number will exceed
90ce3da70b43 Initial load
duke
parents:
diff changeset
   523
     *         (1 - 1/2<sup>{@code certainty}</sup>).  The execution time of
90ce3da70b43 Initial load
duke
parents:
diff changeset
   524
     *         this constructor is proportional to the value of this parameter.
90ce3da70b43 Initial load
duke
parents:
diff changeset
   525
     * @param  rnd source of random bits used to select candidates to be
90ce3da70b43 Initial load
duke
parents:
diff changeset
   526
     *         tested for primality.
90ce3da70b43 Initial load
duke
parents:
diff changeset
   527
     * @throws ArithmeticException {@code bitLength < 2}.
90ce3da70b43 Initial load
duke
parents:
diff changeset
   528
     * @see    #bitLength()
90ce3da70b43 Initial load
duke
parents:
diff changeset
   529
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
   530
    public BigInteger(int bitLength, int certainty, Random rnd) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   531
        BigInteger prime;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   532
90ce3da70b43 Initial load
duke
parents:
diff changeset
   533
        if (bitLength < 2)
90ce3da70b43 Initial load
duke
parents:
diff changeset
   534
            throw new ArithmeticException("bitLength < 2");
90ce3da70b43 Initial load
duke
parents:
diff changeset
   535
        // The cutoff of 95 was chosen empirically for best performance
90ce3da70b43 Initial load
duke
parents:
diff changeset
   536
        prime = (bitLength < 95 ? smallPrime(bitLength, certainty, rnd)
90ce3da70b43 Initial load
duke
parents:
diff changeset
   537
                                : largePrime(bitLength, certainty, rnd));
90ce3da70b43 Initial load
duke
parents:
diff changeset
   538
        signum = 1;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   539
        mag = prime.mag;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   540
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   541
90ce3da70b43 Initial load
duke
parents:
diff changeset
   542
    // Minimum size in bits that the requested prime number has
90ce3da70b43 Initial load
duke
parents:
diff changeset
   543
    // before we use the large prime number generating algorithms
90ce3da70b43 Initial load
duke
parents:
diff changeset
   544
    private static final int SMALL_PRIME_THRESHOLD = 95;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   545
90ce3da70b43 Initial load
duke
parents:
diff changeset
   546
    // Certainty required to meet the spec of probablePrime
90ce3da70b43 Initial load
duke
parents:
diff changeset
   547
    private static final int DEFAULT_PRIME_CERTAINTY = 100;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   548
90ce3da70b43 Initial load
duke
parents:
diff changeset
   549
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
   550
     * Returns a positive BigInteger that is probably prime, with the
90ce3da70b43 Initial load
duke
parents:
diff changeset
   551
     * specified bitLength. The probability that a BigInteger returned
90ce3da70b43 Initial load
duke
parents:
diff changeset
   552
     * by this method is composite does not exceed 2<sup>-100</sup>.
90ce3da70b43 Initial load
duke
parents:
diff changeset
   553
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
   554
     * @param  bitLength bitLength of the returned BigInteger.
90ce3da70b43 Initial load
duke
parents:
diff changeset
   555
     * @param  rnd source of random bits used to select candidates to be
90ce3da70b43 Initial load
duke
parents:
diff changeset
   556
     *         tested for primality.
90ce3da70b43 Initial load
duke
parents:
diff changeset
   557
     * @return a BigInteger of {@code bitLength} bits that is probably prime
90ce3da70b43 Initial load
duke
parents:
diff changeset
   558
     * @throws ArithmeticException {@code bitLength < 2}.
90ce3da70b43 Initial load
duke
parents:
diff changeset
   559
     * @see    #bitLength()
90ce3da70b43 Initial load
duke
parents:
diff changeset
   560
     * @since 1.4
90ce3da70b43 Initial load
duke
parents:
diff changeset
   561
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
   562
    public static BigInteger probablePrime(int bitLength, Random rnd) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   563
        if (bitLength < 2)
90ce3da70b43 Initial load
duke
parents:
diff changeset
   564
            throw new ArithmeticException("bitLength < 2");
90ce3da70b43 Initial load
duke
parents:
diff changeset
   565
90ce3da70b43 Initial load
duke
parents:
diff changeset
   566
        // The cutoff of 95 was chosen empirically for best performance
90ce3da70b43 Initial load
duke
parents:
diff changeset
   567
        return (bitLength < SMALL_PRIME_THRESHOLD ?
90ce3da70b43 Initial load
duke
parents:
diff changeset
   568
                smallPrime(bitLength, DEFAULT_PRIME_CERTAINTY, rnd) :
90ce3da70b43 Initial load
duke
parents:
diff changeset
   569
                largePrime(bitLength, DEFAULT_PRIME_CERTAINTY, rnd));
90ce3da70b43 Initial load
duke
parents:
diff changeset
   570
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   571
90ce3da70b43 Initial load
duke
parents:
diff changeset
   572
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
   573
     * Find a random number of the specified bitLength that is probably prime.
90ce3da70b43 Initial load
duke
parents:
diff changeset
   574
     * This method is used for smaller primes, its performance degrades on
90ce3da70b43 Initial load
duke
parents:
diff changeset
   575
     * larger bitlengths.
90ce3da70b43 Initial load
duke
parents:
diff changeset
   576
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
   577
     * This method assumes bitLength > 1.
90ce3da70b43 Initial load
duke
parents:
diff changeset
   578
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
   579
    private static BigInteger smallPrime(int bitLength, int certainty, Random rnd) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   580
        int magLen = (bitLength + 31) >>> 5;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   581
        int temp[] = new int[magLen];
90ce3da70b43 Initial load
duke
parents:
diff changeset
   582
        int highBit = 1 << ((bitLength+31) & 0x1f);  // High bit of high int
90ce3da70b43 Initial load
duke
parents:
diff changeset
   583
        int highMask = (highBit << 1) - 1;  // Bits to keep in high int
90ce3da70b43 Initial load
duke
parents:
diff changeset
   584
90ce3da70b43 Initial load
duke
parents:
diff changeset
   585
        while(true) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   586
            // Construct a candidate
90ce3da70b43 Initial load
duke
parents:
diff changeset
   587
            for (int i=0; i<magLen; i++)
90ce3da70b43 Initial load
duke
parents:
diff changeset
   588
                temp[i] = rnd.nextInt();
90ce3da70b43 Initial load
duke
parents:
diff changeset
   589
            temp[0] = (temp[0] & highMask) | highBit;  // Ensure exact length
90ce3da70b43 Initial load
duke
parents:
diff changeset
   590
            if (bitLength > 2)
90ce3da70b43 Initial load
duke
parents:
diff changeset
   591
                temp[magLen-1] |= 1;  // Make odd if bitlen > 2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   592
90ce3da70b43 Initial load
duke
parents:
diff changeset
   593
            BigInteger p = new BigInteger(temp, 1);
90ce3da70b43 Initial load
duke
parents:
diff changeset
   594
90ce3da70b43 Initial load
duke
parents:
diff changeset
   595
            // Do cheap "pre-test" if applicable
90ce3da70b43 Initial load
duke
parents:
diff changeset
   596
            if (bitLength > 6) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   597
                long r = p.remainder(SMALL_PRIME_PRODUCT).longValue();
90ce3da70b43 Initial load
duke
parents:
diff changeset
   598
                if ((r%3==0)  || (r%5==0)  || (r%7==0)  || (r%11==0) ||
90ce3da70b43 Initial load
duke
parents:
diff changeset
   599
                    (r%13==0) || (r%17==0) || (r%19==0) || (r%23==0) ||
90ce3da70b43 Initial load
duke
parents:
diff changeset
   600
                    (r%29==0) || (r%31==0) || (r%37==0) || (r%41==0))
90ce3da70b43 Initial load
duke
parents:
diff changeset
   601
                    continue; // Candidate is composite; try another
90ce3da70b43 Initial load
duke
parents:
diff changeset
   602
            }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   603
90ce3da70b43 Initial load
duke
parents:
diff changeset
   604
            // All candidates of bitLength 2 and 3 are prime by this point
90ce3da70b43 Initial load
duke
parents:
diff changeset
   605
            if (bitLength < 4)
90ce3da70b43 Initial load
duke
parents:
diff changeset
   606
                return p;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   607
90ce3da70b43 Initial load
duke
parents:
diff changeset
   608
            // Do expensive test if we survive pre-test (or it's inapplicable)
90ce3da70b43 Initial load
duke
parents:
diff changeset
   609
            if (p.primeToCertainty(certainty, rnd))
90ce3da70b43 Initial load
duke
parents:
diff changeset
   610
                return p;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   611
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   612
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   613
90ce3da70b43 Initial load
duke
parents:
diff changeset
   614
    private static final BigInteger SMALL_PRIME_PRODUCT
90ce3da70b43 Initial load
duke
parents:
diff changeset
   615
                       = valueOf(3L*5*7*11*13*17*19*23*29*31*37*41);
90ce3da70b43 Initial load
duke
parents:
diff changeset
   616
90ce3da70b43 Initial load
duke
parents:
diff changeset
   617
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
   618
     * Find a random number of the specified bitLength that is probably prime.
90ce3da70b43 Initial load
duke
parents:
diff changeset
   619
     * This method is more appropriate for larger bitlengths since it uses
90ce3da70b43 Initial load
duke
parents:
diff changeset
   620
     * a sieve to eliminate most composites before using a more expensive
90ce3da70b43 Initial load
duke
parents:
diff changeset
   621
     * test.
90ce3da70b43 Initial load
duke
parents:
diff changeset
   622
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
   623
    private static BigInteger largePrime(int bitLength, int certainty, Random rnd) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   624
        BigInteger p;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   625
        p = new BigInteger(bitLength, rnd).setBit(bitLength-1);
90ce3da70b43 Initial load
duke
parents:
diff changeset
   626
        p.mag[p.mag.length-1] &= 0xfffffffe;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   627
90ce3da70b43 Initial load
duke
parents:
diff changeset
   628
        // Use a sieve length likely to contain the next prime number
90ce3da70b43 Initial load
duke
parents:
diff changeset
   629
        int searchLen = (bitLength / 20) * 64;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   630
        BitSieve searchSieve = new BitSieve(p, searchLen);
90ce3da70b43 Initial load
duke
parents:
diff changeset
   631
        BigInteger candidate = searchSieve.retrieve(p, certainty, rnd);
90ce3da70b43 Initial load
duke
parents:
diff changeset
   632
90ce3da70b43 Initial load
duke
parents:
diff changeset
   633
        while ((candidate == null) || (candidate.bitLength() != bitLength)) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   634
            p = p.add(BigInteger.valueOf(2*searchLen));
90ce3da70b43 Initial load
duke
parents:
diff changeset
   635
            if (p.bitLength() != bitLength)
90ce3da70b43 Initial load
duke
parents:
diff changeset
   636
                p = new BigInteger(bitLength, rnd).setBit(bitLength-1);
90ce3da70b43 Initial load
duke
parents:
diff changeset
   637
            p.mag[p.mag.length-1] &= 0xfffffffe;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   638
            searchSieve = new BitSieve(p, searchLen);
90ce3da70b43 Initial load
duke
parents:
diff changeset
   639
            candidate = searchSieve.retrieve(p, certainty, rnd);
90ce3da70b43 Initial load
duke
parents:
diff changeset
   640
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   641
        return candidate;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   642
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   643
90ce3da70b43 Initial load
duke
parents:
diff changeset
   644
   /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
   645
    * Returns the first integer greater than this {@code BigInteger} that
90ce3da70b43 Initial load
duke
parents:
diff changeset
   646
    * is probably prime.  The probability that the number returned by this
90ce3da70b43 Initial load
duke
parents:
diff changeset
   647
    * method is composite does not exceed 2<sup>-100</sup>. This method will
90ce3da70b43 Initial load
duke
parents:
diff changeset
   648
    * never skip over a prime when searching: if it returns {@code p}, there
90ce3da70b43 Initial load
duke
parents:
diff changeset
   649
    * is no prime {@code q} such that {@code this < q < p}.
90ce3da70b43 Initial load
duke
parents:
diff changeset
   650
    *
90ce3da70b43 Initial load
duke
parents:
diff changeset
   651
    * @return the first integer greater than this {@code BigInteger} that
90ce3da70b43 Initial load
duke
parents:
diff changeset
   652
    *         is probably prime.
90ce3da70b43 Initial load
duke
parents:
diff changeset
   653
    * @throws ArithmeticException {@code this < 0}.
90ce3da70b43 Initial load
duke
parents:
diff changeset
   654
    * @since 1.5
90ce3da70b43 Initial load
duke
parents:
diff changeset
   655
    */
90ce3da70b43 Initial load
duke
parents:
diff changeset
   656
    public BigInteger nextProbablePrime() {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   657
        if (this.signum < 0)
90ce3da70b43 Initial load
duke
parents:
diff changeset
   658
            throw new ArithmeticException("start < 0: " + this);
90ce3da70b43 Initial load
duke
parents:
diff changeset
   659
90ce3da70b43 Initial load
duke
parents:
diff changeset
   660
        // Handle trivial cases
90ce3da70b43 Initial load
duke
parents:
diff changeset
   661
        if ((this.signum == 0) || this.equals(ONE))
90ce3da70b43 Initial load
duke
parents:
diff changeset
   662
            return TWO;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   663
90ce3da70b43 Initial load
duke
parents:
diff changeset
   664
        BigInteger result = this.add(ONE);
90ce3da70b43 Initial load
duke
parents:
diff changeset
   665
90ce3da70b43 Initial load
duke
parents:
diff changeset
   666
        // Fastpath for small numbers
90ce3da70b43 Initial load
duke
parents:
diff changeset
   667
        if (result.bitLength() < SMALL_PRIME_THRESHOLD) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   668
90ce3da70b43 Initial load
duke
parents:
diff changeset
   669
            // Ensure an odd number
90ce3da70b43 Initial load
duke
parents:
diff changeset
   670
            if (!result.testBit(0))
90ce3da70b43 Initial load
duke
parents:
diff changeset
   671
                result = result.add(ONE);
90ce3da70b43 Initial load
duke
parents:
diff changeset
   672
90ce3da70b43 Initial load
duke
parents:
diff changeset
   673
            while(true) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   674
                // Do cheap "pre-test" if applicable
90ce3da70b43 Initial load
duke
parents:
diff changeset
   675
                if (result.bitLength() > 6) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   676
                    long r = result.remainder(SMALL_PRIME_PRODUCT).longValue();
90ce3da70b43 Initial load
duke
parents:
diff changeset
   677
                    if ((r%3==0)  || (r%5==0)  || (r%7==0)  || (r%11==0) ||
90ce3da70b43 Initial load
duke
parents:
diff changeset
   678
                        (r%13==0) || (r%17==0) || (r%19==0) || (r%23==0) ||
90ce3da70b43 Initial load
duke
parents:
diff changeset
   679
                        (r%29==0) || (r%31==0) || (r%37==0) || (r%41==0)) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   680
                        result = result.add(TWO);
90ce3da70b43 Initial load
duke
parents:
diff changeset
   681
                        continue; // Candidate is composite; try another
90ce3da70b43 Initial load
duke
parents:
diff changeset
   682
                    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   683
                }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   684
90ce3da70b43 Initial load
duke
parents:
diff changeset
   685
                // All candidates of bitLength 2 and 3 are prime by this point
90ce3da70b43 Initial load
duke
parents:
diff changeset
   686
                if (result.bitLength() < 4)
90ce3da70b43 Initial load
duke
parents:
diff changeset
   687
                    return result;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   688
90ce3da70b43 Initial load
duke
parents:
diff changeset
   689
                // The expensive test
90ce3da70b43 Initial load
duke
parents:
diff changeset
   690
                if (result.primeToCertainty(DEFAULT_PRIME_CERTAINTY, null))
90ce3da70b43 Initial load
duke
parents:
diff changeset
   691
                    return result;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   692
90ce3da70b43 Initial load
duke
parents:
diff changeset
   693
                result = result.add(TWO);
90ce3da70b43 Initial load
duke
parents:
diff changeset
   694
            }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   695
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   696
90ce3da70b43 Initial load
duke
parents:
diff changeset
   697
        // Start at previous even number
90ce3da70b43 Initial load
duke
parents:
diff changeset
   698
        if (result.testBit(0))
90ce3da70b43 Initial load
duke
parents:
diff changeset
   699
            result = result.subtract(ONE);
90ce3da70b43 Initial load
duke
parents:
diff changeset
   700
90ce3da70b43 Initial load
duke
parents:
diff changeset
   701
        // Looking for the next large prime
90ce3da70b43 Initial load
duke
parents:
diff changeset
   702
        int searchLen = (result.bitLength() / 20) * 64;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   703
90ce3da70b43 Initial load
duke
parents:
diff changeset
   704
        while(true) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   705
           BitSieve searchSieve = new BitSieve(result, searchLen);
90ce3da70b43 Initial load
duke
parents:
diff changeset
   706
           BigInteger candidate = searchSieve.retrieve(result,
90ce3da70b43 Initial load
duke
parents:
diff changeset
   707
                                                 DEFAULT_PRIME_CERTAINTY, null);
90ce3da70b43 Initial load
duke
parents:
diff changeset
   708
           if (candidate != null)
90ce3da70b43 Initial load
duke
parents:
diff changeset
   709
               return candidate;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   710
           result = result.add(BigInteger.valueOf(2 * searchLen));
90ce3da70b43 Initial load
duke
parents:
diff changeset
   711
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   712
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   713
90ce3da70b43 Initial load
duke
parents:
diff changeset
   714
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
   715
     * Returns {@code true} if this BigInteger is probably prime,
90ce3da70b43 Initial load
duke
parents:
diff changeset
   716
     * {@code false} if it's definitely composite.
90ce3da70b43 Initial load
duke
parents:
diff changeset
   717
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
   718
     * This method assumes bitLength > 2.
90ce3da70b43 Initial load
duke
parents:
diff changeset
   719
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
   720
     * @param  certainty a measure of the uncertainty that the caller is
90ce3da70b43 Initial load
duke
parents:
diff changeset
   721
     *         willing to tolerate: if the call returns {@code true}
90ce3da70b43 Initial load
duke
parents:
diff changeset
   722
     *         the probability that this BigInteger is prime exceeds
90ce3da70b43 Initial load
duke
parents:
diff changeset
   723
     *         {@code (1 - 1/2<sup>certainty</sup>)}.  The execution time of
90ce3da70b43 Initial load
duke
parents:
diff changeset
   724
     *         this method is proportional to the value of this parameter.
90ce3da70b43 Initial load
duke
parents:
diff changeset
   725
     * @return {@code true} if this BigInteger is probably prime,
90ce3da70b43 Initial load
duke
parents:
diff changeset
   726
     *         {@code false} if it's definitely composite.
90ce3da70b43 Initial load
duke
parents:
diff changeset
   727
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
   728
    boolean primeToCertainty(int certainty, Random random) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   729
        int rounds = 0;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   730
        int n = (Math.min(certainty, Integer.MAX_VALUE-1)+1)/2;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   731
90ce3da70b43 Initial load
duke
parents:
diff changeset
   732
        // The relationship between the certainty and the number of rounds
90ce3da70b43 Initial load
duke
parents:
diff changeset
   733
        // we perform is given in the draft standard ANSI X9.80, "PRIME
90ce3da70b43 Initial load
duke
parents:
diff changeset
   734
        // NUMBER GENERATION, PRIMALITY TESTING, AND PRIMALITY CERTIFICATES".
90ce3da70b43 Initial load
duke
parents:
diff changeset
   735
        int sizeInBits = this.bitLength();
90ce3da70b43 Initial load
duke
parents:
diff changeset
   736
        if (sizeInBits < 100) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   737
            rounds = 50;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   738
            rounds = n < rounds ? n : rounds;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   739
            return passesMillerRabin(rounds, random);
90ce3da70b43 Initial load
duke
parents:
diff changeset
   740
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   741
90ce3da70b43 Initial load
duke
parents:
diff changeset
   742
        if (sizeInBits < 256) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   743
            rounds = 27;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   744
        } else if (sizeInBits < 512) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   745
            rounds = 15;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   746
        } else if (sizeInBits < 768) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   747
            rounds = 8;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   748
        } else if (sizeInBits < 1024) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   749
            rounds = 4;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   750
        } else {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   751
            rounds = 2;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   752
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   753
        rounds = n < rounds ? n : rounds;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   754
90ce3da70b43 Initial load
duke
parents:
diff changeset
   755
        return passesMillerRabin(rounds, random) && passesLucasLehmer();
90ce3da70b43 Initial load
duke
parents:
diff changeset
   756
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   757
90ce3da70b43 Initial load
duke
parents:
diff changeset
   758
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
   759
     * Returns true iff this BigInteger is a Lucas-Lehmer probable prime.
90ce3da70b43 Initial load
duke
parents:
diff changeset
   760
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
   761
     * The following assumptions are made:
90ce3da70b43 Initial load
duke
parents:
diff changeset
   762
     * This BigInteger is a positive, odd number.
90ce3da70b43 Initial load
duke
parents:
diff changeset
   763
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
   764
    private boolean passesLucasLehmer() {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   765
        BigInteger thisPlusOne = this.add(ONE);
90ce3da70b43 Initial load
duke
parents:
diff changeset
   766
90ce3da70b43 Initial load
duke
parents:
diff changeset
   767
        // Step 1
90ce3da70b43 Initial load
duke
parents:
diff changeset
   768
        int d = 5;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   769
        while (jacobiSymbol(d, this) != -1) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   770
            // 5, -7, 9, -11, ...
90ce3da70b43 Initial load
duke
parents:
diff changeset
   771
            d = (d<0) ? Math.abs(d)+2 : -(d+2);
90ce3da70b43 Initial load
duke
parents:
diff changeset
   772
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   773
90ce3da70b43 Initial load
duke
parents:
diff changeset
   774
        // Step 2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   775
        BigInteger u = lucasLehmerSequence(d, thisPlusOne, this);
90ce3da70b43 Initial load
duke
parents:
diff changeset
   776
90ce3da70b43 Initial load
duke
parents:
diff changeset
   777
        // Step 3
90ce3da70b43 Initial load
duke
parents:
diff changeset
   778
        return u.mod(this).equals(ZERO);
90ce3da70b43 Initial load
duke
parents:
diff changeset
   779
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   780
90ce3da70b43 Initial load
duke
parents:
diff changeset
   781
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
   782
     * Computes Jacobi(p,n).
90ce3da70b43 Initial load
duke
parents:
diff changeset
   783
     * Assumes n positive, odd, n>=3.
90ce3da70b43 Initial load
duke
parents:
diff changeset
   784
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
   785
    private static int jacobiSymbol(int p, BigInteger n) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   786
        if (p == 0)
90ce3da70b43 Initial load
duke
parents:
diff changeset
   787
            return 0;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   788
90ce3da70b43 Initial load
duke
parents:
diff changeset
   789
        // Algorithm and comments adapted from Colin Plumb's C library.
90ce3da70b43 Initial load
duke
parents:
diff changeset
   790
        int j = 1;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   791
        int u = n.mag[n.mag.length-1];
90ce3da70b43 Initial load
duke
parents:
diff changeset
   792
90ce3da70b43 Initial load
duke
parents:
diff changeset
   793
        // Make p positive
90ce3da70b43 Initial load
duke
parents:
diff changeset
   794
        if (p < 0) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   795
            p = -p;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   796
            int n8 = u & 7;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   797
            if ((n8 == 3) || (n8 == 7))
90ce3da70b43 Initial load
duke
parents:
diff changeset
   798
                j = -j; // 3 (011) or 7 (111) mod 8
90ce3da70b43 Initial load
duke
parents:
diff changeset
   799
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   800
90ce3da70b43 Initial load
duke
parents:
diff changeset
   801
        // Get rid of factors of 2 in p
90ce3da70b43 Initial load
duke
parents:
diff changeset
   802
        while ((p & 3) == 0)
90ce3da70b43 Initial load
duke
parents:
diff changeset
   803
            p >>= 2;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   804
        if ((p & 1) == 0) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   805
            p >>= 1;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   806
            if (((u ^ (u>>1)) & 2) != 0)
90ce3da70b43 Initial load
duke
parents:
diff changeset
   807
                j = -j; // 3 (011) or 5 (101) mod 8
90ce3da70b43 Initial load
duke
parents:
diff changeset
   808
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   809
        if (p == 1)
90ce3da70b43 Initial load
duke
parents:
diff changeset
   810
            return j;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   811
        // Then, apply quadratic reciprocity
90ce3da70b43 Initial load
duke
parents:
diff changeset
   812
        if ((p & u & 2) != 0)   // p = u = 3 (mod 4)?
90ce3da70b43 Initial load
duke
parents:
diff changeset
   813
            j = -j;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   814
        // And reduce u mod p
90ce3da70b43 Initial load
duke
parents:
diff changeset
   815
        u = n.mod(BigInteger.valueOf(p)).intValue();
90ce3da70b43 Initial load
duke
parents:
diff changeset
   816
90ce3da70b43 Initial load
duke
parents:
diff changeset
   817
        // Now compute Jacobi(u,p), u < p
90ce3da70b43 Initial load
duke
parents:
diff changeset
   818
        while (u != 0) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   819
            while ((u & 3) == 0)
90ce3da70b43 Initial load
duke
parents:
diff changeset
   820
                u >>= 2;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   821
            if ((u & 1) == 0) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   822
                u >>= 1;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   823
                if (((p ^ (p>>1)) & 2) != 0)
90ce3da70b43 Initial load
duke
parents:
diff changeset
   824
                    j = -j;     // 3 (011) or 5 (101) mod 8
90ce3da70b43 Initial load
duke
parents:
diff changeset
   825
            }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   826
            if (u == 1)
90ce3da70b43 Initial load
duke
parents:
diff changeset
   827
                return j;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   828
            // Now both u and p are odd, so use quadratic reciprocity
90ce3da70b43 Initial load
duke
parents:
diff changeset
   829
            assert (u < p);
90ce3da70b43 Initial load
duke
parents:
diff changeset
   830
            int t = u; u = p; p = t;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   831
            if ((u & p & 2) != 0) // u = p = 3 (mod 4)?
90ce3da70b43 Initial load
duke
parents:
diff changeset
   832
                j = -j;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   833
            // Now u >= p, so it can be reduced
90ce3da70b43 Initial load
duke
parents:
diff changeset
   834
            u %= p;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   835
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   836
        return 0;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   837
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   838
90ce3da70b43 Initial load
duke
parents:
diff changeset
   839
    private static BigInteger lucasLehmerSequence(int z, BigInteger k, BigInteger n) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   840
        BigInteger d = BigInteger.valueOf(z);
90ce3da70b43 Initial load
duke
parents:
diff changeset
   841
        BigInteger u = ONE; BigInteger u2;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   842
        BigInteger v = ONE; BigInteger v2;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   843
90ce3da70b43 Initial load
duke
parents:
diff changeset
   844
        for (int i=k.bitLength()-2; i>=0; i--) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   845
            u2 = u.multiply(v).mod(n);
90ce3da70b43 Initial load
duke
parents:
diff changeset
   846
90ce3da70b43 Initial load
duke
parents:
diff changeset
   847
            v2 = v.square().add(d.multiply(u.square())).mod(n);
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
   848
            if (v2.testBit(0))
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
   849
                v2 = v2.subtract(n);
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
   850
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   851
            v2 = v2.shiftRight(1);
90ce3da70b43 Initial load
duke
parents:
diff changeset
   852
90ce3da70b43 Initial load
duke
parents:
diff changeset
   853
            u = u2; v = v2;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   854
            if (k.testBit(i)) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   855
                u2 = u.add(v).mod(n);
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
   856
                if (u2.testBit(0))
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
   857
                    u2 = u2.subtract(n);
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
   858
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   859
                u2 = u2.shiftRight(1);
90ce3da70b43 Initial load
duke
parents:
diff changeset
   860
                v2 = v.add(d.multiply(u)).mod(n);
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
   861
                if (v2.testBit(0))
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
   862
                    v2 = v2.subtract(n);
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   863
                v2 = v2.shiftRight(1);
90ce3da70b43 Initial load
duke
parents:
diff changeset
   864
90ce3da70b43 Initial load
duke
parents:
diff changeset
   865
                u = u2; v = v2;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   866
            }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   867
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   868
        return u;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   869
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   870
90ce3da70b43 Initial load
duke
parents:
diff changeset
   871
    private static volatile Random staticRandom;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   872
90ce3da70b43 Initial load
duke
parents:
diff changeset
   873
    private static Random getSecureRandom() {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   874
        if (staticRandom == null) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   875
            staticRandom = new java.security.SecureRandom();
90ce3da70b43 Initial load
duke
parents:
diff changeset
   876
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   877
        return staticRandom;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   878
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   879
90ce3da70b43 Initial load
duke
parents:
diff changeset
   880
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
   881
     * Returns true iff this BigInteger passes the specified number of
90ce3da70b43 Initial load
duke
parents:
diff changeset
   882
     * Miller-Rabin tests. This test is taken from the DSA spec (NIST FIPS
90ce3da70b43 Initial load
duke
parents:
diff changeset
   883
     * 186-2).
90ce3da70b43 Initial load
duke
parents:
diff changeset
   884
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
   885
     * The following assumptions are made:
90ce3da70b43 Initial load
duke
parents:
diff changeset
   886
     * This BigInteger is a positive, odd number greater than 2.
90ce3da70b43 Initial load
duke
parents:
diff changeset
   887
     * iterations<=50.
90ce3da70b43 Initial load
duke
parents:
diff changeset
   888
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
   889
    private boolean passesMillerRabin(int iterations, Random rnd) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   890
        // Find a and m such that m is odd and this == 1 + 2**a * m
90ce3da70b43 Initial load
duke
parents:
diff changeset
   891
        BigInteger thisMinusOne = this.subtract(ONE);
90ce3da70b43 Initial load
duke
parents:
diff changeset
   892
        BigInteger m = thisMinusOne;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   893
        int a = m.getLowestSetBit();
90ce3da70b43 Initial load
duke
parents:
diff changeset
   894
        m = m.shiftRight(a);
90ce3da70b43 Initial load
duke
parents:
diff changeset
   895
90ce3da70b43 Initial load
duke
parents:
diff changeset
   896
        // Do the tests
90ce3da70b43 Initial load
duke
parents:
diff changeset
   897
        if (rnd == null) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   898
            rnd = getSecureRandom();
90ce3da70b43 Initial load
duke
parents:
diff changeset
   899
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   900
        for (int i=0; i<iterations; i++) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   901
            // Generate a uniform random on (1, this)
90ce3da70b43 Initial load
duke
parents:
diff changeset
   902
            BigInteger b;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   903
            do {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   904
                b = new BigInteger(this.bitLength(), rnd);
90ce3da70b43 Initial load
duke
parents:
diff changeset
   905
            } while (b.compareTo(ONE) <= 0 || b.compareTo(this) >= 0);
90ce3da70b43 Initial load
duke
parents:
diff changeset
   906
90ce3da70b43 Initial load
duke
parents:
diff changeset
   907
            int j = 0;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   908
            BigInteger z = b.modPow(m, this);
90ce3da70b43 Initial load
duke
parents:
diff changeset
   909
            while(!((j==0 && z.equals(ONE)) || z.equals(thisMinusOne))) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   910
                if (j>0 && z.equals(ONE) || ++j==a)
90ce3da70b43 Initial load
duke
parents:
diff changeset
   911
                    return false;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   912
                z = z.modPow(TWO, this);
90ce3da70b43 Initial load
duke
parents:
diff changeset
   913
            }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   914
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   915
        return true;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   916
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   917
90ce3da70b43 Initial load
duke
parents:
diff changeset
   918
    /**
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
   919
     * This internal constructor differs from its public cousin
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   920
     * with the arguments reversed in two ways: it assumes that its
90ce3da70b43 Initial load
duke
parents:
diff changeset
   921
     * arguments are correct, and it doesn't copy the magnitude array.
90ce3da70b43 Initial load
duke
parents:
diff changeset
   922
     */
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
   923
    BigInteger(int[] magnitude, int signum) {
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   924
        this.signum = (magnitude.length==0 ? 0 : signum);
90ce3da70b43 Initial load
duke
parents:
diff changeset
   925
        this.mag = magnitude;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   926
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   927
90ce3da70b43 Initial load
duke
parents:
diff changeset
   928
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
   929
     * This private constructor is for internal use and assumes that its
90ce3da70b43 Initial load
duke
parents:
diff changeset
   930
     * arguments are correct.
90ce3da70b43 Initial load
duke
parents:
diff changeset
   931
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
   932
    private BigInteger(byte[] magnitude, int signum) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   933
        this.signum = (magnitude.length==0 ? 0 : signum);
90ce3da70b43 Initial load
duke
parents:
diff changeset
   934
        this.mag = stripLeadingZeroBytes(magnitude);
90ce3da70b43 Initial load
duke
parents:
diff changeset
   935
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   936
90ce3da70b43 Initial load
duke
parents:
diff changeset
   937
    //Static Factory Methods
90ce3da70b43 Initial load
duke
parents:
diff changeset
   938
90ce3da70b43 Initial load
duke
parents:
diff changeset
   939
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
   940
     * Returns a BigInteger whose value is equal to that of the
90ce3da70b43 Initial load
duke
parents:
diff changeset
   941
     * specified {@code long}.  This "static factory method" is
90ce3da70b43 Initial load
duke
parents:
diff changeset
   942
     * provided in preference to a ({@code long}) constructor
90ce3da70b43 Initial load
duke
parents:
diff changeset
   943
     * because it allows for reuse of frequently used BigIntegers.
90ce3da70b43 Initial load
duke
parents:
diff changeset
   944
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
   945
     * @param  val value of the BigInteger to return.
90ce3da70b43 Initial load
duke
parents:
diff changeset
   946
     * @return a BigInteger with the specified value.
90ce3da70b43 Initial load
duke
parents:
diff changeset
   947
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
   948
    public static BigInteger valueOf(long val) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   949
        // If -MAX_CONSTANT < val < MAX_CONSTANT, return stashed constant
90ce3da70b43 Initial load
duke
parents:
diff changeset
   950
        if (val == 0)
90ce3da70b43 Initial load
duke
parents:
diff changeset
   951
            return ZERO;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   952
        if (val > 0 && val <= MAX_CONSTANT)
90ce3da70b43 Initial load
duke
parents:
diff changeset
   953
            return posConst[(int) val];
90ce3da70b43 Initial load
duke
parents:
diff changeset
   954
        else if (val < 0 && val >= -MAX_CONSTANT)
90ce3da70b43 Initial load
duke
parents:
diff changeset
   955
            return negConst[(int) -val];
90ce3da70b43 Initial load
duke
parents:
diff changeset
   956
90ce3da70b43 Initial load
duke
parents:
diff changeset
   957
        return new BigInteger(val);
90ce3da70b43 Initial load
duke
parents:
diff changeset
   958
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   959
90ce3da70b43 Initial load
duke
parents:
diff changeset
   960
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
   961
     * Constructs a BigInteger with the specified value, which may not be zero.
90ce3da70b43 Initial load
duke
parents:
diff changeset
   962
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
   963
    private BigInteger(long val) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   964
        if (val < 0) {
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
   965
            val = -val;
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   966
            signum = -1;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   967
        } else {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   968
            signum = 1;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   969
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   970
90ce3da70b43 Initial load
duke
parents:
diff changeset
   971
        int highWord = (int)(val >>> 32);
90ce3da70b43 Initial load
duke
parents:
diff changeset
   972
        if (highWord==0) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   973
            mag = new int[1];
90ce3da70b43 Initial load
duke
parents:
diff changeset
   974
            mag[0] = (int)val;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   975
        } else {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   976
            mag = new int[2];
90ce3da70b43 Initial load
duke
parents:
diff changeset
   977
            mag[0] = highWord;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   978
            mag[1] = (int)val;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   979
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   980
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   981
90ce3da70b43 Initial load
duke
parents:
diff changeset
   982
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
   983
     * Returns a BigInteger with the given two's complement representation.
90ce3da70b43 Initial load
duke
parents:
diff changeset
   984
     * Assumes that the input array will not be modified (the returned
90ce3da70b43 Initial load
duke
parents:
diff changeset
   985
     * BigInteger will reference the input array if feasible).
90ce3da70b43 Initial load
duke
parents:
diff changeset
   986
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
   987
    private static BigInteger valueOf(int val[]) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   988
        return (val[0]>0 ? new BigInteger(val, 1) : new BigInteger(val));
90ce3da70b43 Initial load
duke
parents:
diff changeset
   989
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   990
90ce3da70b43 Initial load
duke
parents:
diff changeset
   991
    // Constants
90ce3da70b43 Initial load
duke
parents:
diff changeset
   992
90ce3da70b43 Initial load
duke
parents:
diff changeset
   993
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
   994
     * Initialize static constant array when class is loaded.
90ce3da70b43 Initial load
duke
parents:
diff changeset
   995
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
   996
    private final static int MAX_CONSTANT = 16;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   997
    private static BigInteger posConst[] = new BigInteger[MAX_CONSTANT+1];
90ce3da70b43 Initial load
duke
parents:
diff changeset
   998
    private static BigInteger negConst[] = new BigInteger[MAX_CONSTANT+1];
90ce3da70b43 Initial load
duke
parents:
diff changeset
   999
    static {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1000
        for (int i = 1; i <= MAX_CONSTANT; i++) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1001
            int[] magnitude = new int[1];
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1002
            magnitude[0] = i;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1003
            posConst[i] = new BigInteger(magnitude,  1);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1004
            negConst[i] = new BigInteger(magnitude, -1);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1005
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1006
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1007
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1008
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1009
     * The BigInteger constant zero.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1010
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1011
     * @since   1.2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1012
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1013
    public static final BigInteger ZERO = new BigInteger(new int[0], 0);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1014
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1015
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1016
     * The BigInteger constant one.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1017
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1018
     * @since   1.2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1019
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1020
    public static final BigInteger ONE = valueOf(1);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1021
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1022
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1023
     * The BigInteger constant two.  (Not exported.)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1024
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1025
    private static final BigInteger TWO = valueOf(2);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1026
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1027
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1028
     * The BigInteger constant ten.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1029
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1030
     * @since   1.5
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1031
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1032
    public static final BigInteger TEN = valueOf(10);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1033
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1034
    // Arithmetic Operations
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1035
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1036
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1037
     * Returns a BigInteger whose value is {@code (this + val)}.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1038
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1039
     * @param  val value to be added to this BigInteger.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1040
     * @return {@code this + val}
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1041
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1042
    public BigInteger add(BigInteger val) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1043
        if (val.signum == 0)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1044
            return this;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1045
        if (signum == 0)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1046
            return val;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1047
        if (val.signum == signum)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1048
            return new BigInteger(add(mag, val.mag), signum);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1049
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  1050
        int cmp = compareMagnitude(val);
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  1051
        if (cmp == 0)
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1052
            return ZERO;
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  1053
        int[] resultMag = (cmp > 0 ? subtract(mag, val.mag)
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1054
                           : subtract(val.mag, mag));
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1055
        resultMag = trustedStripLeadingZeroInts(resultMag);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1056
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  1057
        return new BigInteger(resultMag, cmp == signum ? 1 : -1);
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1058
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1059
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1060
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1061
     * Adds the contents of the int arrays x and y. This method allocates
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1062
     * a new int array to hold the answer and returns a reference to that
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1063
     * array.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1064
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1065
    private static int[] add(int[] x, int[] y) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1066
        // If x is shorter, swap the two arrays
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1067
        if (x.length < y.length) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1068
            int[] tmp = x;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1069
            x = y;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1070
            y = tmp;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1071
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1072
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1073
        int xIndex = x.length;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1074
        int yIndex = y.length;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1075
        int result[] = new int[xIndex];
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1076
        long sum = 0;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1077
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1078
        // Add common parts of both numbers
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1079
        while(yIndex > 0) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1080
            sum = (x[--xIndex] & LONG_MASK) +
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1081
                  (y[--yIndex] & LONG_MASK) + (sum >>> 32);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1082
            result[xIndex] = (int)sum;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1083
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1084
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1085
        // Copy remainder of longer number while carry propagation is required
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1086
        boolean carry = (sum >>> 32 != 0);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1087
        while (xIndex > 0 && carry)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1088
            carry = ((result[--xIndex] = x[xIndex] + 1) == 0);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1089
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1090
        // Copy remainder of longer number
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1091
        while (xIndex > 0)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1092
            result[--xIndex] = x[xIndex];
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1093
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1094
        // Grow result if necessary
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1095
        if (carry) {
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  1096
            int bigger[] = new int[result.length + 1];
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  1097
            System.arraycopy(result, 0, bigger, 1, result.length);
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  1098
            bigger[0] = 0x01;
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  1099
            return bigger;
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1100
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1101
        return result;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1102
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1103
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1104
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1105
     * Returns a BigInteger whose value is {@code (this - val)}.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1106
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1107
     * @param  val value to be subtracted from this BigInteger.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1108
     * @return {@code this - val}
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1109
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1110
    public BigInteger subtract(BigInteger val) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1111
        if (val.signum == 0)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1112
            return this;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1113
        if (signum == 0)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1114
            return val.negate();
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1115
        if (val.signum != signum)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1116
            return new BigInteger(add(mag, val.mag), signum);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1117
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  1118
        int cmp = compareMagnitude(val);
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  1119
        if (cmp == 0)
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1120
            return ZERO;
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  1121
        int[] resultMag = (cmp > 0 ? subtract(mag, val.mag)
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1122
                           : subtract(val.mag, mag));
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1123
        resultMag = trustedStripLeadingZeroInts(resultMag);
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  1124
        return new BigInteger(resultMag, cmp == signum ? 1 : -1);
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1125
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1126
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1127
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1128
     * Subtracts the contents of the second int arrays (little) from the
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1129
     * first (big).  The first int array (big) must represent a larger number
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1130
     * than the second.  This method allocates the space necessary to hold the
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1131
     * answer.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1132
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1133
    private static int[] subtract(int[] big, int[] little) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1134
        int bigIndex = big.length;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1135
        int result[] = new int[bigIndex];
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1136
        int littleIndex = little.length;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1137
        long difference = 0;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1138
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1139
        // Subtract common parts of both numbers
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1140
        while(littleIndex > 0) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1141
            difference = (big[--bigIndex] & LONG_MASK) -
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1142
                         (little[--littleIndex] & LONG_MASK) +
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1143
                         (difference >> 32);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1144
            result[bigIndex] = (int)difference;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1145
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1146
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1147
        // Subtract remainder of longer number while borrow propagates
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1148
        boolean borrow = (difference >> 32 != 0);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1149
        while (bigIndex > 0 && borrow)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1150
            borrow = ((result[--bigIndex] = big[bigIndex] - 1) == -1);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1151
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1152
        // Copy remainder of longer number
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1153
        while (bigIndex > 0)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1154
            result[--bigIndex] = big[bigIndex];
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1155
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1156
        return result;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1157
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1158
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1159
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1160
     * Returns a BigInteger whose value is {@code (this * val)}.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1161
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1162
     * @param  val value to be multiplied by this BigInteger.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1163
     * @return {@code this * val}
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1164
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1165
    public BigInteger multiply(BigInteger val) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1166
        if (val.signum == 0 || signum == 0)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1167
            return ZERO;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1168
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1169
        int[] result = multiplyToLen(mag, mag.length,
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1170
                                     val.mag, val.mag.length, null);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1171
        result = trustedStripLeadingZeroInts(result);
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  1172
        return new BigInteger(result, signum == val.signum ? 1 : -1);
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  1173
    }
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  1174
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  1175
    /**
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  1176
     * Package private methods used by BigDecimal code to multiply a BigInteger
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  1177
     * with a long. Assumes v is not equal to INFLATED.
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  1178
     */
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  1179
    BigInteger multiply(long v) {
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  1180
        if (v == 0 || signum == 0)
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  1181
          return ZERO;
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  1182
        if (v == BigDecimal.INFLATED)
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  1183
            return multiply(BigInteger.valueOf(v));
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  1184
        int rsign = (v > 0 ? signum : -signum);
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  1185
        if (v < 0)
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  1186
            v = -v;
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  1187
        long dh = v >>> 32;      // higher order bits
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  1188
        long dl = v & LONG_MASK; // lower order bits
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  1189
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  1190
        int xlen = mag.length;
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  1191
        int[] value = mag;
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  1192
        int[] rmag = (dh == 0L) ? (new int[xlen + 1]) : (new int[xlen + 2]);
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  1193
        long carry = 0;
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  1194
        int rstart = rmag.length - 1;
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  1195
        for (int i = xlen - 1; i >= 0; i--) {
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  1196
            long product = (value[i] & LONG_MASK) * dl + carry;
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  1197
            rmag[rstart--] = (int)product;
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  1198
            carry = product >>> 32;
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  1199
        }
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  1200
        rmag[rstart] = (int)carry;
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  1201
        if (dh != 0L) {
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  1202
            carry = 0;
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  1203
            rstart = rmag.length - 2;
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  1204
            for (int i = xlen - 1; i >= 0; i--) {
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  1205
                long product = (value[i] & LONG_MASK) * dh +
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  1206
                    (rmag[rstart] & LONG_MASK) + carry;
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  1207
                rmag[rstart--] = (int)product;
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  1208
                carry = product >>> 32;
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  1209
            }
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  1210
            rmag[0] = (int)carry;
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  1211
        }
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  1212
        if (carry == 0L)
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  1213
            rmag = java.util.Arrays.copyOfRange(rmag, 1, rmag.length);
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  1214
        return new BigInteger(rmag, rsign);
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1215
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1216
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1217
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1218
     * Multiplies int arrays x and y to the specified lengths and places
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  1219
     * the result into z. There will be no leading zeros in the resultant array.
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1220
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1221
    private int[] multiplyToLen(int[] x, int xlen, int[] y, int ylen, int[] z) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1222
        int xstart = xlen - 1;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1223
        int ystart = ylen - 1;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1224
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1225
        if (z == null || z.length < (xlen+ ylen))
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1226
            z = new int[xlen+ylen];
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1227
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1228
        long carry = 0;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1229
        for (int j=ystart, k=ystart+1+xstart; j>=0; j--, k--) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1230
            long product = (y[j] & LONG_MASK) *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1231
                           (x[xstart] & LONG_MASK) + carry;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1232
            z[k] = (int)product;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1233
            carry = product >>> 32;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1234
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1235
        z[xstart] = (int)carry;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1236
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1237
        for (int i = xstart-1; i >= 0; i--) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1238
            carry = 0;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1239
            for (int j=ystart, k=ystart+1+i; j>=0; j--, k--) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1240
                long product = (y[j] & LONG_MASK) *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1241
                               (x[i] & LONG_MASK) +
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1242
                               (z[k] & LONG_MASK) + carry;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1243
                z[k] = (int)product;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1244
                carry = product >>> 32;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1245
            }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1246
            z[i] = (int)carry;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1247
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1248
        return z;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1249
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1250
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1251
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1252
     * Returns a BigInteger whose value is {@code (this<sup>2</sup>)}.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1253
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1254
     * @return {@code this<sup>2</sup>}
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1255
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1256
    private BigInteger square() {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1257
        if (signum == 0)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1258
            return ZERO;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1259
        int[] z = squareToLen(mag, mag.length, null);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1260
        return new BigInteger(trustedStripLeadingZeroInts(z), 1);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1261
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1262
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1263
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1264
     * Squares the contents of the int array x. The result is placed into the
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1265
     * int array z.  The contents of x are not changed.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1266
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1267
    private static final int[] squareToLen(int[] x, int len, int[] z) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1268
        /*
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1269
         * The algorithm used here is adapted from Colin Plumb's C library.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1270
         * Technique: Consider the partial products in the multiplication
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1271
         * of "abcde" by itself:
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1272
         *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1273
         *               a  b  c  d  e
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1274
         *            *  a  b  c  d  e
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1275
         *          ==================
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1276
         *              ae be ce de ee
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1277
         *           ad bd cd dd de
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1278
         *        ac bc cc cd ce
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1279
         *     ab bb bc bd be
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1280
         *  aa ab ac ad ae
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1281
         *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1282
         * Note that everything above the main diagonal:
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1283
         *              ae be ce de = (abcd) * e
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1284
         *           ad bd cd       = (abc) * d
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1285
         *        ac bc             = (ab) * c
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1286
         *     ab                   = (a) * b
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1287
         *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1288
         * is a copy of everything below the main diagonal:
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1289
         *                       de
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1290
         *                 cd ce
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1291
         *           bc bd be
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1292
         *     ab ac ad ae
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1293
         *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1294
         * Thus, the sum is 2 * (off the diagonal) + diagonal.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1295
         *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1296
         * This is accumulated beginning with the diagonal (which
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1297
         * consist of the squares of the digits of the input), which is then
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1298
         * divided by two, the off-diagonal added, and multiplied by two
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1299
         * again.  The low bit is simply a copy of the low bit of the
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1300
         * input, so it doesn't need special care.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1301
         */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1302
        int zlen = len << 1;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1303
        if (z == null || z.length < zlen)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1304
            z = new int[zlen];
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1305
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1306
        // Store the squares, right shifted one bit (i.e., divided by 2)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1307
        int lastProductLowWord = 0;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1308
        for (int j=0, i=0; j<len; j++) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1309
            long piece = (x[j] & LONG_MASK);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1310
            long product = piece * piece;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1311
            z[i++] = (lastProductLowWord << 31) | (int)(product >>> 33);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1312
            z[i++] = (int)(product >>> 1);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1313
            lastProductLowWord = (int)product;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1314
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1315
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1316
        // Add in off-diagonal sums
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1317
        for (int i=len, offset=1; i>0; i--, offset+=2) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1318
            int t = x[i-1];
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1319
            t = mulAdd(z, x, offset, i-1, t);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1320
            addOne(z, offset-1, i, t);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1321
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1322
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1323
        // Shift back up and set low bit
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1324
        primitiveLeftShift(z, zlen, 1);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1325
        z[zlen-1] |= x[len-1] & 1;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1326
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1327
        return z;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1328
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1329
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1330
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1331
     * Returns a BigInteger whose value is {@code (this / val)}.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1332
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1333
     * @param  val value by which this BigInteger is to be divided.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1334
     * @return {@code this / val}
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1335
     * @throws ArithmeticException {@code val==0}
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1336
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1337
    public BigInteger divide(BigInteger val) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1338
        MutableBigInteger q = new MutableBigInteger(),
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1339
                          a = new MutableBigInteger(this.mag),
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1340
                          b = new MutableBigInteger(val.mag);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1341
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  1342
        a.divide(b, q);
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  1343
        return q.toBigInteger(this.signum == val.signum ? 1 : -1);
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1344
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1345
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1346
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1347
     * Returns an array of two BigIntegers containing {@code (this / val)}
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1348
     * followed by {@code (this % val)}.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1349
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1350
     * @param  val value by which this BigInteger is to be divided, and the
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1351
     *         remainder computed.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1352
     * @return an array of two BigIntegers: the quotient {@code (this / val)}
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1353
     *         is the initial element, and the remainder {@code (this % val)}
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1354
     *         is the final element.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1355
     * @throws ArithmeticException {@code val==0}
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1356
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1357
    public BigInteger[] divideAndRemainder(BigInteger val) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1358
        BigInteger[] result = new BigInteger[2];
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1359
        MutableBigInteger q = new MutableBigInteger(),
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1360
                          a = new MutableBigInteger(this.mag),
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1361
                          b = new MutableBigInteger(val.mag);
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  1362
        MutableBigInteger r = a.divide(b, q);
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  1363
        result[0] = q.toBigInteger(this.signum == val.signum ? 1 : -1);
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  1364
        result[1] = r.toBigInteger(this.signum);
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1365
        return result;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1366
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1367
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1368
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1369
     * Returns a BigInteger whose value is {@code (this % val)}.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1370
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1371
     * @param  val value by which this BigInteger is to be divided, and the
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1372
     *         remainder computed.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1373
     * @return {@code this % val}
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1374
     * @throws ArithmeticException {@code val==0}
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1375
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1376
    public BigInteger remainder(BigInteger val) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1377
        MutableBigInteger q = new MutableBigInteger(),
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1378
                          a = new MutableBigInteger(this.mag),
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1379
                          b = new MutableBigInteger(val.mag);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1380
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  1381
        return a.divide(b, q).toBigInteger(this.signum);
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1382
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1383
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1384
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1385
     * Returns a BigInteger whose value is <tt>(this<sup>exponent</sup>)</tt>.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1386
     * Note that {@code exponent} is an integer rather than a BigInteger.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1387
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1388
     * @param  exponent exponent to which this BigInteger is to be raised.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1389
     * @return <tt>this<sup>exponent</sup></tt>
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1390
     * @throws ArithmeticException {@code exponent} is negative.  (This would
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1391
     *         cause the operation to yield a non-integer value.)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1392
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1393
    public BigInteger pow(int exponent) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1394
        if (exponent < 0)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1395
            throw new ArithmeticException("Negative exponent");
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1396
        if (signum==0)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1397
            return (exponent==0 ? ONE : this);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1398
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1399
        // Perform exponentiation using repeated squaring trick
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1400
        int newSign = (signum<0 && (exponent&1)==1 ? -1 : 1);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1401
        int[] baseToPow2 = this.mag;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1402
        int[] result = {1};
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1403
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1404
        while (exponent != 0) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1405
            if ((exponent & 1)==1) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1406
                result = multiplyToLen(result, result.length,
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1407
                                       baseToPow2, baseToPow2.length, null);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1408
                result = trustedStripLeadingZeroInts(result);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1409
            }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1410
            if ((exponent >>>= 1) != 0) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1411
                baseToPow2 = squareToLen(baseToPow2, baseToPow2.length, null);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1412
                baseToPow2 = trustedStripLeadingZeroInts(baseToPow2);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1413
            }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1414
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1415
        return new BigInteger(result, newSign);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1416
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1417
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1418
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1419
     * Returns a BigInteger whose value is the greatest common divisor of
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1420
     * {@code abs(this)} and {@code abs(val)}.  Returns 0 if
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1421
     * {@code this==0 && val==0}.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1422
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1423
     * @param  val value with which the GCD is to be computed.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1424
     * @return {@code GCD(abs(this), abs(val))}
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1425
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1426
    public BigInteger gcd(BigInteger val) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1427
        if (val.signum == 0)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1428
            return this.abs();
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1429
        else if (this.signum == 0)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1430
            return val.abs();
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1431
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1432
        MutableBigInteger a = new MutableBigInteger(this);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1433
        MutableBigInteger b = new MutableBigInteger(val);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1434
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1435
        MutableBigInteger result = a.hybridGCD(b);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1436
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  1437
        return result.toBigInteger(1);
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  1438
    }
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  1439
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  1440
    /**
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  1441
     * Package private method to return bit length for an integer.
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  1442
     */
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  1443
    static int bitLengthForInt(int n) {
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  1444
        return 32 - Integer.numberOfLeadingZeros(n);
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1445
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1446
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1447
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1448
     * Left shift int array a up to len by n bits. Returns the array that
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1449
     * results from the shift since space may have to be reallocated.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1450
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1451
    private static int[] leftShift(int[] a, int len, int n) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1452
        int nInts = n >>> 5;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1453
        int nBits = n&0x1F;
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  1454
        int bitsInHighWord = bitLengthForInt(a[0]);
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1455
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1456
        // If shift can be done without recopy, do so
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1457
        if (n <= (32-bitsInHighWord)) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1458
            primitiveLeftShift(a, len, nBits);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1459
            return a;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1460
        } else { // Array must be resized
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1461
            if (nBits <= (32-bitsInHighWord)) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1462
                int result[] = new int[nInts+len];
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1463
                for (int i=0; i<len; i++)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1464
                    result[i] = a[i];
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1465
                primitiveLeftShift(result, result.length, nBits);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1466
                return result;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1467
            } else {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1468
                int result[] = new int[nInts+len+1];
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1469
                for (int i=0; i<len; i++)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1470
                    result[i] = a[i];
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1471
                primitiveRightShift(result, result.length, 32 - nBits);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1472
                return result;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1473
            }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1474
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1475
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1476
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1477
    // shifts a up to len right n bits assumes no leading zeros, 0<n<32
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1478
    static void primitiveRightShift(int[] a, int len, int n) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1479
        int n2 = 32 - n;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1480
        for (int i=len-1, c=a[i]; i>0; i--) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1481
            int b = c;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1482
            c = a[i-1];
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1483
            a[i] = (c << n2) | (b >>> n);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1484
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1485
        a[0] >>>= n;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1486
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1487
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1488
    // shifts a up to len left n bits assumes no leading zeros, 0<=n<32
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1489
    static void primitiveLeftShift(int[] a, int len, int n) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1490
        if (len == 0 || n == 0)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1491
            return;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1492
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1493
        int n2 = 32 - n;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1494
        for (int i=0, c=a[i], m=i+len-1; i<m; i++) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1495
            int b = c;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1496
            c = a[i+1];
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1497
            a[i] = (b << n) | (c >>> n2);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1498
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1499
        a[len-1] <<= n;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1500
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1501
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1502
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1503
     * Calculate bitlength of contents of the first len elements an int array,
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1504
     * assuming there are no leading zero ints.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1505
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1506
    private static int bitLength(int[] val, int len) {
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  1507
        if (len == 0)
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1508
            return 0;
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  1509
        return ((len - 1) << 5) + bitLengthForInt(val[0]);
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1510
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1511
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1512
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1513
     * Returns a BigInteger whose value is the absolute value of this
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1514
     * BigInteger.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1515
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1516
     * @return {@code abs(this)}
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1517
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1518
    public BigInteger abs() {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1519
        return (signum >= 0 ? this : this.negate());
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1520
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1521
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1522
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1523
     * Returns a BigInteger whose value is {@code (-this)}.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1524
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1525
     * @return {@code -this}
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1526
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1527
    public BigInteger negate() {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1528
        return new BigInteger(this.mag, -this.signum);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1529
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1530
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1531
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1532
     * Returns the signum function of this BigInteger.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1533
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1534
     * @return -1, 0 or 1 as the value of this BigInteger is negative, zero or
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1535
     *         positive.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1536
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1537
    public int signum() {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1538
        return this.signum;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1539
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1540
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1541
    // Modular Arithmetic Operations
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1542
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1543
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1544
     * Returns a BigInteger whose value is {@code (this mod m}).  This method
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1545
     * differs from {@code remainder} in that it always returns a
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1546
     * <i>non-negative</i> BigInteger.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1547
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1548
     * @param  m the modulus.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1549
     * @return {@code this mod m}
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1550
     * @throws ArithmeticException {@code m <= 0}
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1551
     * @see    #remainder
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1552
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1553
    public BigInteger mod(BigInteger m) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1554
        if (m.signum <= 0)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1555
            throw new ArithmeticException("BigInteger: modulus not positive");
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1556
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1557
        BigInteger result = this.remainder(m);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1558
        return (result.signum >= 0 ? result : result.add(m));
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1559
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1560
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1561
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1562
     * Returns a BigInteger whose value is
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1563
     * <tt>(this<sup>exponent</sup> mod m)</tt>.  (Unlike {@code pow}, this
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1564
     * method permits negative exponents.)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1565
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1566
     * @param  exponent the exponent.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1567
     * @param  m the modulus.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1568
     * @return <tt>this<sup>exponent</sup> mod m</tt>
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1569
     * @throws ArithmeticException {@code m <= 0}
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1570
     * @see    #modInverse
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1571
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1572
    public BigInteger modPow(BigInteger exponent, BigInteger m) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1573
        if (m.signum <= 0)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1574
            throw new ArithmeticException("BigInteger: modulus not positive");
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1575
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1576
        // Trivial cases
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1577
        if (exponent.signum == 0)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1578
            return (m.equals(ONE) ? ZERO : ONE);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1579
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1580
        if (this.equals(ONE))
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1581
            return (m.equals(ONE) ? ZERO : ONE);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1582
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1583
        if (this.equals(ZERO) && exponent.signum >= 0)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1584
            return ZERO;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1585
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1586
        if (this.equals(negConst[1]) && (!exponent.testBit(0)))
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1587
            return (m.equals(ONE) ? ZERO : ONE);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1588
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1589
        boolean invertResult;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1590
        if ((invertResult = (exponent.signum < 0)))
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1591
            exponent = exponent.negate();
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1592
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1593
        BigInteger base = (this.signum < 0 || this.compareTo(m) >= 0
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1594
                           ? this.mod(m) : this);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1595
        BigInteger result;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1596
        if (m.testBit(0)) { // odd modulus
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1597
            result = base.oddModPow(exponent, m);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1598
        } else {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1599
            /*
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1600
             * Even modulus.  Tear it into an "odd part" (m1) and power of two
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1601
             * (m2), exponentiate mod m1, manually exponentiate mod m2, and
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1602
             * use Chinese Remainder Theorem to combine results.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1603
             */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1604
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1605
            // Tear m apart into odd part (m1) and power of 2 (m2)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1606
            int p = m.getLowestSetBit();   // Max pow of 2 that divides m
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1607
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1608
            BigInteger m1 = m.shiftRight(p);  // m/2**p
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1609
            BigInteger m2 = ONE.shiftLeft(p); // 2**p
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1610
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1611
            // Calculate new base from m1
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1612
            BigInteger base2 = (this.signum < 0 || this.compareTo(m1) >= 0
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1613
                                ? this.mod(m1) : this);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1614
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1615
            // Caculate (base ** exponent) mod m1.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1616
            BigInteger a1 = (m1.equals(ONE) ? ZERO :
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1617
                             base2.oddModPow(exponent, m1));
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1618
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1619
            // Calculate (this ** exponent) mod m2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1620
            BigInteger a2 = base.modPow2(exponent, p);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1621
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1622
            // Combine results using Chinese Remainder Theorem
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1623
            BigInteger y1 = m2.modInverse(m1);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1624
            BigInteger y2 = m1.modInverse(m2);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1625
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1626
            result = a1.multiply(m2).multiply(y1).add
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1627
                     (a2.multiply(m1).multiply(y2)).mod(m);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1628
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1629
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1630
        return (invertResult ? result.modInverse(m) : result);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1631
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1632
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1633
    static int[] bnExpModThreshTable = {7, 25, 81, 241, 673, 1793,
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1634
                                                Integer.MAX_VALUE}; // Sentinel
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1635
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1636
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1637
     * Returns a BigInteger whose value is x to the power of y mod z.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1638
     * Assumes: z is odd && x < z.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1639
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1640
    private BigInteger oddModPow(BigInteger y, BigInteger z) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1641
    /*
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1642
     * The algorithm is adapted from Colin Plumb's C library.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1643
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1644
     * The window algorithm:
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1645
     * The idea is to keep a running product of b1 = n^(high-order bits of exp)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1646
     * and then keep appending exponent bits to it.  The following patterns
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1647
     * apply to a 3-bit window (k = 3):
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1648
     * To append   0: square
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1649
     * To append   1: square, multiply by n^1
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1650
     * To append  10: square, multiply by n^1, square
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1651
     * To append  11: square, square, multiply by n^3
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1652
     * To append 100: square, multiply by n^1, square, square
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1653
     * To append 101: square, square, square, multiply by n^5
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1654
     * To append 110: square, square, multiply by n^3, square
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1655
     * To append 111: square, square, square, multiply by n^7
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1656
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1657
     * Since each pattern involves only one multiply, the longer the pattern
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1658
     * the better, except that a 0 (no multiplies) can be appended directly.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1659
     * We precompute a table of odd powers of n, up to 2^k, and can then
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1660
     * multiply k bits of exponent at a time.  Actually, assuming random
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1661
     * exponents, there is on average one zero bit between needs to
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1662
     * multiply (1/2 of the time there's none, 1/4 of the time there's 1,
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1663
     * 1/8 of the time, there's 2, 1/32 of the time, there's 3, etc.), so
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1664
     * you have to do one multiply per k+1 bits of exponent.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1665
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1666
     * The loop walks down the exponent, squaring the result buffer as
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1667
     * it goes.  There is a wbits+1 bit lookahead buffer, buf, that is
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1668
     * filled with the upcoming exponent bits.  (What is read after the
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1669
     * end of the exponent is unimportant, but it is filled with zero here.)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1670
     * When the most-significant bit of this buffer becomes set, i.e.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1671
     * (buf & tblmask) != 0, we have to decide what pattern to multiply
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1672
     * by, and when to do it.  We decide, remember to do it in future
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1673
     * after a suitable number of squarings have passed (e.g. a pattern
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1674
     * of "100" in the buffer requires that we multiply by n^1 immediately;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1675
     * a pattern of "110" calls for multiplying by n^3 after one more
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1676
     * squaring), clear the buffer, and continue.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1677
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1678
     * When we start, there is one more optimization: the result buffer
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1679
     * is implcitly one, so squaring it or multiplying by it can be
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1680
     * optimized away.  Further, if we start with a pattern like "100"
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1681
     * in the lookahead window, rather than placing n into the buffer
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1682
     * and then starting to square it, we have already computed n^2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1683
     * to compute the odd-powers table, so we can place that into
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1684
     * the buffer and save a squaring.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1685
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1686
     * This means that if you have a k-bit window, to compute n^z,
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1687
     * where z is the high k bits of the exponent, 1/2 of the time
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1688
     * it requires no squarings.  1/4 of the time, it requires 1
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1689
     * squaring, ... 1/2^(k-1) of the time, it reqires k-2 squarings.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1690
     * And the remaining 1/2^(k-1) of the time, the top k bits are a
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1691
     * 1 followed by k-1 0 bits, so it again only requires k-2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1692
     * squarings, not k-1.  The average of these is 1.  Add that
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1693
     * to the one squaring we have to do to compute the table,
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1694
     * and you'll see that a k-bit window saves k-2 squarings
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1695
     * as well as reducing the multiplies.  (It actually doesn't
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1696
     * hurt in the case k = 1, either.)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1697
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1698
        // Special case for exponent of one
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1699
        if (y.equals(ONE))
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1700
            return this;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1701
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1702
        // Special case for base of zero
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1703
        if (signum==0)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1704
            return ZERO;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1705
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1706
        int[] base = mag.clone();
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1707
        int[] exp = y.mag;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1708
        int[] mod = z.mag;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1709
        int modLen = mod.length;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1710
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1711
        // Select an appropriate window size
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1712
        int wbits = 0;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1713
        int ebits = bitLength(exp, exp.length);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1714
        // if exponent is 65537 (0x10001), use minimum window size
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1715
        if ((ebits != 17) || (exp[0] != 65537)) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1716
            while (ebits > bnExpModThreshTable[wbits]) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1717
                wbits++;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1718
            }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1719
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1720
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1721
        // Calculate appropriate table size
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1722
        int tblmask = 1 << wbits;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1723
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1724
        // Allocate table for precomputed odd powers of base in Montgomery form
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1725
        int[][] table = new int[tblmask][];
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1726
        for (int i=0; i<tblmask; i++)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1727
            table[i] = new int[modLen];
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1728
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1729
        // Compute the modular inverse
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1730
        int inv = -MutableBigInteger.inverseMod32(mod[modLen-1]);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1731
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1732
        // Convert base to Montgomery form
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1733
        int[] a = leftShift(base, base.length, modLen << 5);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1734
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1735
        MutableBigInteger q = new MutableBigInteger(),
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1736
                          a2 = new MutableBigInteger(a),
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1737
                          b2 = new MutableBigInteger(mod);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1738
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  1739
        MutableBigInteger r= a2.divide(b2, q);
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1740
        table[0] = r.toIntArray();
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1741
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1742
        // Pad table[0] with leading zeros so its length is at least modLen
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1743
        if (table[0].length < modLen) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1744
           int offset = modLen - table[0].length;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1745
           int[] t2 = new int[modLen];
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1746
           for (int i=0; i<table[0].length; i++)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1747
               t2[i+offset] = table[0][i];
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1748
           table[0] = t2;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1749
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1750
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1751
        // Set b to the square of the base
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1752
        int[] b = squareToLen(table[0], modLen, null);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1753
        b = montReduce(b, mod, modLen, inv);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1754
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1755
        // Set t to high half of b
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1756
        int[] t = new int[modLen];
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1757
        for(int i=0; i<modLen; i++)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1758
            t[i] = b[i];
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1759
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1760
        // Fill in the table with odd powers of the base
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1761
        for (int i=1; i<tblmask; i++) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1762
            int[] prod = multiplyToLen(t, modLen, table[i-1], modLen, null);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1763
            table[i] = montReduce(prod, mod, modLen, inv);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1764
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1765
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1766
        // Pre load the window that slides over the exponent
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1767
        int bitpos = 1 << ((ebits-1) & (32-1));
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1768
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1769
        int buf = 0;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1770
        int elen = exp.length;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1771
        int eIndex = 0;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1772
        for (int i = 0; i <= wbits; i++) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1773
            buf = (buf << 1) | (((exp[eIndex] & bitpos) != 0)?1:0);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1774
            bitpos >>>= 1;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1775
            if (bitpos == 0) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1776
                eIndex++;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1777
                bitpos = 1 << (32-1);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1778
                elen--;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1779
            }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1780
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1781
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1782
        int multpos = ebits;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1783
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1784
        // The first iteration, which is hoisted out of the main loop
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1785
        ebits--;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1786
        boolean isone = true;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1787
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1788
        multpos = ebits - wbits;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1789
        while ((buf & 1) == 0) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1790
            buf >>>= 1;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1791
            multpos++;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1792
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1793
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1794
        int[] mult = table[buf >>> 1];
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1795
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1796
        buf = 0;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1797
        if (multpos == ebits)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1798
            isone = false;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1799
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1800
        // The main loop
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1801
        while(true) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1802
            ebits--;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1803
            // Advance the window
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1804
            buf <<= 1;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1805
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1806
            if (elen != 0) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1807
                buf |= ((exp[eIndex] & bitpos) != 0) ? 1 : 0;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1808
                bitpos >>>= 1;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1809
                if (bitpos == 0) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1810
                    eIndex++;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1811
                    bitpos = 1 << (32-1);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1812
                    elen--;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1813
                }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1814
            }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1815
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1816
            // Examine the window for pending multiplies
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1817
            if ((buf & tblmask) != 0) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1818
                multpos = ebits - wbits;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1819
                while ((buf & 1) == 0) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1820
                    buf >>>= 1;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1821
                    multpos++;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1822
                }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1823
                mult = table[buf >>> 1];
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1824
                buf = 0;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1825
            }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1826
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1827
            // Perform multiply
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1828
            if (ebits == multpos) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1829
                if (isone) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1830
                    b = mult.clone();
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1831
                    isone = false;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1832
                } else {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1833
                    t = b;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1834
                    a = multiplyToLen(t, modLen, mult, modLen, a);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1835
                    a = montReduce(a, mod, modLen, inv);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1836
                    t = a; a = b; b = t;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1837
                }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1838
            }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1839
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1840
            // Check if done
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1841
            if (ebits == 0)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1842
                break;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1843
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1844
            // Square the input
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1845
            if (!isone) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1846
                t = b;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1847
                a = squareToLen(t, modLen, a);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1848
                a = montReduce(a, mod, modLen, inv);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1849
                t = a; a = b; b = t;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1850
            }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1851
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1852
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1853
        // Convert result out of Montgomery form and return
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1854
        int[] t2 = new int[2*modLen];
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1855
        for(int i=0; i<modLen; i++)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1856
            t2[i+modLen] = b[i];
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1857
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1858
        b = montReduce(t2, mod, modLen, inv);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1859
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1860
        t2 = new int[modLen];
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1861
        for(int i=0; i<modLen; i++)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1862
            t2[i] = b[i];
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1863
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1864
        return new BigInteger(1, t2);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1865
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1866
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1867
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1868
     * Montgomery reduce n, modulo mod.  This reduces modulo mod and divides
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1869
     * by 2^(32*mlen). Adapted from Colin Plumb's C library.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1870
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1871
    private static int[] montReduce(int[] n, int[] mod, int mlen, int inv) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1872
        int c=0;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1873
        int len = mlen;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1874
        int offset=0;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1875
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1876
        do {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1877
            int nEnd = n[n.length-1-offset];
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1878
            int carry = mulAdd(n, mod, offset, mlen, inv * nEnd);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1879
            c += addOne(n, offset, mlen, carry);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1880
            offset++;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1881
        } while(--len > 0);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1882
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1883
        while(c>0)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1884
            c += subN(n, mod, mlen);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1885
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1886
        while (intArrayCmpToLen(n, mod, mlen) >= 0)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1887
            subN(n, mod, mlen);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1888
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1889
        return n;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1890
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1891
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1892
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1893
    /*
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1894
     * Returns -1, 0 or +1 as big-endian unsigned int array arg1 is less than,
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1895
     * equal to, or greater than arg2 up to length len.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1896
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1897
    private static int intArrayCmpToLen(int[] arg1, int[] arg2, int len) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1898
        for (int i=0; i<len; i++) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1899
            long b1 = arg1[i] & LONG_MASK;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1900
            long b2 = arg2[i] & LONG_MASK;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1901
            if (b1 < b2)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1902
                return -1;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1903
            if (b1 > b2)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1904
                return 1;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1905
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1906
        return 0;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1907
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1908
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1909
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1910
     * Subtracts two numbers of same length, returning borrow.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1911
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1912
    private static int subN(int[] a, int[] b, int len) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1913
        long sum = 0;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1914
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1915
        while(--len >= 0) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1916
            sum = (a[len] & LONG_MASK) -
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1917
                 (b[len] & LONG_MASK) + (sum >> 32);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1918
            a[len] = (int)sum;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1919
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1920
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1921
        return (int)(sum >> 32);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1922
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1923
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1924
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1925
     * Multiply an array by one word k and add to result, return the carry
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1926
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1927
    static int mulAdd(int[] out, int[] in, int offset, int len, int k) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1928
        long kLong = k & LONG_MASK;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1929
        long carry = 0;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1930
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1931
        offset = out.length-offset - 1;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1932
        for (int j=len-1; j >= 0; j--) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1933
            long product = (in[j] & LONG_MASK) * kLong +
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1934
                           (out[offset] & LONG_MASK) + carry;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1935
            out[offset--] = (int)product;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1936
            carry = product >>> 32;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1937
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1938
        return (int)carry;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1939
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1940
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1941
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1942
     * Add one word to the number a mlen words into a. Return the resulting
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1943
     * carry.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1944
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1945
    static int addOne(int[] a, int offset, int mlen, int carry) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1946
        offset = a.length-1-mlen-offset;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1947
        long t = (a[offset] & LONG_MASK) + (carry & LONG_MASK);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1948
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1949
        a[offset] = (int)t;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1950
        if ((t >>> 32) == 0)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1951
            return 0;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1952
        while (--mlen >= 0) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1953
            if (--offset < 0) { // Carry out of number
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1954
                return 1;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1955
            } else {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1956
                a[offset]++;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1957
                if (a[offset] != 0)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1958
                    return 0;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1959
            }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1960
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1961
        return 1;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1962
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1963
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1964
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1965
     * Returns a BigInteger whose value is (this ** exponent) mod (2**p)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1966
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1967
    private BigInteger modPow2(BigInteger exponent, int p) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1968
        /*
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1969
         * Perform exponentiation using repeated squaring trick, chopping off
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1970
         * high order bits as indicated by modulus.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1971
         */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1972
        BigInteger result = valueOf(1);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1973
        BigInteger baseToPow2 = this.mod2(p);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1974
        int expOffset = 0;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1975
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1976
        int limit = exponent.bitLength();
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1977
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1978
        if (this.testBit(0))
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1979
           limit = (p-1) < limit ? (p-1) : limit;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1980
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1981
        while (expOffset < limit) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1982
            if (exponent.testBit(expOffset))
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1983
                result = result.multiply(baseToPow2).mod2(p);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1984
            expOffset++;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1985
            if (expOffset < limit)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1986
                baseToPow2 = baseToPow2.square().mod2(p);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1987
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1988
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1989
        return result;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1990
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1991
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1992
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1993
     * Returns a BigInteger whose value is this mod(2**p).
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1994
     * Assumes that this {@code BigInteger >= 0} and {@code p > 0}.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1995
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1996
    private BigInteger mod2(int p) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1997
        if (bitLength() <= p)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1998
            return this;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1999
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2000
        // Copy remaining ints of mag
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  2001
        int numInts = (p + 31) >>> 5;
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2002
        int[] mag = new int[numInts];
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2003
        for (int i=0; i<numInts; i++)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2004
            mag[i] = this.mag[i + (this.mag.length - numInts)];
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2005
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2006
        // Mask out any excess bits
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2007
        int excessBits = (numInts << 5) - p;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2008
        mag[0] &= (1L << (32-excessBits)) - 1;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2009
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2010
        return (mag[0]==0 ? new BigInteger(1, mag) : new BigInteger(mag, 1));
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2011
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2012
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2013
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2014
     * Returns a BigInteger whose value is {@code (this}<sup>-1</sup> {@code mod m)}.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2015
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2016
     * @param  m the modulus.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2017
     * @return {@code this}<sup>-1</sup> {@code mod m}.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2018
     * @throws ArithmeticException {@code  m <= 0}, or this BigInteger
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2019
     *         has no multiplicative inverse mod m (that is, this BigInteger
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2020
     *         is not <i>relatively prime</i> to m).
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2021
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2022
    public BigInteger modInverse(BigInteger m) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2023
        if (m.signum != 1)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2024
            throw new ArithmeticException("BigInteger: modulus not positive");
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2025
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2026
        if (m.equals(ONE))
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2027
            return ZERO;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2028
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2029
        // Calculate (this mod m)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2030
        BigInteger modVal = this;
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  2031
        if (signum < 0 || (this.compareMagnitude(m) >= 0))
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2032
            modVal = this.mod(m);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2033
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2034
        if (modVal.equals(ONE))
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2035
            return ONE;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2036
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2037
        MutableBigInteger a = new MutableBigInteger(modVal);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2038
        MutableBigInteger b = new MutableBigInteger(m);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2039
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2040
        MutableBigInteger result = a.mutableModInverse(b);
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  2041
        return result.toBigInteger(1);
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2042
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2043
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2044
    // Shift Operations
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2045
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2046
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2047
     * Returns a BigInteger whose value is {@code (this << n)}.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2048
     * The shift distance, {@code n}, may be negative, in which case
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2049
     * this method performs a right shift.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2050
     * (Computes <tt>floor(this * 2<sup>n</sup>)</tt>.)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2051
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2052
     * @param  n shift distance, in bits.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2053
     * @return {@code this << n}
4151
db7d59c0b0e6 6371401: java.math.BigInteger.shift(Integer.MIN_VALUE) throws StackOverflowError
darcy
parents: 2922
diff changeset
  2054
     * @throws ArithmeticException if the shift distance is {@code
db7d59c0b0e6 6371401: java.math.BigInteger.shift(Integer.MIN_VALUE) throws StackOverflowError
darcy
parents: 2922
diff changeset
  2055
     *         Integer.MIN_VALUE}.
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2056
     * @see #shiftRight
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2057
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2058
    public BigInteger shiftLeft(int n) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2059
        if (signum == 0)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2060
            return ZERO;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2061
        if (n==0)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2062
            return this;
4151
db7d59c0b0e6 6371401: java.math.BigInteger.shift(Integer.MIN_VALUE) throws StackOverflowError
darcy
parents: 2922
diff changeset
  2063
        if (n<0) {
db7d59c0b0e6 6371401: java.math.BigInteger.shift(Integer.MIN_VALUE) throws StackOverflowError
darcy
parents: 2922
diff changeset
  2064
            if (n == Integer.MIN_VALUE) {
db7d59c0b0e6 6371401: java.math.BigInteger.shift(Integer.MIN_VALUE) throws StackOverflowError
darcy
parents: 2922
diff changeset
  2065
                throw new ArithmeticException("Shift distance of Integer.MIN_VALUE not supported.");
db7d59c0b0e6 6371401: java.math.BigInteger.shift(Integer.MIN_VALUE) throws StackOverflowError
darcy
parents: 2922
diff changeset
  2066
            } else {
db7d59c0b0e6 6371401: java.math.BigInteger.shift(Integer.MIN_VALUE) throws StackOverflowError
darcy
parents: 2922
diff changeset
  2067
                return shiftRight(-n);
db7d59c0b0e6 6371401: java.math.BigInteger.shift(Integer.MIN_VALUE) throws StackOverflowError
darcy
parents: 2922
diff changeset
  2068
            }
db7d59c0b0e6 6371401: java.math.BigInteger.shift(Integer.MIN_VALUE) throws StackOverflowError
darcy
parents: 2922
diff changeset
  2069
        }
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2070
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2071
        int nInts = n >>> 5;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2072
        int nBits = n & 0x1f;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2073
        int magLen = mag.length;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2074
        int newMag[] = null;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2075
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2076
        if (nBits == 0) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2077
            newMag = new int[magLen + nInts];
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2078
            for (int i=0; i<magLen; i++)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2079
                newMag[i] = mag[i];
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2080
        } else {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2081
            int i = 0;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2082
            int nBits2 = 32 - nBits;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2083
            int highBits = mag[0] >>> nBits2;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2084
            if (highBits != 0) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2085
                newMag = new int[magLen + nInts + 1];
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2086
                newMag[i++] = highBits;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2087
            } else {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2088
                newMag = new int[magLen + nInts];
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2089
            }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2090
            int j=0;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2091
            while (j < magLen-1)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2092
                newMag[i++] = mag[j++] << nBits | mag[j] >>> nBits2;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2093
            newMag[i] = mag[j] << nBits;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2094
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2095
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2096
        return new BigInteger(newMag, signum);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2097
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2098
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2099
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2100
     * Returns a BigInteger whose value is {@code (this >> n)}.  Sign
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2101
     * extension is performed.  The shift distance, {@code n}, may be
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2102
     * negative, in which case this method performs a left shift.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2103
     * (Computes <tt>floor(this / 2<sup>n</sup>)</tt>.)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2104
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2105
     * @param  n shift distance, in bits.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2106
     * @return {@code this >> n}
4151
db7d59c0b0e6 6371401: java.math.BigInteger.shift(Integer.MIN_VALUE) throws StackOverflowError
darcy
parents: 2922
diff changeset
  2107
     * @throws ArithmeticException if the shift distance is {@code
db7d59c0b0e6 6371401: java.math.BigInteger.shift(Integer.MIN_VALUE) throws StackOverflowError
darcy
parents: 2922
diff changeset
  2108
     *         Integer.MIN_VALUE}.
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2109
     * @see #shiftLeft
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2110
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2111
    public BigInteger shiftRight(int n) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2112
        if (n==0)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2113
            return this;
4151
db7d59c0b0e6 6371401: java.math.BigInteger.shift(Integer.MIN_VALUE) throws StackOverflowError
darcy
parents: 2922
diff changeset
  2114
        if (n<0) {
db7d59c0b0e6 6371401: java.math.BigInteger.shift(Integer.MIN_VALUE) throws StackOverflowError
darcy
parents: 2922
diff changeset
  2115
            if (n == Integer.MIN_VALUE) {
db7d59c0b0e6 6371401: java.math.BigInteger.shift(Integer.MIN_VALUE) throws StackOverflowError
darcy
parents: 2922
diff changeset
  2116
                throw new ArithmeticException("Shift distance of Integer.MIN_VALUE not supported.");
db7d59c0b0e6 6371401: java.math.BigInteger.shift(Integer.MIN_VALUE) throws StackOverflowError
darcy
parents: 2922
diff changeset
  2117
            } else {
db7d59c0b0e6 6371401: java.math.BigInteger.shift(Integer.MIN_VALUE) throws StackOverflowError
darcy
parents: 2922
diff changeset
  2118
                return shiftLeft(-n);
db7d59c0b0e6 6371401: java.math.BigInteger.shift(Integer.MIN_VALUE) throws StackOverflowError
darcy
parents: 2922
diff changeset
  2119
            }
db7d59c0b0e6 6371401: java.math.BigInteger.shift(Integer.MIN_VALUE) throws StackOverflowError
darcy
parents: 2922
diff changeset
  2120
        }
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2121
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2122
        int nInts = n >>> 5;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2123
        int nBits = n & 0x1f;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2124
        int magLen = mag.length;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2125
        int newMag[] = null;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2126
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2127
        // Special case: entire contents shifted off the end
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2128
        if (nInts >= magLen)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2129
            return (signum >= 0 ? ZERO : negConst[1]);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2130
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2131
        if (nBits == 0) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2132
            int newMagLen = magLen - nInts;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2133
            newMag = new int[newMagLen];
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2134
            for (int i=0; i<newMagLen; i++)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2135
                newMag[i] = mag[i];
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2136
        } else {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2137
            int i = 0;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2138
            int highBits = mag[0] >>> nBits;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2139
            if (highBits != 0) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2140
                newMag = new int[magLen - nInts];
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2141
                newMag[i++] = highBits;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2142
            } else {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2143
                newMag = new int[magLen - nInts -1];
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2144
            }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2145
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2146
            int nBits2 = 32 - nBits;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2147
            int j=0;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2148
            while (j < magLen - nInts - 1)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2149
                newMag[i++] = (mag[j++] << nBits2) | (mag[j] >>> nBits);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2150
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2151
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2152
        if (signum < 0) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2153
            // Find out whether any one-bits were shifted off the end.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2154
            boolean onesLost = false;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2155
            for (int i=magLen-1, j=magLen-nInts; i>=j && !onesLost; i--)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2156
                onesLost = (mag[i] != 0);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2157
            if (!onesLost && nBits != 0)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2158
                onesLost = (mag[magLen - nInts - 1] << (32 - nBits) != 0);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2159
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2160
            if (onesLost)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2161
                newMag = javaIncrement(newMag);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2162
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2163
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2164
        return new BigInteger(newMag, signum);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2165
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2166
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2167
    int[] javaIncrement(int[] val) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2168
        int lastSum = 0;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2169
        for (int i=val.length-1;  i >= 0 && lastSum == 0; i--)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2170
            lastSum = (val[i] += 1);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2171
        if (lastSum == 0) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2172
            val = new int[val.length+1];
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2173
            val[0] = 1;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2174
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2175
        return val;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2176
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2177
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2178
    // Bitwise Operations
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2179
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2180
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2181
     * Returns a BigInteger whose value is {@code (this & val)}.  (This
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2182
     * method returns a negative BigInteger if and only if this and val are
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2183
     * both negative.)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2184
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2185
     * @param val value to be AND'ed with this BigInteger.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2186
     * @return {@code this & val}
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2187
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2188
    public BigInteger and(BigInteger val) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2189
        int[] result = new int[Math.max(intLength(), val.intLength())];
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2190
        for (int i=0; i<result.length; i++)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2191
            result[i] = (getInt(result.length-i-1)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2192
                         & val.getInt(result.length-i-1));
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2193
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2194
        return valueOf(result);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2195
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2196
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2197
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2198
     * Returns a BigInteger whose value is {@code (this | val)}.  (This method
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2199
     * returns a negative BigInteger if and only if either this or val is
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2200
     * negative.)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2201
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2202
     * @param val value to be OR'ed with this BigInteger.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2203
     * @return {@code this | val}
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2204
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2205
    public BigInteger or(BigInteger val) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2206
        int[] result = new int[Math.max(intLength(), val.intLength())];
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2207
        for (int i=0; i<result.length; i++)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2208
            result[i] = (getInt(result.length-i-1)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2209
                         | val.getInt(result.length-i-1));
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2210
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2211
        return valueOf(result);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2212
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2213
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2214
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2215
     * Returns a BigInteger whose value is {@code (this ^ val)}.  (This method
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2216
     * returns a negative BigInteger if and only if exactly one of this and
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2217
     * val are negative.)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2218
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2219
     * @param val value to be XOR'ed with this BigInteger.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2220
     * @return {@code this ^ val}
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2221
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2222
    public BigInteger xor(BigInteger val) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2223
        int[] result = new int[Math.max(intLength(), val.intLength())];
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2224
        for (int i=0; i<result.length; i++)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2225
            result[i] = (getInt(result.length-i-1)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2226
                         ^ val.getInt(result.length-i-1));
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2227
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2228
        return valueOf(result);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2229
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2230
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2231
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2232
     * Returns a BigInteger whose value is {@code (~this)}.  (This method
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2233
     * returns a negative value if and only if this BigInteger is
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2234
     * non-negative.)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2235
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2236
     * @return {@code ~this}
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2237
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2238
    public BigInteger not() {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2239
        int[] result = new int[intLength()];
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2240
        for (int i=0; i<result.length; i++)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2241
            result[i] = ~getInt(result.length-i-1);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2242
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2243
        return valueOf(result);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2244
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2245
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2246
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2247
     * Returns a BigInteger whose value is {@code (this & ~val)}.  This
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2248
     * method, which is equivalent to {@code and(val.not())}, is provided as
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2249
     * a convenience for masking operations.  (This method returns a negative
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2250
     * BigInteger if and only if {@code this} is negative and {@code val} is
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2251
     * positive.)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2252
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2253
     * @param val value to be complemented and AND'ed with this BigInteger.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2254
     * @return {@code this & ~val}
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2255
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2256
    public BigInteger andNot(BigInteger val) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2257
        int[] result = new int[Math.max(intLength(), val.intLength())];
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2258
        for (int i=0; i<result.length; i++)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2259
            result[i] = (getInt(result.length-i-1)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2260
                         & ~val.getInt(result.length-i-1));
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2261
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2262
        return valueOf(result);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2263
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2264
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2265
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2266
    // Single Bit Operations
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2267
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2268
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2269
     * Returns {@code true} if and only if the designated bit is set.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2270
     * (Computes {@code ((this & (1<<n)) != 0)}.)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2271
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2272
     * @param  n index of bit to test.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2273
     * @return {@code true} if and only if the designated bit is set.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2274
     * @throws ArithmeticException {@code n} is negative.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2275
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2276
    public boolean testBit(int n) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2277
        if (n<0)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2278
            throw new ArithmeticException("Negative bit address");
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2279
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  2280
        return (getInt(n >>> 5) & (1 << (n & 31))) != 0;
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2281
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2282
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2283
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2284
     * Returns a BigInteger whose value is equivalent to this BigInteger
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2285
     * with the designated bit set.  (Computes {@code (this | (1<<n))}.)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2286
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2287
     * @param  n index of bit to set.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2288
     * @return {@code this | (1<<n)}
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2289
     * @throws ArithmeticException {@code n} is negative.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2290
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2291
    public BigInteger setBit(int n) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2292
        if (n<0)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2293
            throw new ArithmeticException("Negative bit address");
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2294
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  2295
        int intNum = n >>> 5;
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2296
        int[] result = new int[Math.max(intLength(), intNum+2)];
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2297
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2298
        for (int i=0; i<result.length; i++)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2299
            result[result.length-i-1] = getInt(i);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2300
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  2301
        result[result.length-intNum-1] |= (1 << (n & 31));
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2302
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2303
        return valueOf(result);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2304
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2305
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2306
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2307
     * Returns a BigInteger whose value is equivalent to this BigInteger
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2308
     * with the designated bit cleared.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2309
     * (Computes {@code (this & ~(1<<n))}.)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2310
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2311
     * @param  n index of bit to clear.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2312
     * @return {@code this & ~(1<<n)}
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2313
     * @throws ArithmeticException {@code n} is negative.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2314
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2315
    public BigInteger clearBit(int n) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2316
        if (n<0)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2317
            throw new ArithmeticException("Negative bit address");
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2318
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  2319
        int intNum = n >>> 5;
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  2320
        int[] result = new int[Math.max(intLength(), ((n + 1) >>> 5) + 1)];
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2321
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2322
        for (int i=0; i<result.length; i++)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2323
            result[result.length-i-1] = getInt(i);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2324
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  2325
        result[result.length-intNum-1] &= ~(1 << (n & 31));
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2326
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2327
        return valueOf(result);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2328
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2329
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2330
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2331
     * Returns a BigInteger whose value is equivalent to this BigInteger
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2332
     * with the designated bit flipped.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2333
     * (Computes {@code (this ^ (1<<n))}.)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2334
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2335
     * @param  n index of bit to flip.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2336
     * @return {@code this ^ (1<<n)}
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2337
     * @throws ArithmeticException {@code n} is negative.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2338
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2339
    public BigInteger flipBit(int n) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2340
        if (n<0)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2341
            throw new ArithmeticException("Negative bit address");
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2342
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  2343
        int intNum = n >>> 5;
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2344
        int[] result = new int[Math.max(intLength(), intNum+2)];
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2345
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2346
        for (int i=0; i<result.length; i++)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2347
            result[result.length-i-1] = getInt(i);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2348
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  2349
        result[result.length-intNum-1] ^= (1 << (n & 31));
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2350
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2351
        return valueOf(result);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2352
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2353
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2354
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2355
     * Returns the index of the rightmost (lowest-order) one bit in this
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2356
     * BigInteger (the number of zero bits to the right of the rightmost
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2357
     * one bit).  Returns -1 if this BigInteger contains no one bits.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2358
     * (Computes {@code (this==0? -1 : log2(this & -this))}.)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2359
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2360
     * @return index of the rightmost one bit in this BigInteger.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2361
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2362
    public int getLowestSetBit() {
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  2363
        @SuppressWarnings("deprecation") int lsb = lowestSetBit - 2;
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  2364
        if (lsb == -2) {  // lowestSetBit not initialized yet
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  2365
            lsb = 0;
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2366
            if (signum == 0) {
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  2367
                lsb -= 1;
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2368
            } else {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2369
                // Search for lowest order nonzero int
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2370
                int i,b;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2371
                for (i=0; (b = getInt(i))==0; i++)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2372
                    ;
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  2373
                lsb += (i << 5) + Integer.numberOfTrailingZeros(b);
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2374
            }
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  2375
            lowestSetBit = lsb + 2;
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2376
        }
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  2377
        return lsb;
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2378
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2379
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2380
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2381
    // Miscellaneous Bit Operations
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2382
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2383
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2384
     * Returns the number of bits in the minimal two's-complement
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2385
     * representation of this BigInteger, <i>excluding</i> a sign bit.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2386
     * For positive BigIntegers, this is equivalent to the number of bits in
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2387
     * the ordinary binary representation.  (Computes
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2388
     * {@code (ceil(log2(this < 0 ? -this : this+1)))}.)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2389
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2390
     * @return number of bits in the minimal two's-complement
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2391
     *         representation of this BigInteger, <i>excluding</i> a sign bit.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2392
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2393
    public int bitLength() {
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  2394
        @SuppressWarnings("deprecation") int n = bitLength - 1;
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  2395
        if (n == -1) { // bitLength not initialized yet
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  2396
            int[] m = mag;
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  2397
            int len = m.length;
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  2398
            if (len == 0) {
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  2399
                n = 0; // offset by one to initialize
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  2400
            }  else {
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2401
                // Calculate the bit length of the magnitude
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  2402
                int magBitLength = ((len - 1) << 5) + bitLengthForInt(mag[0]);
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  2403
                 if (signum < 0) {
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  2404
                     // Check if magnitude is a power of two
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  2405
                     boolean pow2 = (Integer.bitCount(mag[0]) == 1);
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  2406
                     for(int i=1; i< len && pow2; i++)
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  2407
                         pow2 = (mag[i] == 0);
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  2408
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  2409
                     n = (pow2 ? magBitLength -1 : magBitLength);
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  2410
                 } else {
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  2411
                     n = magBitLength;
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  2412
                 }
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2413
            }
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  2414
            bitLength = n + 1;
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2415
        }
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  2416
        return n;
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2417
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2418
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2419
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2420
     * Returns the number of bits in the two's complement representation
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2421
     * of this BigInteger that differ from its sign bit.  This method is
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2422
     * useful when implementing bit-vector style sets atop BigIntegers.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2423
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2424
     * @return number of bits in the two's complement representation
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2425
     *         of this BigInteger that differ from its sign bit.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2426
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2427
    public int bitCount() {
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  2428
        @SuppressWarnings("deprecation") int bc = bitCount - 1;
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  2429
        if (bc == -1) {  // bitCount not initialized yet
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  2430
            bc = 0;      // offset by one to initialize
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2431
            // Count the bits in the magnitude
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2432
            for (int i=0; i<mag.length; i++)
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  2433
                bc += Integer.bitCount(mag[i]);
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2434
            if (signum < 0) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2435
                // Count the trailing zeros in the magnitude
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2436
                int magTrailingZeroCount = 0, j;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2437
                for (j=mag.length-1; mag[j]==0; j--)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2438
                    magTrailingZeroCount += 32;
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  2439
                magTrailingZeroCount += Integer.numberOfTrailingZeros(mag[j]);
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  2440
                bc += magTrailingZeroCount - 1;
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2441
            }
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  2442
            bitCount = bc + 1;
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2443
        }
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  2444
        return bc;
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2445
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2446
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2447
    // Primality Testing
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2448
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2449
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2450
     * Returns {@code true} if this BigInteger is probably prime,
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2451
     * {@code false} if it's definitely composite.  If
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2452
     * {@code certainty} is {@code  <= 0}, {@code true} is
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2453
     * returned.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2454
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2455
     * @param  certainty a measure of the uncertainty that the caller is
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2456
     *         willing to tolerate: if the call returns {@code true}
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2457
     *         the probability that this BigInteger is prime exceeds
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2458
     *         (1 - 1/2<sup>{@code certainty}</sup>).  The execution time of
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2459
     *         this method is proportional to the value of this parameter.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2460
     * @return {@code true} if this BigInteger is probably prime,
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2461
     *         {@code false} if it's definitely composite.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2462
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2463
    public boolean isProbablePrime(int certainty) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2464
        if (certainty <= 0)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2465
            return true;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2466
        BigInteger w = this.abs();
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2467
        if (w.equals(TWO))
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2468
            return true;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2469
        if (!w.testBit(0) || w.equals(ONE))
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2470
            return false;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2471
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2472
        return w.primeToCertainty(certainty, null);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2473
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2474
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2475
    // Comparison Operations
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2476
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2477
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2478
     * Compares this BigInteger with the specified BigInteger.  This
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2479
     * method is provided in preference to individual methods for each
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2480
     * of the six boolean comparison operators ({@literal <}, ==,
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2481
     * {@literal >}, {@literal >=}, !=, {@literal <=}).  The suggested
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2482
     * idiom for performing these comparisons is: {@code
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2483
     * (x.compareTo(y)} &lt;<i>op</i>&gt; {@code 0)}, where
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2484
     * &lt;<i>op</i>&gt; is one of the six comparison operators.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2485
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2486
     * @param  val BigInteger to which this BigInteger is to be compared.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2487
     * @return -1, 0 or 1 as this BigInteger is numerically less than, equal
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2488
     *         to, or greater than {@code val}.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2489
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2490
    public int compareTo(BigInteger val) {
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  2491
        if (signum == val.signum) {
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  2492
            switch (signum) {
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  2493
            case 1:
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  2494
                return compareMagnitude(val);
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  2495
            case -1:
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  2496
                return val.compareMagnitude(this);
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  2497
            default:
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  2498
                return 0;
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  2499
            }
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  2500
        }
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  2501
        return signum > val.signum ? 1 : -1;
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2502
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2503
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  2504
    /**
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  2505
     * Compares the magnitude array of this BigInteger with the specified
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  2506
     * BigInteger's. This is the version of compareTo ignoring sign.
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  2507
     *
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  2508
     * @param val BigInteger whose magnitude array to be compared.
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  2509
     * @return -1, 0 or 1 as this magnitude array is less than, equal to or
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  2510
     *         greater than the magnitude aray for the specified BigInteger's.
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2511
     */
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  2512
    final int compareMagnitude(BigInteger val) {
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  2513
        int[] m1 = mag;
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  2514
        int len1 = m1.length;
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  2515
        int[] m2 = val.mag;
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  2516
        int len2 = m2.length;
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  2517
        if (len1 < len2)
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2518
            return -1;
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  2519
        if (len1 > len2)
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2520
            return 1;
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  2521
        for (int i = 0; i < len1; i++) {
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  2522
            int a = m1[i];
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  2523
            int b = m2[i];
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  2524
            if (a != b)
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  2525
                return ((a & LONG_MASK) < (b & LONG_MASK)) ? -1 : 1;
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2526
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2527
        return 0;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2528
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2529
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2530
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2531
     * Compares this BigInteger with the specified Object for equality.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2532
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2533
     * @param  x Object to which this BigInteger is to be compared.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2534
     * @return {@code true} if and only if the specified Object is a
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2535
     *         BigInteger whose value is numerically equal to this BigInteger.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2536
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2537
    public boolean equals(Object x) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2538
        // This test is just an optimization, which may or may not help
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2539
        if (x == this)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2540
            return true;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2541
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2542
        if (!(x instanceof BigInteger))
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2543
            return false;
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  2544
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2545
        BigInteger xInt = (BigInteger) x;
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  2546
        if (xInt.signum != signum)
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2547
            return false;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2548
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  2549
        int[] m = mag;
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  2550
        int len = m.length;
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  2551
        int[] xm = xInt.mag;
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  2552
        if (len != xm.length)
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  2553
            return false;
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  2554
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  2555
        for (int i = 0; i < len; i++)
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  2556
            if (xm[i] != m[i])
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2557
                return false;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2558
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2559
        return true;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2560
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2561
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2562
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2563
     * Returns the minimum of this BigInteger and {@code val}.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2564
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2565
     * @param  val value with which the minimum is to be computed.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2566
     * @return the BigInteger whose value is the lesser of this BigInteger and
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2567
     *         {@code val}.  If they are equal, either may be returned.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2568
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2569
    public BigInteger min(BigInteger val) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2570
        return (compareTo(val)<0 ? this : val);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2571
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2572
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2573
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2574
     * Returns the maximum of this BigInteger and {@code val}.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2575
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2576
     * @param  val value with which the maximum is to be computed.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2577
     * @return the BigInteger whose value is the greater of this and
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2578
     *         {@code val}.  If they are equal, either may be returned.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2579
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2580
    public BigInteger max(BigInteger val) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2581
        return (compareTo(val)>0 ? this : val);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2582
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2583
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2584
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2585
    // Hash Function
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2586
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2587
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2588
     * Returns the hash code for this BigInteger.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2589
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2590
     * @return hash code for this BigInteger.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2591
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2592
    public int hashCode() {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2593
        int hashCode = 0;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2594
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2595
        for (int i=0; i<mag.length; i++)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2596
            hashCode = (int)(31*hashCode + (mag[i] & LONG_MASK));
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2597
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2598
        return hashCode * signum;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2599
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2600
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2601
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2602
     * Returns the String representation of this BigInteger in the
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2603
     * given radix.  If the radix is outside the range from {@link
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2604
     * Character#MIN_RADIX} to {@link Character#MAX_RADIX} inclusive,
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2605
     * it will default to 10 (as is the case for
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2606
     * {@code Integer.toString}).  The digit-to-character mapping
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2607
     * provided by {@code Character.forDigit} is used, and a minus
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2608
     * sign is prepended if appropriate.  (This representation is
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2609
     * compatible with the {@link #BigInteger(String, int) (String,
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2610
     * int)} constructor.)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2611
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2612
     * @param  radix  radix of the String representation.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2613
     * @return String representation of this BigInteger in the given radix.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2614
     * @see    Integer#toString
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2615
     * @see    Character#forDigit
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2616
     * @see    #BigInteger(java.lang.String, int)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2617
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2618
    public String toString(int radix) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2619
        if (signum == 0)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2620
            return "0";
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2621
        if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2622
            radix = 10;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2623
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2624
        // Compute upper bound on number of digit groups and allocate space
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2625
        int maxNumDigitGroups = (4*mag.length + 6)/7;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2626
        String digitGroup[] = new String[maxNumDigitGroups];
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2627
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2628
        // Translate number to string, a digit group at a time
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2629
        BigInteger tmp = this.abs();
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2630
        int numGroups = 0;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2631
        while (tmp.signum != 0) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2632
            BigInteger d = longRadix[radix];
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2633
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2634
            MutableBigInteger q = new MutableBigInteger(),
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2635
                              a = new MutableBigInteger(tmp.mag),
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2636
                              b = new MutableBigInteger(d.mag);
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  2637
            MutableBigInteger r = a.divide(b, q);
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  2638
            BigInteger q2 = q.toBigInteger(tmp.signum * d.signum);
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  2639
            BigInteger r2 = r.toBigInteger(tmp.signum * d.signum);
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2640
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2641
            digitGroup[numGroups++] = Long.toString(r2.longValue(), radix);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2642
            tmp = q2;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2643
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2644
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2645
        // Put sign (if any) and first digit group into result buffer
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2646
        StringBuilder buf = new StringBuilder(numGroups*digitsPerLong[radix]+1);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2647
        if (signum<0)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2648
            buf.append('-');
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2649
        buf.append(digitGroup[numGroups-1]);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2650
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2651
        // Append remaining digit groups padded with leading zeros
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2652
        for (int i=numGroups-2; i>=0; i--) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2653
            // Prepend (any) leading zeros for this digit group
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2654
            int numLeadingZeros = digitsPerLong[radix]-digitGroup[i].length();
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2655
            if (numLeadingZeros != 0)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2656
                buf.append(zeros[numLeadingZeros]);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2657
            buf.append(digitGroup[i]);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2658
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2659
        return buf.toString();
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2660
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2661
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2662
    /* zero[i] is a string of i consecutive zeros. */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2663
    private static String zeros[] = new String[64];
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2664
    static {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2665
        zeros[63] =
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2666
            "000000000000000000000000000000000000000000000000000000000000000";
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2667
        for (int i=0; i<63; i++)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2668
            zeros[i] = zeros[63].substring(0, i);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2669
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2670
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2671
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2672
     * Returns the decimal String representation of this BigInteger.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2673
     * The digit-to-character mapping provided by
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2674
     * {@code Character.forDigit} is used, and a minus sign is
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2675
     * prepended if appropriate.  (This representation is compatible
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2676
     * with the {@link #BigInteger(String) (String)} constructor, and
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2677
     * allows for String concatenation with Java's + operator.)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2678
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2679
     * @return decimal String representation of this BigInteger.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2680
     * @see    Character#forDigit
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2681
     * @see    #BigInteger(java.lang.String)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2682
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2683
    public String toString() {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2684
        return toString(10);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2685
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2686
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2687
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2688
     * Returns a byte array containing the two's-complement
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2689
     * representation of this BigInteger.  The byte array will be in
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2690
     * <i>big-endian</i> byte-order: the most significant byte is in
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2691
     * the zeroth element.  The array will contain the minimum number
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2692
     * of bytes required to represent this BigInteger, including at
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2693
     * least one sign bit, which is {@code (ceil((this.bitLength() +
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2694
     * 1)/8))}.  (This representation is compatible with the
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2695
     * {@link #BigInteger(byte[]) (byte[])} constructor.)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2696
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2697
     * @return a byte array containing the two's-complement representation of
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2698
     *         this BigInteger.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2699
     * @see    #BigInteger(byte[])
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2700
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2701
    public byte[] toByteArray() {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2702
        int byteLen = bitLength()/8 + 1;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2703
        byte[] byteArray = new byte[byteLen];
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2704
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2705
        for (int i=byteLen-1, bytesCopied=4, nextInt=0, intIndex=0; i>=0; i--) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2706
            if (bytesCopied == 4) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2707
                nextInt = getInt(intIndex++);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2708
                bytesCopied = 1;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2709
            } else {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2710
                nextInt >>>= 8;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2711
                bytesCopied++;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2712
            }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2713
            byteArray[i] = (byte)nextInt;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2714
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2715
        return byteArray;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2716
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2717
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2718
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2719
     * Converts this BigInteger to an {@code int}.  This
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2720
     * conversion is analogous to a <a
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2721
     * href="http://java.sun.com/docs/books/jls/second_edition/html/conversions.doc.html#25363"><i>narrowing
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2722
     * primitive conversion</i></a> from {@code long} to
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2723
     * {@code int} as defined in the <a
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2724
     * href="http://java.sun.com/docs/books/jls/html/">Java Language
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2725
     * Specification</a>: if this BigInteger is too big to fit in an
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2726
     * {@code int}, only the low-order 32 bits are returned.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2727
     * Note that this conversion can lose information about the
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2728
     * overall magnitude of the BigInteger value as well as return a
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2729
     * result with the opposite sign.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2730
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2731
     * @return this BigInteger converted to an {@code int}.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2732
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2733
    public int intValue() {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2734
        int result = 0;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2735
        result = getInt(0);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2736
        return result;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2737
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2738
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2739
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2740
     * Converts this BigInteger to a {@code long}.  This
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2741
     * conversion is analogous to a <a
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2742
     * href="http://java.sun.com/docs/books/jls/second_edition/html/conversions.doc.html#25363"><i>narrowing
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2743
     * primitive conversion</i></a> from {@code long} to
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2744
     * {@code int} as defined in the <a
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2745
     * href="http://java.sun.com/docs/books/jls/html/">Java Language
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2746
     * Specification</a>: if this BigInteger is too big to fit in a
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2747
     * {@code long}, only the low-order 64 bits are returned.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2748
     * Note that this conversion can lose information about the
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2749
     * overall magnitude of the BigInteger value as well as return a
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2750
     * result with the opposite sign.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2751
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2752
     * @return this BigInteger converted to a {@code long}.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2753
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2754
    public long longValue() {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2755
        long result = 0;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2756
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2757
        for (int i=1; i>=0; i--)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2758
            result = (result << 32) + (getInt(i) & LONG_MASK);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2759
        return result;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2760
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2761
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2762
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2763
     * Converts this BigInteger to a {@code float}.  This
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2764
     * conversion is similar to the <a
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2765
     * href="http://java.sun.com/docs/books/jls/second_edition/html/conversions.doc.html#25363"><i>narrowing
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2766
     * primitive conversion</i></a> from {@code double} to
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2767
     * {@code float} defined in the <a
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2768
     * href="http://java.sun.com/docs/books/jls/html/">Java Language
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2769
     * Specification</a>: if this BigInteger has too great a magnitude
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2770
     * to represent as a {@code float}, it will be converted to
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2771
     * {@link Float#NEGATIVE_INFINITY} or {@link
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2772
     * Float#POSITIVE_INFINITY} as appropriate.  Note that even when
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2773
     * the return value is finite, this conversion can lose
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2774
     * information about the precision of the BigInteger value.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2775
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2776
     * @return this BigInteger converted to a {@code float}.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2777
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2778
    public float floatValue() {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2779
        // Somewhat inefficient, but guaranteed to work.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2780
        return Float.parseFloat(this.toString());
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2781
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2782
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2783
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2784
     * Converts this BigInteger to a {@code double}.  This
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2785
     * conversion is similar to the <a
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2786
     * href="http://java.sun.com/docs/books/jls/second_edition/html/conversions.doc.html#25363"><i>narrowing
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2787
     * primitive conversion</i></a> from {@code double} to
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2788
     * {@code float} defined in the <a
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2789
     * href="http://java.sun.com/docs/books/jls/html/">Java Language
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2790
     * Specification</a>: if this BigInteger has too great a magnitude
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2791
     * to represent as a {@code double}, it will be converted to
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2792
     * {@link Double#NEGATIVE_INFINITY} or {@link
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2793
     * Double#POSITIVE_INFINITY} as appropriate.  Note that even when
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2794
     * the return value is finite, this conversion can lose
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2795
     * information about the precision of the BigInteger value.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2796
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2797
     * @return this BigInteger converted to a {@code double}.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2798
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2799
    public double doubleValue() {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2800
        // Somewhat inefficient, but guaranteed to work.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2801
        return Double.parseDouble(this.toString());
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2802
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2803
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2804
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2805
     * Returns a copy of the input array stripped of any leading zero bytes.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2806
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2807
    private static int[] stripLeadingZeroInts(int val[]) {
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  2808
        int vlen = val.length;
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2809
        int keep;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2810
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2811
        // Find first nonzero byte
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  2812
        for (keep = 0; keep < vlen && val[keep] == 0; keep++)
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2813
            ;
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  2814
        return java.util.Arrays.copyOfRange(val, keep, vlen);
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2815
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2816
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2817
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2818
     * Returns the input array stripped of any leading zero bytes.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2819
     * Since the source is trusted the copying may be skipped.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2820
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2821
    private static int[] trustedStripLeadingZeroInts(int val[]) {
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  2822
        int vlen = val.length;
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2823
        int keep;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2824
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2825
        // Find first nonzero byte
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  2826
        for (keep = 0; keep < vlen && val[keep] == 0; keep++)
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2827
            ;
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  2828
        return keep == 0 ? val : java.util.Arrays.copyOfRange(val, keep, vlen);
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2829
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2830
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2831
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2832
     * Returns a copy of the input array stripped of any leading zero bytes.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2833
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2834
    private static int[] stripLeadingZeroBytes(byte a[]) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2835
        int byteLength = a.length;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2836
        int keep;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2837
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2838
        // Find first nonzero byte
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  2839
        for (keep = 0; keep < byteLength && a[keep]==0; keep++)
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2840
            ;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2841
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2842
        // Allocate new array and copy relevant part of input array
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  2843
        int intLength = ((byteLength - keep) + 3) >>> 2;
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2844
        int[] result = new int[intLength];
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2845
        int b = byteLength - 1;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2846
        for (int i = intLength-1; i >= 0; i--) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2847
            result[i] = a[b--] & 0xff;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2848
            int bytesRemaining = b - keep + 1;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2849
            int bytesToTransfer = Math.min(3, bytesRemaining);
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  2850
            for (int j=8; j <= (bytesToTransfer << 3); j += 8)
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2851
                result[i] |= ((a[b--] & 0xff) << j);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2852
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2853
        return result;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2854
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2855
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2856
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2857
     * Takes an array a representing a negative 2's-complement number and
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2858
     * returns the minimal (no leading zero bytes) unsigned whose value is -a.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2859
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2860
    private static int[] makePositive(byte a[]) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2861
        int keep, k;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2862
        int byteLength = a.length;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2863
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2864
        // Find first non-sign (0xff) byte of input
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2865
        for (keep=0; keep<byteLength && a[keep]==-1; keep++)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2866
            ;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2867
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2868
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2869
        /* Allocate output array.  If all non-sign bytes are 0x00, we must
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2870
         * allocate space for one extra output byte. */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2871
        for (k=keep; k<byteLength && a[k]==0; k++)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2872
            ;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2873
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2874
        int extraByte = (k==byteLength) ? 1 : 0;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2875
        int intLength = ((byteLength - keep + extraByte) + 3)/4;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2876
        int result[] = new int[intLength];
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2877
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2878
        /* Copy one's complement of input into output, leaving extra
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2879
         * byte (if it exists) == 0x00 */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2880
        int b = byteLength - 1;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2881
        for (int i = intLength-1; i >= 0; i--) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2882
            result[i] = a[b--] & 0xff;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2883
            int numBytesToTransfer = Math.min(3, b-keep+1);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2884
            if (numBytesToTransfer < 0)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2885
                numBytesToTransfer = 0;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2886
            for (int j=8; j <= 8*numBytesToTransfer; j += 8)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2887
                result[i] |= ((a[b--] & 0xff) << j);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2888
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2889
            // Mask indicates which bits must be complemented
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2890
            int mask = -1 >>> (8*(3-numBytesToTransfer));
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2891
            result[i] = ~result[i] & mask;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2892
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2893
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2894
        // Add one to one's complement to generate two's complement
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2895
        for (int i=result.length-1; i>=0; i--) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2896
            result[i] = (int)((result[i] & LONG_MASK) + 1);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2897
            if (result[i] != 0)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2898
                break;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2899
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2900
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2901
        return result;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2902
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2903
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2904
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2905
     * Takes an array a representing a negative 2's-complement number and
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2906
     * returns the minimal (no leading zero ints) unsigned whose value is -a.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2907
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2908
    private static int[] makePositive(int a[]) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2909
        int keep, j;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2910
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2911
        // Find first non-sign (0xffffffff) int of input
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2912
        for (keep=0; keep<a.length && a[keep]==-1; keep++)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2913
            ;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2914
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2915
        /* Allocate output array.  If all non-sign ints are 0x00, we must
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2916
         * allocate space for one extra output int. */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2917
        for (j=keep; j<a.length && a[j]==0; j++)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2918
            ;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2919
        int extraInt = (j==a.length ? 1 : 0);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2920
        int result[] = new int[a.length - keep + extraInt];
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2921
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2922
        /* Copy one's complement of input into output, leaving extra
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2923
         * int (if it exists) == 0x00 */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2924
        for (int i = keep; i<a.length; i++)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2925
            result[i - keep + extraInt] = ~a[i];
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2926
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2927
        // Add one to one's complement to generate two's complement
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2928
        for (int i=result.length-1; ++result[i]==0; i--)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2929
            ;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2930
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2931
        return result;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2932
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2933
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2934
    /*
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2935
     * The following two arrays are used for fast String conversions.  Both
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2936
     * are indexed by radix.  The first is the number of digits of the given
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2937
     * radix that can fit in a Java long without "going negative", i.e., the
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2938
     * highest integer n such that radix**n < 2**63.  The second is the
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2939
     * "long radix" that tears each number into "long digits", each of which
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2940
     * consists of the number of digits in the corresponding element in
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2941
     * digitsPerLong (longRadix[i] = i**digitPerLong[i]).  Both arrays have
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2942
     * nonsense values in their 0 and 1 elements, as radixes 0 and 1 are not
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2943
     * used.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2944
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2945
    private static int digitsPerLong[] = {0, 0,
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2946
        62, 39, 31, 27, 24, 22, 20, 19, 18, 18, 17, 17, 16, 16, 15, 15, 15, 14,
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2947
        14, 14, 14, 13, 13, 13, 13, 13, 13, 12, 12, 12, 12, 12, 12, 12, 12};
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2948
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2949
    private static BigInteger longRadix[] = {null, null,
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2950
        valueOf(0x4000000000000000L), valueOf(0x383d9170b85ff80bL),
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2951
        valueOf(0x4000000000000000L), valueOf(0x6765c793fa10079dL),
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2952
        valueOf(0x41c21cb8e1000000L), valueOf(0x3642798750226111L),
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2953
        valueOf(0x1000000000000000L), valueOf(0x12bf307ae81ffd59L),
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2954
        valueOf( 0xde0b6b3a7640000L), valueOf(0x4d28cb56c33fa539L),
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2955
        valueOf(0x1eca170c00000000L), valueOf(0x780c7372621bd74dL),
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2956
        valueOf(0x1e39a5057d810000L), valueOf(0x5b27ac993df97701L),
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2957
        valueOf(0x1000000000000000L), valueOf(0x27b95e997e21d9f1L),
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2958
        valueOf(0x5da0e1e53c5c8000L), valueOf( 0xb16a458ef403f19L),
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2959
        valueOf(0x16bcc41e90000000L), valueOf(0x2d04b7fdd9c0ef49L),
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2960
        valueOf(0x5658597bcaa24000L), valueOf( 0x6feb266931a75b7L),
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2961
        valueOf( 0xc29e98000000000L), valueOf(0x14adf4b7320334b9L),
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2962
        valueOf(0x226ed36478bfa000L), valueOf(0x383d9170b85ff80bL),
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2963
        valueOf(0x5a3c23e39c000000L), valueOf( 0x4e900abb53e6b71L),
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2964
        valueOf( 0x7600ec618141000L), valueOf( 0xaee5720ee830681L),
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2965
        valueOf(0x1000000000000000L), valueOf(0x172588ad4f5f0981L),
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2966
        valueOf(0x211e44f7d02c1000L), valueOf(0x2ee56725f06e5c71L),
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2967
        valueOf(0x41c21cb8e1000000L)};
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2968
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2969
    /*
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2970
     * These two arrays are the integer analogue of above.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2971
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2972
    private static int digitsPerInt[] = {0, 0, 30, 19, 15, 13, 11,
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2973
        11, 10, 9, 9, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6,
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2974
        6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 5};
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2975
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2976
    private static int intRadix[] = {0, 0,
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2977
        0x40000000, 0x4546b3db, 0x40000000, 0x48c27395, 0x159fd800,
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2978
        0x75db9c97, 0x40000000, 0x17179149, 0x3b9aca00, 0xcc6db61,
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2979
        0x19a10000, 0x309f1021, 0x57f6c100, 0xa2f1b6f,  0x10000000,
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2980
        0x18754571, 0x247dbc80, 0x3547667b, 0x4c4b4000, 0x6b5a6e1d,
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2981
        0x6c20a40,  0x8d2d931,  0xb640000,  0xe8d4a51,  0x1269ae40,
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2982
        0x17179149, 0x1cb91000, 0x23744899, 0x2b73a840, 0x34e63b41,
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2983
        0x40000000, 0x4cfa3cc1, 0x5c13d840, 0x6d91b519, 0x39aa400
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2984
    };
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2985
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2986
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2987
     * These routines provide access to the two's complement representation
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2988
     * of BigIntegers.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2989
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2990
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2991
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2992
     * Returns the length of the two's complement representation in ints,
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2993
     * including space for at least one sign bit.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2994
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2995
    private int intLength() {
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  2996
        return (bitLength() >>> 5) + 1;
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2997
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2998
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2999
    /* Returns sign bit */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3000
    private int signBit() {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3001
        return signum < 0 ? 1 : 0;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3002
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3003
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3004
    /* Returns an int of sign bits */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3005
    private int signInt() {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3006
        return signum < 0 ? -1 : 0;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3007
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3008
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3009
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3010
     * Returns the specified int of the little-endian two's complement
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3011
     * representation (int 0 is the least significant).  The int number can
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3012
     * be arbitrarily high (values are logically preceded by infinitely many
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3013
     * sign ints).
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3014
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3015
    private int getInt(int n) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3016
        if (n < 0)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3017
            return 0;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3018
        if (n >= mag.length)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3019
            return signInt();
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3020
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3021
        int magInt = mag[mag.length-n-1];
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3022
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3023
        return (signum >= 0 ? magInt :
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3024
                (n <= firstNonzeroIntNum() ? -magInt : ~magInt));
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3025
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3026
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3027
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3028
     * Returns the index of the int that contains the first nonzero int in the
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3029
     * little-endian binary representation of the magnitude (int 0 is the
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3030
     * least significant). If the magnitude is zero, return value is undefined.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3031
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3032
     private int firstNonzeroIntNum() {
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  3033
         int fn = firstNonzeroIntNum - 2;
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  3034
         if (fn == -2) { // firstNonzeroIntNum not initialized yet
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  3035
             fn = 0;
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  3036
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  3037
             // Search for the first nonzero int
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  3038
             int i;
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  3039
             int mlen = mag.length;
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  3040
             for (i = mlen - 1; i >= 0 && mag[i] == 0; i--)
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  3041
                 ;
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  3042
             fn = mlen - i - 1;
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  3043
             firstNonzeroIntNum = fn + 2; // offset by two to initialize
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  3044
         }
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  3045
         return fn;
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  3046
     }
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3047
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3048
    /** use serialVersionUID from JDK 1.1. for interoperability */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3049
    private static final long serialVersionUID = -8287574255936472291L;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3050
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3051
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3052
     * Serializable fields for BigInteger.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3053
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3054
     * @serialField signum  int
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3055
     *              signum of this BigInteger.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3056
     * @serialField magnitude int[]
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3057
     *              magnitude array of this BigInteger.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3058
     * @serialField bitCount  int
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3059
     *              number of bits in this BigInteger
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3060
     * @serialField bitLength int
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3061
     *              the number of bits in the minimal two's-complement
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3062
     *              representation of this BigInteger
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3063
     * @serialField lowestSetBit int
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3064
     *              lowest set bit in the twos complement representation
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3065
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3066
    private static final ObjectStreamField[] serialPersistentFields = {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3067
        new ObjectStreamField("signum", Integer.TYPE),
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3068
        new ObjectStreamField("magnitude", byte[].class),
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3069
        new ObjectStreamField("bitCount", Integer.TYPE),
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3070
        new ObjectStreamField("bitLength", Integer.TYPE),
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3071
        new ObjectStreamField("firstNonzeroByteNum", Integer.TYPE),
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3072
        new ObjectStreamField("lowestSetBit", Integer.TYPE)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3073
        };
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3074
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3075
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3076
     * Reconstitute the {@code BigInteger} instance from a stream (that is,
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3077
     * deserialize it). The magnitude is read in as an array of bytes
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3078
     * for historical reasons, but it is converted to an array of ints
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3079
     * and the byte array is discarded.
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  3080
     * Note:
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  3081
     * The current convention is to initialize the cache fields, bitCount,
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  3082
     * bitLength and lowestSetBit, to 0 rather than some other marker value.
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  3083
     * Therefore, no explicit action to set these fields needs to be taken in
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  3084
     * readObject because those fields already have a 0 value be default since
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  3085
     * defaultReadObject is not being used.
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3086
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3087
    private void readObject(java.io.ObjectInputStream s)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3088
        throws java.io.IOException, ClassNotFoundException {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3089
        /*
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3090
         * In order to maintain compatibility with previous serialized forms,
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3091
         * the magnitude of a BigInteger is serialized as an array of bytes.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3092
         * The magnitude field is used as a temporary store for the byte array
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3093
         * that is deserialized. The cached computation fields should be
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3094
         * transient but are serialized for compatibility reasons.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3095
         */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3096
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3097
        // prepare to read the alternate persistent fields
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3098
        ObjectInputStream.GetField fields = s.readFields();
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3099
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3100
        // Read the alternate persistent fields that we care about
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  3101
        int sign = fields.get("signum", -2);
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3102
        byte[] magnitude = (byte[])fields.get("magnitude", null);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3103
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3104
        // Validate signum
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  3105
        if (sign < -1 || sign > 1) {
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3106
            String message = "BigInteger: Invalid signum value";
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3107
            if (fields.defaulted("signum"))
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3108
                message = "BigInteger: Signum not present in stream";
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3109
            throw new java.io.StreamCorruptedException(message);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3110
        }
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  3111
        if ((magnitude.length == 0) != (sign == 0)) {
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3112
            String message = "BigInteger: signum-magnitude mismatch";
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3113
            if (fields.defaulted("magnitude"))
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3114
                message = "BigInteger: Magnitude not present in stream";
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3115
            throw new java.io.StreamCorruptedException(message);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3116
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3117
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  3118
        // Commit final fields via Unsafe
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  3119
        unsafe.putIntVolatile(this, signumOffset, sign);
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3120
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3121
        // Calculate mag field from magnitude and discard magnitude
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  3122
        unsafe.putObjectVolatile(this, magOffset,
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  3123
                                 stripLeadingZeroBytes(magnitude));
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  3124
    }
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  3125
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  3126
    // Support for resetting final fields while deserializing
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  3127
    private static final sun.misc.Unsafe unsafe = sun.misc.Unsafe.getUnsafe();
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  3128
    private static final long signumOffset;
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  3129
    private static final long magOffset;
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  3130
    static {
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  3131
        try {
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  3132
            signumOffset = unsafe.objectFieldOffset
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  3133
                (BigInteger.class.getDeclaredField("signum"));
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  3134
            magOffset = unsafe.objectFieldOffset
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  3135
                (BigInteger.class.getDeclaredField("mag"));
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  3136
        } catch (Exception ex) {
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  3137
            throw new Error(ex);
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  3138
        }
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3139
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3140
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3141
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3142
     * Save the {@code BigInteger} instance to a stream.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3143
     * The magnitude of a BigInteger is serialized as a byte array for
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3144
     * historical reasons.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3145
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3146
     * @serialData two necessary fields are written as well as obsolete
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3147
     *             fields for compatibility with older versions.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3148
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3149
    private void writeObject(ObjectOutputStream s) throws IOException {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3150
        // set the values of the Serializable fields
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3151
        ObjectOutputStream.PutField fields = s.putFields();
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3152
        fields.put("signum", signum);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3153
        fields.put("magnitude", magSerializedForm());
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  3154
        // The values written for cached fields are compatible with older
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  3155
        // versions, but are ignored in readObject so don't otherwise matter.
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3156
        fields.put("bitCount", -1);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3157
        fields.put("bitLength", -1);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3158
        fields.put("lowestSetBit", -2);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3159
        fields.put("firstNonzeroByteNum", -2);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3160
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3161
        // save them
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3162
        s.writeFields();
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3163
}
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3164
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3165
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3166
     * Returns the mag array as an array of bytes.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3167
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3168
    private byte[] magSerializedForm() {
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  3169
        int len = mag.length;
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  3170
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  3171
        int bitLen = (len == 0 ? 0 : ((len - 1) << 5) + bitLengthForInt(mag[0]));
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  3172
        int byteLen = (bitLen + 7) >>> 3;
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3173
        byte[] result = new byte[byteLen];
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3174
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  3175
        for (int i = byteLen - 1, bytesCopied = 4, intIndex = len - 1, nextInt = 0;
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3176
             i>=0; i--) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3177
            if (bytesCopied == 4) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3178
                nextInt = mag[intIndex--];
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3179
                bytesCopied = 1;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3180
            } else {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3181
                nextInt >>>= 8;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3182
                bytesCopied++;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3183
            }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3184
            result[i] = (byte)nextInt;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3185
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3186
        return result;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3187
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3188
}