src/java.base/share/classes/java/math/BigInteger.java
author mchung
Mon, 22 Oct 2018 17:00:04 -0700
changeset 52220 9c260a6b6471
parent 52088 c7f7d824f2b6
child 53327 620b31ed8807
permissions -rw-r--r--
8207146: Rename jdk.internal.misc.Unsafe::xxxObject to xxxReference Reviewed-by: dholmes, thartmann
Ignore whitespace changes - Everywhere: Within whitespace: At end of lines:
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
     1
/*
49237
6e6c3a755b89 8199258: BigInteger.bitLength() should explicitly specify behavior when the value is zero
bpb
parents: 47866
diff changeset
     2
 * Copyright (c) 1996, 2018, Oracle and/or its affiliates. All rights reserved.
2
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
5506
202f599c92aa 6943119: Rebrand source copyright notices
ohair
parents: 4182
diff changeset
     7
 * published by the Free Software Foundation.  Oracle designates this
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
     8
 * particular file as subject to the "Classpath" exception as provided
5506
202f599c92aa 6943119: Rebrand source copyright notices
ohair
parents: 4182
diff changeset
     9
 * by Oracle in the LICENSE file that accompanied this code.
2
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
 *
5506
202f599c92aa 6943119: Rebrand source copyright notices
ohair
parents: 4182
diff changeset
    21
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
202f599c92aa 6943119: Rebrand source copyright notices
ohair
parents: 4182
diff changeset
    22
 * or visit www.oracle.com if you need additional information or have any
202f599c92aa 6943119: Rebrand source copyright notices
ohair
parents: 4182
diff changeset
    23
 * questions.
2
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
18286
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
    32
import java.io.IOException;
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
    33
import java.io.ObjectInputStream;
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
    34
import java.io.ObjectOutputStream;
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
    35
import java.io.ObjectStreamField;
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
    36
import java.util.Arrays;
31671
362e0c0acece 8076112: Add @HotSpotIntrinsicCandidate annotation to indicate methods for which Java Runtime has intrinsics
zmajo
parents: 31667
diff changeset
    37
import java.util.Objects;
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
    38
import java.util.Random;
20756
d998355e6a5c 7189139: BigInteger's staticRandom field can be a source of bottlenecks.
bpb
parents: 19585
diff changeset
    39
import java.util.concurrent.ThreadLocalRandom;
31671
362e0c0acece 8076112: Add @HotSpotIntrinsicCandidate annotation to indicate methods for which Java Runtime has intrinsics
zmajo
parents: 31667
diff changeset
    40
34781
479b1724ab80 8145990: Move sun.misc math support classes to jdk.internal.math
chegar
parents: 34538
diff changeset
    41
import jdk.internal.math.DoubleConsts;
479b1724ab80 8145990: Move sun.misc math support classes to jdk.internal.math
chegar
parents: 34538
diff changeset
    42
import jdk.internal.math.FloatConsts;
31671
362e0c0acece 8076112: Add @HotSpotIntrinsicCandidate annotation to indicate methods for which Java Runtime has intrinsics
zmajo
parents: 31667
diff changeset
    43
import jdk.internal.HotSpotIntrinsicCandidate;
52088
c7f7d824f2b6 8152910: Get performance improvement with Stable annotation
bpb
parents: 50062
diff changeset
    44
import jdk.internal.vm.annotation.Stable;
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
    45
90ce3da70b43 Initial load
duke
parents:
diff changeset
    46
/**
90ce3da70b43 Initial load
duke
parents:
diff changeset
    47
 * Immutable arbitrary-precision integers.  All operations behave as if
90ce3da70b43 Initial load
duke
parents:
diff changeset
    48
 * BigIntegers were represented in two's-complement notation (like Java's
90ce3da70b43 Initial load
duke
parents:
diff changeset
    49
 * primitive integer types).  BigInteger provides analogues to all of Java's
90ce3da70b43 Initial load
duke
parents:
diff changeset
    50
 * primitive integer operators, and all relevant methods from java.lang.Math.
90ce3da70b43 Initial load
duke
parents:
diff changeset
    51
 * Additionally, BigInteger provides operations for modular arithmetic, GCD
90ce3da70b43 Initial load
duke
parents:
diff changeset
    52
 * calculation, primality testing, prime generation, bit manipulation,
90ce3da70b43 Initial load
duke
parents:
diff changeset
    53
 * and a few other miscellaneous operations.
90ce3da70b43 Initial load
duke
parents:
diff changeset
    54
 *
90ce3da70b43 Initial load
duke
parents:
diff changeset
    55
 * <p>Semantics of arithmetic operations exactly mimic those of Java's integer
50062
e64e3cd120b7 8202563: BigInteger/BigDecimal not immune to overflow, contrary to spec
darcy
parents: 49237
diff changeset
    56
 * arithmetic operators, as defined in <i>The Java&trade; Language Specification</i>.
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
    57
 * For example, division by zero throws an {@code ArithmeticException}, and
90ce3da70b43 Initial load
duke
parents:
diff changeset
    58
 * division of a negative by a positive yields a negative (or zero) remainder.
90ce3da70b43 Initial load
duke
parents:
diff changeset
    59
 *
90ce3da70b43 Initial load
duke
parents:
diff changeset
    60
 * <p>Semantics of shift operations extend those of Java's shift operators
90ce3da70b43 Initial load
duke
parents:
diff changeset
    61
 * to allow for negative shift distances.  A right-shift with a negative
90ce3da70b43 Initial load
duke
parents:
diff changeset
    62
 * shift distance results in a left shift, and vice-versa.  The unsigned
50062
e64e3cd120b7 8202563: BigInteger/BigDecimal not immune to overflow, contrary to spec
darcy
parents: 49237
diff changeset
    63
 * right shift operator ({@code >>>}) is omitted since this operation
e64e3cd120b7 8202563: BigInteger/BigDecimal not immune to overflow, contrary to spec
darcy
parents: 49237
diff changeset
    64
 * only makes sense for a fixed sized word and not for a
e64e3cd120b7 8202563: BigInteger/BigDecimal not immune to overflow, contrary to spec
darcy
parents: 49237
diff changeset
    65
 * representation conceptually having an infinite number of leading
e64e3cd120b7 8202563: BigInteger/BigDecimal not immune to overflow, contrary to spec
darcy
parents: 49237
diff changeset
    66
 * virtual sign bits.
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
    67
 *
90ce3da70b43 Initial load
duke
parents:
diff changeset
    68
 * <p>Semantics of bitwise logical operations exactly mimic those of Java's
90ce3da70b43 Initial load
duke
parents:
diff changeset
    69
 * bitwise integer operators.  The binary operators ({@code and},
90ce3da70b43 Initial load
duke
parents:
diff changeset
    70
 * {@code or}, {@code xor}) implicitly perform sign extension on the shorter
90ce3da70b43 Initial load
duke
parents:
diff changeset
    71
 * of the two operands prior to performing the operation.
90ce3da70b43 Initial load
duke
parents:
diff changeset
    72
 *
90ce3da70b43 Initial load
duke
parents:
diff changeset
    73
 * <p>Comparison operations perform signed integer comparisons, analogous to
90ce3da70b43 Initial load
duke
parents:
diff changeset
    74
 * those performed by Java's relational and equality operators.
90ce3da70b43 Initial load
duke
parents:
diff changeset
    75
 *
90ce3da70b43 Initial load
duke
parents:
diff changeset
    76
 * <p>Modular arithmetic operations are provided to compute residues, perform
90ce3da70b43 Initial load
duke
parents:
diff changeset
    77
 * exponentiation, and compute multiplicative inverses.  These methods always
90ce3da70b43 Initial load
duke
parents:
diff changeset
    78
 * return a non-negative result, between {@code 0} and {@code (modulus - 1)},
90ce3da70b43 Initial load
duke
parents:
diff changeset
    79
 * inclusive.
90ce3da70b43 Initial load
duke
parents:
diff changeset
    80
 *
90ce3da70b43 Initial load
duke
parents:
diff changeset
    81
 * <p>Bit operations operate on a single bit of the two's-complement
90ce3da70b43 Initial load
duke
parents:
diff changeset
    82
 * representation of their operand.  If necessary, the operand is sign-
90ce3da70b43 Initial load
duke
parents:
diff changeset
    83
 * extended so that it contains the designated bit.  None of the single-bit
90ce3da70b43 Initial load
duke
parents:
diff changeset
    84
 * operations can produce a BigInteger with a different sign from the
90ce3da70b43 Initial load
duke
parents:
diff changeset
    85
 * BigInteger being operated on, as they affect only a single bit, and the
50062
e64e3cd120b7 8202563: BigInteger/BigDecimal not immune to overflow, contrary to spec
darcy
parents: 49237
diff changeset
    86
 * arbitrarily large abstraction provided by this class ensures that conceptually
e64e3cd120b7 8202563: BigInteger/BigDecimal not immune to overflow, contrary to spec
darcy
parents: 49237
diff changeset
    87
 * there are infinitely many "virtual sign bits" preceding each BigInteger.
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
    88
 *
90ce3da70b43 Initial load
duke
parents:
diff changeset
    89
 * <p>For the sake of brevity and clarity, pseudo-code is used throughout the
90ce3da70b43 Initial load
duke
parents:
diff changeset
    90
 * descriptions of BigInteger methods.  The pseudo-code expression
90ce3da70b43 Initial load
duke
parents:
diff changeset
    91
 * {@code (i + j)} is shorthand for "a BigInteger whose value is
90ce3da70b43 Initial load
duke
parents:
diff changeset
    92
 * that of the BigInteger {@code i} plus that of the BigInteger {@code j}."
90ce3da70b43 Initial load
duke
parents:
diff changeset
    93
 * The pseudo-code expression {@code (i == j)} is shorthand for
90ce3da70b43 Initial load
duke
parents:
diff changeset
    94
 * "{@code true} if and only if the BigInteger {@code i} represents the same
90ce3da70b43 Initial load
duke
parents:
diff changeset
    95
 * value as the BigInteger {@code j}."  Other pseudo-code expressions are
90ce3da70b43 Initial load
duke
parents:
diff changeset
    96
 * interpreted similarly.
90ce3da70b43 Initial load
duke
parents:
diff changeset
    97
 *
90ce3da70b43 Initial load
duke
parents:
diff changeset
    98
 * <p>All methods and constructors in this class throw
90ce3da70b43 Initial load
duke
parents:
diff changeset
    99
 * {@code NullPointerException} when passed
90ce3da70b43 Initial load
duke
parents:
diff changeset
   100
 * a null object reference for any input parameter.
90ce3da70b43 Initial load
duke
parents:
diff changeset
   101
 *
21420
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
   102
 * BigInteger must support values in the range
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
   103
 * -2<sup>{@code Integer.MAX_VALUE}</sup> (exclusive) to
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
   104
 * +2<sup>{@code Integer.MAX_VALUE}</sup> (exclusive)
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
   105
 * and may support values outside of that range.
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
   106
 *
50062
e64e3cd120b7 8202563: BigInteger/BigDecimal not immune to overflow, contrary to spec
darcy
parents: 49237
diff changeset
   107
 * An {@code ArithmeticException} is thrown when a BigInteger
e64e3cd120b7 8202563: BigInteger/BigDecimal not immune to overflow, contrary to spec
darcy
parents: 49237
diff changeset
   108
 * constructor or method would generate a value outside of the
e64e3cd120b7 8202563: BigInteger/BigDecimal not immune to overflow, contrary to spec
darcy
parents: 49237
diff changeset
   109
 * supported range.
e64e3cd120b7 8202563: BigInteger/BigDecimal not immune to overflow, contrary to spec
darcy
parents: 49237
diff changeset
   110
 *
21420
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
   111
 * The range of probable prime values is limited and may be less than
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
   112
 * the full supported positive range of {@code BigInteger}.
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
   113
 * The range must be at least 1 to 2<sup>500000000</sup>.
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
   114
 *
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
   115
 * @implNote
50062
e64e3cd120b7 8202563: BigInteger/BigDecimal not immune to overflow, contrary to spec
darcy
parents: 49237
diff changeset
   116
 * In the reference implementation, BigInteger constructors and
e64e3cd120b7 8202563: BigInteger/BigDecimal not immune to overflow, contrary to spec
darcy
parents: 49237
diff changeset
   117
 * operations throw {@code ArithmeticException} when the result is out
e64e3cd120b7 8202563: BigInteger/BigDecimal not immune to overflow, contrary to spec
darcy
parents: 49237
diff changeset
   118
 * of the supported range of
21420
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
   119
 * -2<sup>{@code Integer.MAX_VALUE}</sup> (exclusive) to
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
   120
 * +2<sup>{@code Integer.MAX_VALUE}</sup> (exclusive).
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
   121
 *
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   122
 * @see     BigDecimal
38553
0553095041d7 8157724: Improve javadoc tag usage in java.math
darcy
parents: 37880
diff changeset
   123
 * @jls     4.2.2 Integer Operations
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   124
 * @author  Josh Bloch
90ce3da70b43 Initial load
duke
parents:
diff changeset
   125
 * @author  Michael McCloskey
18286
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
   126
 * @author  Alan Eliasen
19060
4d949a65ad7f 8014319: Faster division of large integers
bpb
parents: 18588
diff changeset
   127
 * @author  Timothy Buktu
24865
09b1d992ca72 8044740: Convert all JDK versions used in @since tag to 1.n[.n] in jdk repo
henryjen
parents: 24367
diff changeset
   128
 * @since 1.1
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   129
 */
90ce3da70b43 Initial load
duke
parents:
diff changeset
   130
90ce3da70b43 Initial load
duke
parents:
diff changeset
   131
public class BigInteger extends Number implements Comparable<BigInteger> {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   132
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
   133
     * The signum of this BigInteger: -1 for negative, 0 for zero, or
38553
0553095041d7 8157724: Improve javadoc tag usage in java.math
darcy
parents: 37880
diff changeset
   134
     * 1 for positive.  Note that the BigInteger zero <em>must</em> have
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   135
     * a signum of 0.  This is necessary to ensures that there is exactly one
90ce3da70b43 Initial load
duke
parents:
diff changeset
   136
     * representation for each BigInteger value.
90ce3da70b43 Initial load
duke
parents:
diff changeset
   137
     */
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
   138
    final int signum;
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   139
90ce3da70b43 Initial load
duke
parents:
diff changeset
   140
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
   141
     * The magnitude of this BigInteger, in <i>big-endian</i> order: the
90ce3da70b43 Initial load
duke
parents:
diff changeset
   142
     * zeroth element of this array is the most-significant int of the
90ce3da70b43 Initial load
duke
parents:
diff changeset
   143
     * magnitude.  The magnitude must be "minimal" in that the most-significant
90ce3da70b43 Initial load
duke
parents:
diff changeset
   144
     * int ({@code mag[0]}) must be non-zero.  This is necessary to
90ce3da70b43 Initial load
duke
parents:
diff changeset
   145
     * ensure that there is exactly one representation for each BigInteger
90ce3da70b43 Initial load
duke
parents:
diff changeset
   146
     * value.  Note that this implies that the BigInteger zero has a
90ce3da70b43 Initial load
duke
parents:
diff changeset
   147
     * zero-length mag array.
90ce3da70b43 Initial load
duke
parents:
diff changeset
   148
     */
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
   149
    final int[] mag;
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   150
23332
c36c4773fe96 8035279: Clean up internal deprecations in BigInteger
bpb
parents: 22042
diff changeset
   151
    // The following fields are stable variables. A stable variable's value
c36c4773fe96 8035279: Clean up internal deprecations in BigInteger
bpb
parents: 22042
diff changeset
   152
    // changes at most once from the default zero value to a non-zero stable
c36c4773fe96 8035279: Clean up internal deprecations in BigInteger
bpb
parents: 22042
diff changeset
   153
    // value. A stable value is calculated lazily on demand.
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   154
90ce3da70b43 Initial load
duke
parents:
diff changeset
   155
    /**
23332
c36c4773fe96 8035279: Clean up internal deprecations in BigInteger
bpb
parents: 22042
diff changeset
   156
     * One plus the bitCount of this BigInteger. This is a stable variable.
c36c4773fe96 8035279: Clean up internal deprecations in BigInteger
bpb
parents: 22042
diff changeset
   157
     *
c36c4773fe96 8035279: Clean up internal deprecations in BigInteger
bpb
parents: 22042
diff changeset
   158
     * @see #bitCount
c36c4773fe96 8035279: Clean up internal deprecations in BigInteger
bpb
parents: 22042
diff changeset
   159
     */
c36c4773fe96 8035279: Clean up internal deprecations in BigInteger
bpb
parents: 22042
diff changeset
   160
    private int bitCountPlusOne;
c36c4773fe96 8035279: Clean up internal deprecations in BigInteger
bpb
parents: 22042
diff changeset
   161
c36c4773fe96 8035279: Clean up internal deprecations in BigInteger
bpb
parents: 22042
diff changeset
   162
    /**
c36c4773fe96 8035279: Clean up internal deprecations in BigInteger
bpb
parents: 22042
diff changeset
   163
     * One plus the bitLength of this BigInteger. This is a stable variable.
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   164
     * (either value is acceptable).
90ce3da70b43 Initial load
duke
parents:
diff changeset
   165
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
   166
     * @see #bitLength()
90ce3da70b43 Initial load
duke
parents:
diff changeset
   167
     */
23332
c36c4773fe96 8035279: Clean up internal deprecations in BigInteger
bpb
parents: 22042
diff changeset
   168
    private int bitLengthPlusOne;
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   169
90ce3da70b43 Initial load
duke
parents:
diff changeset
   170
    /**
23332
c36c4773fe96 8035279: Clean up internal deprecations in BigInteger
bpb
parents: 22042
diff changeset
   171
     * Two plus the lowest set bit of this BigInteger. This is a stable variable.
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   172
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
   173
     * @see #getLowestSetBit
90ce3da70b43 Initial load
duke
parents:
diff changeset
   174
     */
23332
c36c4773fe96 8035279: Clean up internal deprecations in BigInteger
bpb
parents: 22042
diff changeset
   175
    private int lowestSetBitPlusTwo;
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   176
90ce3da70b43 Initial load
duke
parents:
diff changeset
   177
    /**
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
   178
     * Two plus the index of the lowest-order int in the magnitude of this
23332
c36c4773fe96 8035279: Clean up internal deprecations in BigInteger
bpb
parents: 22042
diff changeset
   179
     * BigInteger that contains a nonzero int. This is a stable variable. The
c36c4773fe96 8035279: Clean up internal deprecations in BigInteger
bpb
parents: 22042
diff changeset
   180
     * least significant int has int-number 0, the next int in order of
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
   181
     * increasing significance has int-number 1, and so forth.
23332
c36c4773fe96 8035279: Clean up internal deprecations in BigInteger
bpb
parents: 22042
diff changeset
   182
     *
c36c4773fe96 8035279: Clean up internal deprecations in BigInteger
bpb
parents: 22042
diff changeset
   183
     * <p>Note: never used for a BigInteger with a magnitude of zero.
c36c4773fe96 8035279: Clean up internal deprecations in BigInteger
bpb
parents: 22042
diff changeset
   184
     *
c36c4773fe96 8035279: Clean up internal deprecations in BigInteger
bpb
parents: 22042
diff changeset
   185
     * @see #firstNonzeroIntNum()
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   186
     */
23332
c36c4773fe96 8035279: Clean up internal deprecations in BigInteger
bpb
parents: 22042
diff changeset
   187
    private int firstNonzeroIntNumPlusTwo;
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   188
90ce3da70b43 Initial load
duke
parents:
diff changeset
   189
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
   190
     * This mask is used to obtain the value of an int as if it were unsigned.
90ce3da70b43 Initial load
duke
parents:
diff changeset
   191
     */
32649
2ee9017c7597 8136583: Core libraries should use blessed modifier order
martin
parents: 32033
diff changeset
   192
    static final long LONG_MASK = 0xffffffffL;
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   193
18286
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
   194
    /**
21420
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
   195
     * This constant limits {@code mag.length} of BigIntegers to the supported
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
   196
     * range.
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
   197
     */
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
   198
    private static final int MAX_MAG_LENGTH = Integer.MAX_VALUE / Integer.SIZE + 1; // (1 << 26)
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
   199
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
   200
    /**
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
   201
     * Bit lengths larger than this constant can cause overflow in searchLen
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
   202
     * calculation and in BitSieve.singleSearch method.
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
   203
     */
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
   204
    private static final  int PRIME_SEARCH_BIT_LENGTH_LIMIT = 500000000;
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
   205
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
   206
    /**
18286
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
   207
     * The threshold value for using Karatsuba multiplication.  If the number
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
   208
     * of ints in both mag arrays are greater than this number, then
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
   209
     * Karatsuba multiplication will be used.   This value is found
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
   210
     * experimentally to work well.
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
   211
     */
21956
ec42ad3d0bf8 8022181: Tune algorithm crossover thresholds in BigInteger
bpb
parents: 21420
diff changeset
   212
    private static final int KARATSUBA_THRESHOLD = 80;
18286
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
   213
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
   214
    /**
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
   215
     * The threshold value for using 3-way Toom-Cook multiplication.
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
   216
     * If the number of ints in each mag array is greater than the
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
   217
     * Karatsuba threshold, and the number of ints in at least one of
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
   218
     * the mag arrays is greater than this threshold, then Toom-Cook
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
   219
     * multiplication will be used.
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
   220
     */
21956
ec42ad3d0bf8 8022181: Tune algorithm crossover thresholds in BigInteger
bpb
parents: 21420
diff changeset
   221
    private static final int TOOM_COOK_THRESHOLD = 240;
18286
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
   222
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
   223
    /**
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
   224
     * The threshold value for using Karatsuba squaring.  If the number
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
   225
     * of ints in the number are larger than this value,
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
   226
     * Karatsuba squaring will be used.   This value is found
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
   227
     * experimentally to work well.
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
   228
     */
21956
ec42ad3d0bf8 8022181: Tune algorithm crossover thresholds in BigInteger
bpb
parents: 21420
diff changeset
   229
    private static final int KARATSUBA_SQUARE_THRESHOLD = 128;
18286
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
   230
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
   231
    /**
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
   232
     * The threshold value for using Toom-Cook squaring.  If the number
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
   233
     * of ints in the number are larger than this value,
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
   234
     * Toom-Cook squaring will be used.   This value is found
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
   235
     * experimentally to work well.
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
   236
     */
21956
ec42ad3d0bf8 8022181: Tune algorithm crossover thresholds in BigInteger
bpb
parents: 21420
diff changeset
   237
    private static final int TOOM_COOK_SQUARE_THRESHOLD = 216;
18286
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
   238
18548
0b6ca9785d8c 4641897: Faster string conversion of large integers
bpb
parents: 18538
diff changeset
   239
    /**
19060
4d949a65ad7f 8014319: Faster division of large integers
bpb
parents: 18588
diff changeset
   240
     * The threshold value for using Burnikel-Ziegler division.  If the number
21984
4dff16390b67 8029501: BigInteger division algorithm selection heuristic is incorrect
bpb
parents: 21983
diff changeset
   241
     * of ints in the divisor are larger than this value, Burnikel-Ziegler
4dff16390b67 8029501: BigInteger division algorithm selection heuristic is incorrect
bpb
parents: 21983
diff changeset
   242
     * division may be used.  This value is found experimentally to work well.
19060
4d949a65ad7f 8014319: Faster division of large integers
bpb
parents: 18588
diff changeset
   243
     */
21956
ec42ad3d0bf8 8022181: Tune algorithm crossover thresholds in BigInteger
bpb
parents: 21420
diff changeset
   244
    static final int BURNIKEL_ZIEGLER_THRESHOLD = 80;
19060
4d949a65ad7f 8014319: Faster division of large integers
bpb
parents: 18588
diff changeset
   245
4d949a65ad7f 8014319: Faster division of large integers
bpb
parents: 18588
diff changeset
   246
    /**
21984
4dff16390b67 8029501: BigInteger division algorithm selection heuristic is incorrect
bpb
parents: 21983
diff changeset
   247
     * The offset value for using Burnikel-Ziegler division.  If the number
4dff16390b67 8029501: BigInteger division algorithm selection heuristic is incorrect
bpb
parents: 21983
diff changeset
   248
     * of ints in the divisor exceeds the Burnikel-Ziegler threshold, and the
4dff16390b67 8029501: BigInteger division algorithm selection heuristic is incorrect
bpb
parents: 21983
diff changeset
   249
     * number of ints in the dividend is greater than the number of ints in the
4dff16390b67 8029501: BigInteger division algorithm selection heuristic is incorrect
bpb
parents: 21983
diff changeset
   250
     * divisor plus this value, Burnikel-Ziegler division will be used.  This
4dff16390b67 8029501: BigInteger division algorithm selection heuristic is incorrect
bpb
parents: 21983
diff changeset
   251
     * value is found experimentally to work well.
4dff16390b67 8029501: BigInteger division algorithm selection heuristic is incorrect
bpb
parents: 21983
diff changeset
   252
     */
4dff16390b67 8029501: BigInteger division algorithm selection heuristic is incorrect
bpb
parents: 21983
diff changeset
   253
    static final int BURNIKEL_ZIEGLER_OFFSET = 40;
4dff16390b67 8029501: BigInteger division algorithm selection heuristic is incorrect
bpb
parents: 21983
diff changeset
   254
4dff16390b67 8029501: BigInteger division algorithm selection heuristic is incorrect
bpb
parents: 21983
diff changeset
   255
    /**
18548
0b6ca9785d8c 4641897: Faster string conversion of large integers
bpb
parents: 18538
diff changeset
   256
     * The threshold value for using Schoenhage recursive base conversion. If
0b6ca9785d8c 4641897: Faster string conversion of large integers
bpb
parents: 18538
diff changeset
   257
     * the number of ints in the number are larger than this value,
0b6ca9785d8c 4641897: Faster string conversion of large integers
bpb
parents: 18538
diff changeset
   258
     * the Schoenhage algorithm will be used.  In practice, it appears that the
0b6ca9785d8c 4641897: Faster string conversion of large integers
bpb
parents: 18538
diff changeset
   259
     * Schoenhage routine is faster for any threshold down to 2, and is
0b6ca9785d8c 4641897: Faster string conversion of large integers
bpb
parents: 18538
diff changeset
   260
     * relatively flat for thresholds between 2-25, so this choice may be
0b6ca9785d8c 4641897: Faster string conversion of large integers
bpb
parents: 18538
diff changeset
   261
     * varied within this range for very small effect.
0b6ca9785d8c 4641897: Faster string conversion of large integers
bpb
parents: 18538
diff changeset
   262
     */
21956
ec42ad3d0bf8 8022181: Tune algorithm crossover thresholds in BigInteger
bpb
parents: 21420
diff changeset
   263
    private static final int SCHOENHAGE_BASE_CONVERSION_THRESHOLD = 20;
18548
0b6ca9785d8c 4641897: Faster string conversion of large integers
bpb
parents: 18538
diff changeset
   264
22042
98541fec9c62 4891331: BigInteger a.multiply(a) should use squaring code
bpb
parents: 21984
diff changeset
   265
    /**
98541fec9c62 4891331: BigInteger a.multiply(a) should use squaring code
bpb
parents: 21984
diff changeset
   266
     * The threshold value for using squaring code to perform multiplication
98541fec9c62 4891331: BigInteger a.multiply(a) should use squaring code
bpb
parents: 21984
diff changeset
   267
     * of a {@code BigInteger} instance by itself.  If the number of ints in
98541fec9c62 4891331: BigInteger a.multiply(a) should use squaring code
bpb
parents: 21984
diff changeset
   268
     * the number are larger than this value, {@code multiply(this)} will
98541fec9c62 4891331: BigInteger a.multiply(a) should use squaring code
bpb
parents: 21984
diff changeset
   269
     * return {@code square()}.
98541fec9c62 4891331: BigInteger a.multiply(a) should use squaring code
bpb
parents: 21984
diff changeset
   270
     */
98541fec9c62 4891331: BigInteger a.multiply(a) should use squaring code
bpb
parents: 21984
diff changeset
   271
    private static final int MULTIPLY_SQUARE_THRESHOLD = 20;
98541fec9c62 4891331: BigInteger a.multiply(a) should use squaring code
bpb
parents: 21984
diff changeset
   272
31667
15a14e8fcfb0 8130150: Implement BigInteger.montgomeryMultiply intrinsic
aph
parents: 31146
diff changeset
   273
    /**
15a14e8fcfb0 8130150: Implement BigInteger.montgomeryMultiply intrinsic
aph
parents: 31146
diff changeset
   274
     * The threshold for using an intrinsic version of
15a14e8fcfb0 8130150: Implement BigInteger.montgomeryMultiply intrinsic
aph
parents: 31146
diff changeset
   275
     * implMontgomeryXXX to perform Montgomery multiplication.  If the
15a14e8fcfb0 8130150: Implement BigInteger.montgomeryMultiply intrinsic
aph
parents: 31146
diff changeset
   276
     * number of ints in the number is more than this value we do not
15a14e8fcfb0 8130150: Implement BigInteger.montgomeryMultiply intrinsic
aph
parents: 31146
diff changeset
   277
     * use the intrinsic.
15a14e8fcfb0 8130150: Implement BigInteger.montgomeryMultiply intrinsic
aph
parents: 31146
diff changeset
   278
     */
15a14e8fcfb0 8130150: Implement BigInteger.montgomeryMultiply intrinsic
aph
parents: 31146
diff changeset
   279
    private static final int MONTGOMERY_INTRINSIC_THRESHOLD = 512;
15a14e8fcfb0 8130150: Implement BigInteger.montgomeryMultiply intrinsic
aph
parents: 31146
diff changeset
   280
15a14e8fcfb0 8130150: Implement BigInteger.montgomeryMultiply intrinsic
aph
parents: 31146
diff changeset
   281
22042
98541fec9c62 4891331: BigInteger a.multiply(a) should use squaring code
bpb
parents: 21984
diff changeset
   282
    // Constructors
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   283
90ce3da70b43 Initial load
duke
parents:
diff changeset
   284
    /**
28309
45f25a2cf942 4026465: Provide more byte array constructors for BigInteger
bpb
parents: 25859
diff changeset
   285
     * Translates a byte sub-array containing the two's-complement binary
45f25a2cf942 4026465: Provide more byte array constructors for BigInteger
bpb
parents: 25859
diff changeset
   286
     * representation of a BigInteger into a BigInteger.  The sub-array is
45f25a2cf942 4026465: Provide more byte array constructors for BigInteger
bpb
parents: 25859
diff changeset
   287
     * specified via an offset into the array and a length.  The sub-array is
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   288
     * assumed to be in <i>big-endian</i> byte-order: the most significant
28309
45f25a2cf942 4026465: Provide more byte array constructors for BigInteger
bpb
parents: 25859
diff changeset
   289
     * byte is the element at index {@code off}.  The {@code val} array is
45f25a2cf942 4026465: Provide more byte array constructors for BigInteger
bpb
parents: 25859
diff changeset
   290
     * assumed to be unchanged for the duration of the constructor call.
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   291
     *
28309
45f25a2cf942 4026465: Provide more byte array constructors for BigInteger
bpb
parents: 25859
diff changeset
   292
     * An {@code IndexOutOfBoundsException} is thrown if the length of the array
45f25a2cf942 4026465: Provide more byte array constructors for BigInteger
bpb
parents: 25859
diff changeset
   293
     * {@code val} is non-zero and either {@code off} is negative, {@code len}
45f25a2cf942 4026465: Provide more byte array constructors for BigInteger
bpb
parents: 25859
diff changeset
   294
     * is negative, or {@code off+len} is greater than the length of
45f25a2cf942 4026465: Provide more byte array constructors for BigInteger
bpb
parents: 25859
diff changeset
   295
     * {@code val}.
45f25a2cf942 4026465: Provide more byte array constructors for BigInteger
bpb
parents: 25859
diff changeset
   296
     *
45f25a2cf942 4026465: Provide more byte array constructors for BigInteger
bpb
parents: 25859
diff changeset
   297
     * @param  val byte array containing a sub-array which is the big-endian
45f25a2cf942 4026465: Provide more byte array constructors for BigInteger
bpb
parents: 25859
diff changeset
   298
     *         two's-complement binary representation of a BigInteger.
45f25a2cf942 4026465: Provide more byte array constructors for BigInteger
bpb
parents: 25859
diff changeset
   299
     * @param  off the start offset of the binary representation.
45f25a2cf942 4026465: Provide more byte array constructors for BigInteger
bpb
parents: 25859
diff changeset
   300
     * @param  len the number of bytes to use.
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   301
     * @throws NumberFormatException {@code val} is zero bytes long.
28309
45f25a2cf942 4026465: Provide more byte array constructors for BigInteger
bpb
parents: 25859
diff changeset
   302
     * @throws IndexOutOfBoundsException if the provided array offset and
45f25a2cf942 4026465: Provide more byte array constructors for BigInteger
bpb
parents: 25859
diff changeset
   303
     *         length would cause an index into the byte array to be
45f25a2cf942 4026465: Provide more byte array constructors for BigInteger
bpb
parents: 25859
diff changeset
   304
     *         negative or greater than or equal to the array length.
35302
e4d2275861c3 8136494: Update "@since 1.9" to "@since 9" to match java.version.specification
iris
parents: 34781
diff changeset
   305
     * @since 9
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   306
     */
28309
45f25a2cf942 4026465: Provide more byte array constructors for BigInteger
bpb
parents: 25859
diff changeset
   307
    public BigInteger(byte[] val, int off, int len) {
45f25a2cf942 4026465: Provide more byte array constructors for BigInteger
bpb
parents: 25859
diff changeset
   308
        if (val.length == 0) {
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   309
            throw new NumberFormatException("Zero length BigInteger");
28309
45f25a2cf942 4026465: Provide more byte array constructors for BigInteger
bpb
parents: 25859
diff changeset
   310
        } else if ((off < 0) || (off >= val.length) || (len < 0) ||
45f25a2cf942 4026465: Provide more byte array constructors for BigInteger
bpb
parents: 25859
diff changeset
   311
                   (len > val.length - off)) { // 0 <= off < val.length
45f25a2cf942 4026465: Provide more byte array constructors for BigInteger
bpb
parents: 25859
diff changeset
   312
            throw new IndexOutOfBoundsException();
45f25a2cf942 4026465: Provide more byte array constructors for BigInteger
bpb
parents: 25859
diff changeset
   313
        }
45f25a2cf942 4026465: Provide more byte array constructors for BigInteger
bpb
parents: 25859
diff changeset
   314
45f25a2cf942 4026465: Provide more byte array constructors for BigInteger
bpb
parents: 25859
diff changeset
   315
        if (val[off] < 0) {
45f25a2cf942 4026465: Provide more byte array constructors for BigInteger
bpb
parents: 25859
diff changeset
   316
            mag = makePositive(val, off, len);
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   317
            signum = -1;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   318
        } else {
28309
45f25a2cf942 4026465: Provide more byte array constructors for BigInteger
bpb
parents: 25859
diff changeset
   319
            mag = stripLeadingZeroBytes(val, off, len);
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   320
            signum = (mag.length == 0 ? 0 : 1);
90ce3da70b43 Initial load
duke
parents:
diff changeset
   321
        }
21420
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
   322
        if (mag.length >= MAX_MAG_LENGTH) {
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
   323
            checkRange();
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
   324
        }
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   325
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   326
90ce3da70b43 Initial load
duke
parents:
diff changeset
   327
    /**
28309
45f25a2cf942 4026465: Provide more byte array constructors for BigInteger
bpb
parents: 25859
diff changeset
   328
     * Translates a byte array containing the two's-complement binary
45f25a2cf942 4026465: Provide more byte array constructors for BigInteger
bpb
parents: 25859
diff changeset
   329
     * representation of a BigInteger into a BigInteger.  The input array is
45f25a2cf942 4026465: Provide more byte array constructors for BigInteger
bpb
parents: 25859
diff changeset
   330
     * assumed to be in <i>big-endian</i> byte-order: the most significant
45f25a2cf942 4026465: Provide more byte array constructors for BigInteger
bpb
parents: 25859
diff changeset
   331
     * byte is in the zeroth element.  The {@code val} array is assumed to be
45f25a2cf942 4026465: Provide more byte array constructors for BigInteger
bpb
parents: 25859
diff changeset
   332
     * unchanged for the duration of the constructor call.
45f25a2cf942 4026465: Provide more byte array constructors for BigInteger
bpb
parents: 25859
diff changeset
   333
     *
45f25a2cf942 4026465: Provide more byte array constructors for BigInteger
bpb
parents: 25859
diff changeset
   334
     * @param  val big-endian two's-complement binary representation of a
45f25a2cf942 4026465: Provide more byte array constructors for BigInteger
bpb
parents: 25859
diff changeset
   335
     *         BigInteger.
45f25a2cf942 4026465: Provide more byte array constructors for BigInteger
bpb
parents: 25859
diff changeset
   336
     * @throws NumberFormatException {@code val} is zero bytes long.
45f25a2cf942 4026465: Provide more byte array constructors for BigInteger
bpb
parents: 25859
diff changeset
   337
     */
45f25a2cf942 4026465: Provide more byte array constructors for BigInteger
bpb
parents: 25859
diff changeset
   338
    public BigInteger(byte[] val) {
45f25a2cf942 4026465: Provide more byte array constructors for BigInteger
bpb
parents: 25859
diff changeset
   339
        this(val, 0, val.length);
45f25a2cf942 4026465: Provide more byte array constructors for BigInteger
bpb
parents: 25859
diff changeset
   340
    }
45f25a2cf942 4026465: Provide more byte array constructors for BigInteger
bpb
parents: 25859
diff changeset
   341
45f25a2cf942 4026465: Provide more byte array constructors for BigInteger
bpb
parents: 25859
diff changeset
   342
    /**
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   343
     * This private constructor translates an int array containing the
90ce3da70b43 Initial load
duke
parents:
diff changeset
   344
     * two's-complement binary representation of a BigInteger into a
90ce3da70b43 Initial load
duke
parents:
diff changeset
   345
     * BigInteger. The input array is assumed to be in <i>big-endian</i>
28309
45f25a2cf942 4026465: Provide more byte array constructors for BigInteger
bpb
parents: 25859
diff changeset
   346
     * int-order: the most significant int is in the zeroth element.  The
45f25a2cf942 4026465: Provide more byte array constructors for BigInteger
bpb
parents: 25859
diff changeset
   347
     * {@code val} array is assumed to be unchanged for the duration of
45f25a2cf942 4026465: Provide more byte array constructors for BigInteger
bpb
parents: 25859
diff changeset
   348
     * the constructor call.
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   349
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
   350
    private BigInteger(int[] val) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   351
        if (val.length == 0)
90ce3da70b43 Initial load
duke
parents:
diff changeset
   352
            throw new NumberFormatException("Zero length BigInteger");
90ce3da70b43 Initial load
duke
parents:
diff changeset
   353
90ce3da70b43 Initial load
duke
parents:
diff changeset
   354
        if (val[0] < 0) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   355
            mag = makePositive(val);
90ce3da70b43 Initial load
duke
parents:
diff changeset
   356
            signum = -1;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   357
        } else {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   358
            mag = trustedStripLeadingZeroInts(val);
90ce3da70b43 Initial load
duke
parents:
diff changeset
   359
            signum = (mag.length == 0 ? 0 : 1);
90ce3da70b43 Initial load
duke
parents:
diff changeset
   360
        }
21420
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
   361
        if (mag.length >= MAX_MAG_LENGTH) {
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
   362
            checkRange();
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
   363
        }
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   364
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   365
90ce3da70b43 Initial load
duke
parents:
diff changeset
   366
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
   367
     * Translates the sign-magnitude representation of a BigInteger into a
90ce3da70b43 Initial load
duke
parents:
diff changeset
   368
     * BigInteger.  The sign is represented as an integer signum value: -1 for
28309
45f25a2cf942 4026465: Provide more byte array constructors for BigInteger
bpb
parents: 25859
diff changeset
   369
     * negative, 0 for zero, or 1 for positive.  The magnitude is a sub-array of
45f25a2cf942 4026465: Provide more byte array constructors for BigInteger
bpb
parents: 25859
diff changeset
   370
     * a byte array in <i>big-endian</i> byte-order: the most significant byte
45f25a2cf942 4026465: Provide more byte array constructors for BigInteger
bpb
parents: 25859
diff changeset
   371
     * is the element at index {@code off}.  A zero value of the length
45f25a2cf942 4026465: Provide more byte array constructors for BigInteger
bpb
parents: 25859
diff changeset
   372
     * {@code len} is permissible, and will result in a BigInteger value of 0,
45f25a2cf942 4026465: Provide more byte array constructors for BigInteger
bpb
parents: 25859
diff changeset
   373
     * whether signum is -1, 0 or 1.  The {@code magnitude} array is assumed to
45f25a2cf942 4026465: Provide more byte array constructors for BigInteger
bpb
parents: 25859
diff changeset
   374
     * be unchanged for the duration of the constructor call.
45f25a2cf942 4026465: Provide more byte array constructors for BigInteger
bpb
parents: 25859
diff changeset
   375
     *
45f25a2cf942 4026465: Provide more byte array constructors for BigInteger
bpb
parents: 25859
diff changeset
   376
     * An {@code IndexOutOfBoundsException} is thrown if the length of the array
45f25a2cf942 4026465: Provide more byte array constructors for BigInteger
bpb
parents: 25859
diff changeset
   377
     * {@code magnitude} is non-zero and either {@code off} is negative,
45f25a2cf942 4026465: Provide more byte array constructors for BigInteger
bpb
parents: 25859
diff changeset
   378
     * {@code len} is negative, or {@code off+len} is greater than the length of
45f25a2cf942 4026465: Provide more byte array constructors for BigInteger
bpb
parents: 25859
diff changeset
   379
     * {@code magnitude}.
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   380
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
   381
     * @param  signum signum of the number (-1 for negative, 0 for zero, 1
90ce3da70b43 Initial load
duke
parents:
diff changeset
   382
     *         for positive).
90ce3da70b43 Initial load
duke
parents:
diff changeset
   383
     * @param  magnitude big-endian binary representation of the magnitude of
90ce3da70b43 Initial load
duke
parents:
diff changeset
   384
     *         the number.
28309
45f25a2cf942 4026465: Provide more byte array constructors for BigInteger
bpb
parents: 25859
diff changeset
   385
     * @param  off the start offset of the binary representation.
45f25a2cf942 4026465: Provide more byte array constructors for BigInteger
bpb
parents: 25859
diff changeset
   386
     * @param  len the number of bytes to use.
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   387
     * @throws NumberFormatException {@code signum} is not one of the three
90ce3da70b43 Initial load
duke
parents:
diff changeset
   388
     *         legal values (-1, 0, and 1), or {@code signum} is 0 and
90ce3da70b43 Initial load
duke
parents:
diff changeset
   389
     *         {@code magnitude} contains one or more non-zero bytes.
28309
45f25a2cf942 4026465: Provide more byte array constructors for BigInteger
bpb
parents: 25859
diff changeset
   390
     * @throws IndexOutOfBoundsException if the provided array offset and
45f25a2cf942 4026465: Provide more byte array constructors for BigInteger
bpb
parents: 25859
diff changeset
   391
     *         length would cause an index into the byte array to be
45f25a2cf942 4026465: Provide more byte array constructors for BigInteger
bpb
parents: 25859
diff changeset
   392
     *         negative or greater than or equal to the array length.
35302
e4d2275861c3 8136494: Update "@since 1.9" to "@since 9" to match java.version.specification
iris
parents: 34781
diff changeset
   393
     * @since 9
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   394
     */
28309
45f25a2cf942 4026465: Provide more byte array constructors for BigInteger
bpb
parents: 25859
diff changeset
   395
    public BigInteger(int signum, byte[] magnitude, int off, int len) {
45f25a2cf942 4026465: Provide more byte array constructors for BigInteger
bpb
parents: 25859
diff changeset
   396
        if (signum < -1 || signum > 1) {
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   397
            throw(new NumberFormatException("Invalid signum value"));
28309
45f25a2cf942 4026465: Provide more byte array constructors for BigInteger
bpb
parents: 25859
diff changeset
   398
        } else if ((off < 0) || (len < 0) ||
45f25a2cf942 4026465: Provide more byte array constructors for BigInteger
bpb
parents: 25859
diff changeset
   399
            (len > 0 &&
45f25a2cf942 4026465: Provide more byte array constructors for BigInteger
bpb
parents: 25859
diff changeset
   400
                ((off >= magnitude.length) ||
45f25a2cf942 4026465: Provide more byte array constructors for BigInteger
bpb
parents: 25859
diff changeset
   401
                 (len > magnitude.length - off)))) { // 0 <= off < magnitude.length
45f25a2cf942 4026465: Provide more byte array constructors for BigInteger
bpb
parents: 25859
diff changeset
   402
            throw new IndexOutOfBoundsException();
45f25a2cf942 4026465: Provide more byte array constructors for BigInteger
bpb
parents: 25859
diff changeset
   403
        }
45f25a2cf942 4026465: Provide more byte array constructors for BigInteger
bpb
parents: 25859
diff changeset
   404
45f25a2cf942 4026465: Provide more byte array constructors for BigInteger
bpb
parents: 25859
diff changeset
   405
        // stripLeadingZeroBytes() returns a zero length array if len == 0
45f25a2cf942 4026465: Provide more byte array constructors for BigInteger
bpb
parents: 25859
diff changeset
   406
        this.mag = stripLeadingZeroBytes(magnitude, off, len);
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   407
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
   408
        if (this.mag.length == 0) {
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   409
            this.signum = 0;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   410
        } else {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   411
            if (signum == 0)
90ce3da70b43 Initial load
duke
parents:
diff changeset
   412
                throw(new NumberFormatException("signum-magnitude mismatch"));
90ce3da70b43 Initial load
duke
parents:
diff changeset
   413
            this.signum = signum;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   414
        }
21420
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
   415
        if (mag.length >= MAX_MAG_LENGTH) {
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
   416
            checkRange();
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
   417
        }
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   418
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   419
90ce3da70b43 Initial load
duke
parents:
diff changeset
   420
    /**
28309
45f25a2cf942 4026465: Provide more byte array constructors for BigInteger
bpb
parents: 25859
diff changeset
   421
     * Translates the sign-magnitude representation of a BigInteger into a
45f25a2cf942 4026465: Provide more byte array constructors for BigInteger
bpb
parents: 25859
diff changeset
   422
     * BigInteger.  The sign is represented as an integer signum value: -1 for
45f25a2cf942 4026465: Provide more byte array constructors for BigInteger
bpb
parents: 25859
diff changeset
   423
     * negative, 0 for zero, or 1 for positive.  The magnitude is a byte array
45f25a2cf942 4026465: Provide more byte array constructors for BigInteger
bpb
parents: 25859
diff changeset
   424
     * in <i>big-endian</i> byte-order: the most significant byte is the
45f25a2cf942 4026465: Provide more byte array constructors for BigInteger
bpb
parents: 25859
diff changeset
   425
     * zeroth element.  A zero-length magnitude array is permissible, and will
45f25a2cf942 4026465: Provide more byte array constructors for BigInteger
bpb
parents: 25859
diff changeset
   426
     * result in a BigInteger value of 0, whether signum is -1, 0 or 1.  The
45f25a2cf942 4026465: Provide more byte array constructors for BigInteger
bpb
parents: 25859
diff changeset
   427
     * {@code magnitude} array is assumed to be unchanged for the duration of
45f25a2cf942 4026465: Provide more byte array constructors for BigInteger
bpb
parents: 25859
diff changeset
   428
     * the constructor call.
45f25a2cf942 4026465: Provide more byte array constructors for BigInteger
bpb
parents: 25859
diff changeset
   429
     *
45f25a2cf942 4026465: Provide more byte array constructors for BigInteger
bpb
parents: 25859
diff changeset
   430
     * @param  signum signum of the number (-1 for negative, 0 for zero, 1
45f25a2cf942 4026465: Provide more byte array constructors for BigInteger
bpb
parents: 25859
diff changeset
   431
     *         for positive).
45f25a2cf942 4026465: Provide more byte array constructors for BigInteger
bpb
parents: 25859
diff changeset
   432
     * @param  magnitude big-endian binary representation of the magnitude of
45f25a2cf942 4026465: Provide more byte array constructors for BigInteger
bpb
parents: 25859
diff changeset
   433
     *         the number.
45f25a2cf942 4026465: Provide more byte array constructors for BigInteger
bpb
parents: 25859
diff changeset
   434
     * @throws NumberFormatException {@code signum} is not one of the three
45f25a2cf942 4026465: Provide more byte array constructors for BigInteger
bpb
parents: 25859
diff changeset
   435
     *         legal values (-1, 0, and 1), or {@code signum} is 0 and
45f25a2cf942 4026465: Provide more byte array constructors for BigInteger
bpb
parents: 25859
diff changeset
   436
     *         {@code magnitude} contains one or more non-zero bytes.
45f25a2cf942 4026465: Provide more byte array constructors for BigInteger
bpb
parents: 25859
diff changeset
   437
     */
45f25a2cf942 4026465: Provide more byte array constructors for BigInteger
bpb
parents: 25859
diff changeset
   438
    public BigInteger(int signum, byte[] magnitude) {
45f25a2cf942 4026465: Provide more byte array constructors for BigInteger
bpb
parents: 25859
diff changeset
   439
         this(signum, magnitude, 0, magnitude.length);
45f25a2cf942 4026465: Provide more byte array constructors for BigInteger
bpb
parents: 25859
diff changeset
   440
    }
45f25a2cf942 4026465: Provide more byte array constructors for BigInteger
bpb
parents: 25859
diff changeset
   441
45f25a2cf942 4026465: Provide more byte array constructors for BigInteger
bpb
parents: 25859
diff changeset
   442
    /**
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   443
     * A constructor for internal use that translates the sign-magnitude
90ce3da70b43 Initial load
duke
parents:
diff changeset
   444
     * representation of a BigInteger into a BigInteger. It checks the
90ce3da70b43 Initial load
duke
parents:
diff changeset
   445
     * arguments and copies the magnitude so this constructor would be
28309
45f25a2cf942 4026465: Provide more byte array constructors for BigInteger
bpb
parents: 25859
diff changeset
   446
     * safe for external use.  The {@code magnitude} array is assumed to be
45f25a2cf942 4026465: Provide more byte array constructors for BigInteger
bpb
parents: 25859
diff changeset
   447
     * unchanged for the duration of the constructor call.
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   448
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
   449
    private BigInteger(int signum, int[] magnitude) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   450
        this.mag = stripLeadingZeroInts(magnitude);
90ce3da70b43 Initial load
duke
parents:
diff changeset
   451
90ce3da70b43 Initial load
duke
parents:
diff changeset
   452
        if (signum < -1 || signum > 1)
90ce3da70b43 Initial load
duke
parents:
diff changeset
   453
            throw(new NumberFormatException("Invalid signum value"));
90ce3da70b43 Initial load
duke
parents:
diff changeset
   454
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
   455
        if (this.mag.length == 0) {
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   456
            this.signum = 0;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   457
        } else {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   458
            if (signum == 0)
90ce3da70b43 Initial load
duke
parents:
diff changeset
   459
                throw(new NumberFormatException("signum-magnitude mismatch"));
90ce3da70b43 Initial load
duke
parents:
diff changeset
   460
            this.signum = signum;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   461
        }
21420
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
   462
        if (mag.length >= MAX_MAG_LENGTH) {
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
   463
            checkRange();
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
   464
        }
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   465
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   466
90ce3da70b43 Initial load
duke
parents:
diff changeset
   467
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
   468
     * Translates the String representation of a BigInteger in the
90ce3da70b43 Initial load
duke
parents:
diff changeset
   469
     * specified radix into a BigInteger.  The String representation
90ce3da70b43 Initial load
duke
parents:
diff changeset
   470
     * consists of an optional minus or plus sign followed by a
90ce3da70b43 Initial load
duke
parents:
diff changeset
   471
     * sequence of one or more digits in the specified radix.  The
90ce3da70b43 Initial load
duke
parents:
diff changeset
   472
     * character-to-digit mapping is provided by {@code
90ce3da70b43 Initial load
duke
parents:
diff changeset
   473
     * Character.digit}.  The String may not contain any extraneous
90ce3da70b43 Initial load
duke
parents:
diff changeset
   474
     * characters (whitespace, for example).
90ce3da70b43 Initial load
duke
parents:
diff changeset
   475
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
   476
     * @param val String representation of BigInteger.
90ce3da70b43 Initial load
duke
parents:
diff changeset
   477
     * @param radix radix to be used in interpreting {@code val}.
90ce3da70b43 Initial load
duke
parents:
diff changeset
   478
     * @throws NumberFormatException {@code val} is not a valid representation
90ce3da70b43 Initial load
duke
parents:
diff changeset
   479
     *         of a BigInteger in the specified radix, or {@code radix} is
90ce3da70b43 Initial load
duke
parents:
diff changeset
   480
     *         outside the range from {@link Character#MIN_RADIX} to
90ce3da70b43 Initial load
duke
parents:
diff changeset
   481
     *         {@link Character#MAX_RADIX}, inclusive.
90ce3da70b43 Initial load
duke
parents:
diff changeset
   482
     * @see    Character#digit
90ce3da70b43 Initial load
duke
parents:
diff changeset
   483
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
   484
    public BigInteger(String val, int radix) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   485
        int cursor = 0, numDigits;
4182
ffdc79c88a0e 6897550: BigInteger constructor should use local cached String length
darcy
parents: 4160
diff changeset
   486
        final int len = val.length();
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   487
90ce3da70b43 Initial load
duke
parents:
diff changeset
   488
        if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX)
90ce3da70b43 Initial load
duke
parents:
diff changeset
   489
            throw new NumberFormatException("Radix out of range");
4182
ffdc79c88a0e 6897550: BigInteger constructor should use local cached String length
darcy
parents: 4160
diff changeset
   490
        if (len == 0)
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   491
            throw new NumberFormatException("Zero length BigInteger");
90ce3da70b43 Initial load
duke
parents:
diff changeset
   492
90ce3da70b43 Initial load
duke
parents:
diff changeset
   493
        // Check for at most one leading sign
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
   494
        int sign = 1;
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   495
        int index1 = val.lastIndexOf('-');
90ce3da70b43 Initial load
duke
parents:
diff changeset
   496
        int index2 = val.lastIndexOf('+');
21420
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
   497
        if (index1 >= 0) {
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
   498
            if (index1 != 0 || index2 >= 0) {
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
   499
                throw new NumberFormatException("Illegal embedded sign character");
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   500
            }
21420
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
   501
            sign = -1;
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
   502
            cursor = 1;
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
   503
        } else if (index2 >= 0) {
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
   504
            if (index2 != 0) {
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
   505
                throw new NumberFormatException("Illegal embedded sign character");
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
   506
            }
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
   507
            cursor = 1;
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
   508
        }
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
   509
        if (cursor == len)
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
   510
            throw new NumberFormatException("Zero length BigInteger");
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   511
90ce3da70b43 Initial load
duke
parents:
diff changeset
   512
        // Skip leading zeros and compute number of digits in magnitude
90ce3da70b43 Initial load
duke
parents:
diff changeset
   513
        while (cursor < len &&
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
   514
               Character.digit(val.charAt(cursor), radix) == 0) {
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   515
            cursor++;
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
   516
        }
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
   517
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   518
        if (cursor == len) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   519
            signum = 0;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   520
            mag = ZERO.mag;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   521
            return;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   522
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   523
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
   524
        numDigits = len - cursor;
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
   525
        signum = sign;
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
   526
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   527
        // Pre-allocate array of expected size. May be too large but can
90ce3da70b43 Initial load
duke
parents:
diff changeset
   528
        // never be too small. Typically exact.
21420
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
   529
        long numBits = ((numDigits * bitsPerDigit[radix]) >>> 10) + 1;
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
   530
        if (numBits + 31 >= (1L << 32)) {
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
   531
            reportOverflow();
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
   532
        }
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
   533
        int numWords = (int) (numBits + 31) >>> 5;
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
   534
        int[] magnitude = new int[numWords];
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   535
90ce3da70b43 Initial load
duke
parents:
diff changeset
   536
        // Process first (potentially short) digit group
90ce3da70b43 Initial load
duke
parents:
diff changeset
   537
        int firstGroupLen = numDigits % digitsPerInt[radix];
90ce3da70b43 Initial load
duke
parents:
diff changeset
   538
        if (firstGroupLen == 0)
90ce3da70b43 Initial load
duke
parents:
diff changeset
   539
            firstGroupLen = digitsPerInt[radix];
90ce3da70b43 Initial load
duke
parents:
diff changeset
   540
        String group = val.substring(cursor, cursor += firstGroupLen);
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
   541
        magnitude[numWords - 1] = Integer.parseInt(group, radix);
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
   542
        if (magnitude[numWords - 1] < 0)
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   543
            throw new NumberFormatException("Illegal digit");
90ce3da70b43 Initial load
duke
parents:
diff changeset
   544
90ce3da70b43 Initial load
duke
parents:
diff changeset
   545
        // Process remaining digit groups
90ce3da70b43 Initial load
duke
parents:
diff changeset
   546
        int superRadix = intRadix[radix];
90ce3da70b43 Initial load
duke
parents:
diff changeset
   547
        int groupVal = 0;
4182
ffdc79c88a0e 6897550: BigInteger constructor should use local cached String length
darcy
parents: 4160
diff changeset
   548
        while (cursor < len) {
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   549
            group = val.substring(cursor, cursor += digitsPerInt[radix]);
90ce3da70b43 Initial load
duke
parents:
diff changeset
   550
            groupVal = Integer.parseInt(group, radix);
90ce3da70b43 Initial load
duke
parents:
diff changeset
   551
            if (groupVal < 0)
90ce3da70b43 Initial load
duke
parents:
diff changeset
   552
                throw new NumberFormatException("Illegal digit");
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
   553
            destructiveMulAdd(magnitude, superRadix, groupVal);
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   554
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   555
        // Required for cases where the array was overallocated.
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
   556
        mag = trustedStripLeadingZeroInts(magnitude);
21420
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
   557
        if (mag.length >= MAX_MAG_LENGTH) {
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
   558
            checkRange();
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
   559
        }
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   560
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   561
10423
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
   562
    /*
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
   563
     * Constructs a new BigInteger using a char array with radix=10.
28309
45f25a2cf942 4026465: Provide more byte array constructors for BigInteger
bpb
parents: 25859
diff changeset
   564
     * Sign is precalculated outside and not allowed in the val. The {@code val}
45f25a2cf942 4026465: Provide more byte array constructors for BigInteger
bpb
parents: 25859
diff changeset
   565
     * array is assumed to be unchanged for the duration of the constructor
45f25a2cf942 4026465: Provide more byte array constructors for BigInteger
bpb
parents: 25859
diff changeset
   566
     * call.
10423
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
   567
     */
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
   568
    BigInteger(char[] val, int sign, int len) {
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   569
        int cursor = 0, numDigits;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   570
90ce3da70b43 Initial load
duke
parents:
diff changeset
   571
        // Skip leading zeros and compute number of digits in magnitude
10423
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
   572
        while (cursor < len && Character.digit(val[cursor], 10) == 0) {
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   573
            cursor++;
10423
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
   574
        }
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   575
        if (cursor == len) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   576
            signum = 0;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   577
            mag = ZERO.mag;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   578
            return;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   579
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   580
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
   581
        numDigits = len - cursor;
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
   582
        signum = sign;
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   583
        // Pre-allocate array of expected size
90ce3da70b43 Initial load
duke
parents:
diff changeset
   584
        int numWords;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   585
        if (len < 10) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   586
            numWords = 1;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   587
        } else {
21420
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
   588
            long numBits = ((numDigits * bitsPerDigit[10]) >>> 10) + 1;
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
   589
            if (numBits + 31 >= (1L << 32)) {
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
   590
                reportOverflow();
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
   591
            }
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
   592
            numWords = (int) (numBits + 31) >>> 5;
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   593
        }
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
   594
        int[] magnitude = new int[numWords];
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   595
90ce3da70b43 Initial load
duke
parents:
diff changeset
   596
        // Process first (potentially short) digit group
90ce3da70b43 Initial load
duke
parents:
diff changeset
   597
        int firstGroupLen = numDigits % digitsPerInt[10];
90ce3da70b43 Initial load
duke
parents:
diff changeset
   598
        if (firstGroupLen == 0)
90ce3da70b43 Initial load
duke
parents:
diff changeset
   599
            firstGroupLen = digitsPerInt[10];
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
   600
        magnitude[numWords - 1] = parseInt(val, cursor,  cursor += firstGroupLen);
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   601
90ce3da70b43 Initial load
duke
parents:
diff changeset
   602
        // Process remaining digit groups
90ce3da70b43 Initial load
duke
parents:
diff changeset
   603
        while (cursor < len) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   604
            int groupVal = parseInt(val, cursor, cursor += digitsPerInt[10]);
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
   605
            destructiveMulAdd(magnitude, intRadix[10], groupVal);
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   606
        }
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
   607
        mag = trustedStripLeadingZeroInts(magnitude);
21420
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
   608
        if (mag.length >= MAX_MAG_LENGTH) {
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
   609
            checkRange();
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
   610
        }
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   611
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   612
90ce3da70b43 Initial load
duke
parents:
diff changeset
   613
    // Create an integer with the digits between the two indexes
90ce3da70b43 Initial load
duke
parents:
diff changeset
   614
    // Assumes start < end. The result may be negative, but it
90ce3da70b43 Initial load
duke
parents:
diff changeset
   615
    // is to be treated as an unsigned value.
90ce3da70b43 Initial load
duke
parents:
diff changeset
   616
    private int parseInt(char[] source, int start, int end) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   617
        int result = Character.digit(source[start++], 10);
90ce3da70b43 Initial load
duke
parents:
diff changeset
   618
        if (result == -1)
90ce3da70b43 Initial load
duke
parents:
diff changeset
   619
            throw new NumberFormatException(new String(source));
90ce3da70b43 Initial load
duke
parents:
diff changeset
   620
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
   621
        for (int index = start; index < end; index++) {
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   622
            int nextVal = Character.digit(source[index], 10);
90ce3da70b43 Initial load
duke
parents:
diff changeset
   623
            if (nextVal == -1)
90ce3da70b43 Initial load
duke
parents:
diff changeset
   624
                throw new NumberFormatException(new String(source));
90ce3da70b43 Initial load
duke
parents:
diff changeset
   625
            result = 10*result + nextVal;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   626
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   627
90ce3da70b43 Initial load
duke
parents:
diff changeset
   628
        return result;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   629
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   630
90ce3da70b43 Initial load
duke
parents:
diff changeset
   631
    // bitsPerDigit in the given radix times 1024
90ce3da70b43 Initial load
duke
parents:
diff changeset
   632
    // Rounded up to avoid underallocation.
90ce3da70b43 Initial load
duke
parents:
diff changeset
   633
    private static long bitsPerDigit[] = { 0, 0,
90ce3da70b43 Initial load
duke
parents:
diff changeset
   634
        1024, 1624, 2048, 2378, 2648, 2875, 3072, 3247, 3402, 3543, 3672,
90ce3da70b43 Initial load
duke
parents:
diff changeset
   635
        3790, 3899, 4001, 4096, 4186, 4271, 4350, 4426, 4498, 4567, 4633,
90ce3da70b43 Initial load
duke
parents:
diff changeset
   636
        4696, 4756, 4814, 4870, 4923, 4975, 5025, 5074, 5120, 5166, 5210,
90ce3da70b43 Initial load
duke
parents:
diff changeset
   637
                                           5253, 5295};
90ce3da70b43 Initial load
duke
parents:
diff changeset
   638
90ce3da70b43 Initial load
duke
parents:
diff changeset
   639
    // Multiply x array times word y in place, and add word z
90ce3da70b43 Initial load
duke
parents:
diff changeset
   640
    private static void destructiveMulAdd(int[] x, int y, int z) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   641
        // Perform the multiplication word by word
90ce3da70b43 Initial load
duke
parents:
diff changeset
   642
        long ylong = y & LONG_MASK;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   643
        long zlong = z & LONG_MASK;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   644
        int len = x.length;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   645
90ce3da70b43 Initial load
duke
parents:
diff changeset
   646
        long product = 0;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   647
        long carry = 0;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   648
        for (int i = len-1; i >= 0; i--) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   649
            product = ylong * (x[i] & LONG_MASK) + carry;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   650
            x[i] = (int)product;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   651
            carry = product >>> 32;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   652
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   653
90ce3da70b43 Initial load
duke
parents:
diff changeset
   654
        // Perform the addition
90ce3da70b43 Initial load
duke
parents:
diff changeset
   655
        long sum = (x[len-1] & LONG_MASK) + zlong;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   656
        x[len-1] = (int)sum;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   657
        carry = sum >>> 32;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   658
        for (int i = len-2; i >= 0; i--) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   659
            sum = (x[i] & LONG_MASK) + carry;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   660
            x[i] = (int)sum;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   661
            carry = sum >>> 32;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   662
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   663
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   664
90ce3da70b43 Initial load
duke
parents:
diff changeset
   665
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
   666
     * Translates the decimal String representation of a BigInteger into a
90ce3da70b43 Initial load
duke
parents:
diff changeset
   667
     * BigInteger.  The String representation consists of an optional minus
90ce3da70b43 Initial load
duke
parents:
diff changeset
   668
     * sign followed by a sequence of one or more decimal digits.  The
90ce3da70b43 Initial load
duke
parents:
diff changeset
   669
     * character-to-digit mapping is provided by {@code Character.digit}.
90ce3da70b43 Initial load
duke
parents:
diff changeset
   670
     * The String may not contain any extraneous characters (whitespace, for
90ce3da70b43 Initial load
duke
parents:
diff changeset
   671
     * example).
90ce3da70b43 Initial load
duke
parents:
diff changeset
   672
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
   673
     * @param val decimal String representation of BigInteger.
90ce3da70b43 Initial load
duke
parents:
diff changeset
   674
     * @throws NumberFormatException {@code val} is not a valid representation
90ce3da70b43 Initial load
duke
parents:
diff changeset
   675
     *         of a BigInteger.
90ce3da70b43 Initial load
duke
parents:
diff changeset
   676
     * @see    Character#digit
90ce3da70b43 Initial load
duke
parents:
diff changeset
   677
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
   678
    public BigInteger(String val) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   679
        this(val, 10);
90ce3da70b43 Initial load
duke
parents:
diff changeset
   680
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   681
90ce3da70b43 Initial load
duke
parents:
diff changeset
   682
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
   683
     * Constructs a randomly generated BigInteger, uniformly distributed over
4160
bda0a85afcb7 6560935: BigInteger.modPow() throws ArithmeticException for negative exponent
darcy
parents: 4151
diff changeset
   684
     * the range 0 to (2<sup>{@code numBits}</sup> - 1), inclusive.
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   685
     * The uniformity of the distribution assumes that a fair source of random
90ce3da70b43 Initial load
duke
parents:
diff changeset
   686
     * bits is provided in {@code rnd}.  Note that this constructor always
90ce3da70b43 Initial load
duke
parents:
diff changeset
   687
     * constructs a non-negative BigInteger.
90ce3da70b43 Initial load
duke
parents:
diff changeset
   688
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
   689
     * @param  numBits maximum bitLength of the new BigInteger.
90ce3da70b43 Initial load
duke
parents:
diff changeset
   690
     * @param  rnd source of randomness to be used in computing the new
90ce3da70b43 Initial load
duke
parents:
diff changeset
   691
     *         BigInteger.
90ce3da70b43 Initial load
duke
parents:
diff changeset
   692
     * @throws IllegalArgumentException {@code numBits} is negative.
90ce3da70b43 Initial load
duke
parents:
diff changeset
   693
     * @see #bitLength()
90ce3da70b43 Initial load
duke
parents:
diff changeset
   694
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
   695
    public BigInteger(int numBits, Random rnd) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   696
        this(1, randomBits(numBits, rnd));
90ce3da70b43 Initial load
duke
parents:
diff changeset
   697
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   698
90ce3da70b43 Initial load
duke
parents:
diff changeset
   699
    private static byte[] randomBits(int numBits, Random rnd) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   700
        if (numBits < 0)
90ce3da70b43 Initial load
duke
parents:
diff changeset
   701
            throw new IllegalArgumentException("numBits must be non-negative");
90ce3da70b43 Initial load
duke
parents:
diff changeset
   702
        int numBytes = (int)(((long)numBits+7)/8); // avoid overflow
90ce3da70b43 Initial load
duke
parents:
diff changeset
   703
        byte[] randomBits = new byte[numBytes];
90ce3da70b43 Initial load
duke
parents:
diff changeset
   704
90ce3da70b43 Initial load
duke
parents:
diff changeset
   705
        // Generate random bytes and mask out any excess bits
90ce3da70b43 Initial load
duke
parents:
diff changeset
   706
        if (numBytes > 0) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   707
            rnd.nextBytes(randomBits);
90ce3da70b43 Initial load
duke
parents:
diff changeset
   708
            int excessBits = 8*numBytes - numBits;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   709
            randomBits[0] &= (1 << (8-excessBits)) - 1;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   710
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   711
        return randomBits;
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
     * Constructs a randomly generated positive BigInteger that is probably
90ce3da70b43 Initial load
duke
parents:
diff changeset
   716
     * prime, with the specified bitLength.
90ce3da70b43 Initial load
duke
parents:
diff changeset
   717
     *
38553
0553095041d7 8157724: Improve javadoc tag usage in java.math
darcy
parents: 37880
diff changeset
   718
     * @apiNote It is recommended that the {@link #probablePrime probablePrime}
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   719
     * method be used in preference to this constructor unless there
90ce3da70b43 Initial load
duke
parents:
diff changeset
   720
     * is a compelling need to specify a certainty.
90ce3da70b43 Initial load
duke
parents:
diff changeset
   721
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
   722
     * @param  bitLength bitLength of the returned BigInteger.
90ce3da70b43 Initial load
duke
parents:
diff changeset
   723
     * @param  certainty a measure of the uncertainty that the caller is
90ce3da70b43 Initial load
duke
parents:
diff changeset
   724
     *         willing to tolerate.  The probability that the new BigInteger
90ce3da70b43 Initial load
duke
parents:
diff changeset
   725
     *         represents a prime number will exceed
90ce3da70b43 Initial load
duke
parents:
diff changeset
   726
     *         (1 - 1/2<sup>{@code certainty}</sup>).  The execution time of
90ce3da70b43 Initial load
duke
parents:
diff changeset
   727
     *         this constructor is proportional to the value of this parameter.
90ce3da70b43 Initial load
duke
parents:
diff changeset
   728
     * @param  rnd source of random bits used to select candidates to be
90ce3da70b43 Initial load
duke
parents:
diff changeset
   729
     *         tested for primality.
21420
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
   730
     * @throws ArithmeticException {@code bitLength < 2} or {@code bitLength} is too large.
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   731
     * @see    #bitLength()
90ce3da70b43 Initial load
duke
parents:
diff changeset
   732
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
   733
    public BigInteger(int bitLength, int certainty, Random rnd) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   734
        BigInteger prime;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   735
90ce3da70b43 Initial load
duke
parents:
diff changeset
   736
        if (bitLength < 2)
90ce3da70b43 Initial load
duke
parents:
diff changeset
   737
            throw new ArithmeticException("bitLength < 2");
18286
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
   738
        prime = (bitLength < SMALL_PRIME_THRESHOLD
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
   739
                                ? smallPrime(bitLength, certainty, rnd)
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   740
                                : largePrime(bitLength, certainty, rnd));
90ce3da70b43 Initial load
duke
parents:
diff changeset
   741
        signum = 1;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   742
        mag = prime.mag;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   743
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   744
90ce3da70b43 Initial load
duke
parents:
diff changeset
   745
    // Minimum size in bits that the requested prime number has
18286
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
   746
    // before we use the large prime number generating algorithms.
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
   747
    // The cutoff of 95 was chosen empirically for best performance.
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   748
    private static final int SMALL_PRIME_THRESHOLD = 95;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   749
90ce3da70b43 Initial load
duke
parents:
diff changeset
   750
    // Certainty required to meet the spec of probablePrime
90ce3da70b43 Initial load
duke
parents:
diff changeset
   751
    private static final int DEFAULT_PRIME_CERTAINTY = 100;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   752
90ce3da70b43 Initial load
duke
parents:
diff changeset
   753
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
   754
     * Returns a positive BigInteger that is probably prime, with the
90ce3da70b43 Initial load
duke
parents:
diff changeset
   755
     * specified bitLength. The probability that a BigInteger returned
90ce3da70b43 Initial load
duke
parents:
diff changeset
   756
     * by this method is composite does not exceed 2<sup>-100</sup>.
90ce3da70b43 Initial load
duke
parents:
diff changeset
   757
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
   758
     * @param  bitLength bitLength of the returned BigInteger.
90ce3da70b43 Initial load
duke
parents:
diff changeset
   759
     * @param  rnd source of random bits used to select candidates to be
90ce3da70b43 Initial load
duke
parents:
diff changeset
   760
     *         tested for primality.
90ce3da70b43 Initial load
duke
parents:
diff changeset
   761
     * @return a BigInteger of {@code bitLength} bits that is probably prime
21420
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
   762
     * @throws ArithmeticException {@code bitLength < 2} or {@code bitLength} is too large.
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   763
     * @see    #bitLength()
90ce3da70b43 Initial load
duke
parents:
diff changeset
   764
     * @since 1.4
90ce3da70b43 Initial load
duke
parents:
diff changeset
   765
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
   766
    public static BigInteger probablePrime(int bitLength, Random rnd) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   767
        if (bitLength < 2)
90ce3da70b43 Initial load
duke
parents:
diff changeset
   768
            throw new ArithmeticException("bitLength < 2");
90ce3da70b43 Initial load
duke
parents:
diff changeset
   769
90ce3da70b43 Initial load
duke
parents:
diff changeset
   770
        return (bitLength < SMALL_PRIME_THRESHOLD ?
90ce3da70b43 Initial load
duke
parents:
diff changeset
   771
                smallPrime(bitLength, DEFAULT_PRIME_CERTAINTY, rnd) :
90ce3da70b43 Initial load
duke
parents:
diff changeset
   772
                largePrime(bitLength, DEFAULT_PRIME_CERTAINTY, rnd));
90ce3da70b43 Initial load
duke
parents:
diff changeset
   773
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   774
90ce3da70b43 Initial load
duke
parents:
diff changeset
   775
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
   776
     * Find a random number of the specified bitLength that is probably prime.
90ce3da70b43 Initial load
duke
parents:
diff changeset
   777
     * This method is used for smaller primes, its performance degrades on
90ce3da70b43 Initial load
duke
parents:
diff changeset
   778
     * larger bitlengths.
90ce3da70b43 Initial load
duke
parents:
diff changeset
   779
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
   780
     * This method assumes bitLength > 1.
90ce3da70b43 Initial load
duke
parents:
diff changeset
   781
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
   782
    private static BigInteger smallPrime(int bitLength, int certainty, Random rnd) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   783
        int magLen = (bitLength + 31) >>> 5;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   784
        int temp[] = new int[magLen];
90ce3da70b43 Initial load
duke
parents:
diff changeset
   785
        int highBit = 1 << ((bitLength+31) & 0x1f);  // High bit of high int
90ce3da70b43 Initial load
duke
parents:
diff changeset
   786
        int highMask = (highBit << 1) - 1;  // Bits to keep in high int
90ce3da70b43 Initial load
duke
parents:
diff changeset
   787
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
   788
        while (true) {
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   789
            // Construct a candidate
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
   790
            for (int i=0; i < magLen; i++)
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   791
                temp[i] = rnd.nextInt();
90ce3da70b43 Initial load
duke
parents:
diff changeset
   792
            temp[0] = (temp[0] & highMask) | highBit;  // Ensure exact length
90ce3da70b43 Initial load
duke
parents:
diff changeset
   793
            if (bitLength > 2)
90ce3da70b43 Initial load
duke
parents:
diff changeset
   794
                temp[magLen-1] |= 1;  // Make odd if bitlen > 2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   795
90ce3da70b43 Initial load
duke
parents:
diff changeset
   796
            BigInteger p = new BigInteger(temp, 1);
90ce3da70b43 Initial load
duke
parents:
diff changeset
   797
90ce3da70b43 Initial load
duke
parents:
diff changeset
   798
            // Do cheap "pre-test" if applicable
90ce3da70b43 Initial load
duke
parents:
diff changeset
   799
            if (bitLength > 6) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   800
                long r = p.remainder(SMALL_PRIME_PRODUCT).longValue();
90ce3da70b43 Initial load
duke
parents:
diff changeset
   801
                if ((r%3==0)  || (r%5==0)  || (r%7==0)  || (r%11==0) ||
90ce3da70b43 Initial load
duke
parents:
diff changeset
   802
                    (r%13==0) || (r%17==0) || (r%19==0) || (r%23==0) ||
90ce3da70b43 Initial load
duke
parents:
diff changeset
   803
                    (r%29==0) || (r%31==0) || (r%37==0) || (r%41==0))
90ce3da70b43 Initial load
duke
parents:
diff changeset
   804
                    continue; // Candidate is composite; try another
90ce3da70b43 Initial load
duke
parents:
diff changeset
   805
            }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   806
90ce3da70b43 Initial load
duke
parents:
diff changeset
   807
            // All candidates of bitLength 2 and 3 are prime by this point
90ce3da70b43 Initial load
duke
parents:
diff changeset
   808
            if (bitLength < 4)
90ce3da70b43 Initial load
duke
parents:
diff changeset
   809
                return p;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   810
90ce3da70b43 Initial load
duke
parents:
diff changeset
   811
            // Do expensive test if we survive pre-test (or it's inapplicable)
90ce3da70b43 Initial load
duke
parents:
diff changeset
   812
            if (p.primeToCertainty(certainty, rnd))
90ce3da70b43 Initial load
duke
parents:
diff changeset
   813
                return p;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   814
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   815
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   816
90ce3da70b43 Initial load
duke
parents:
diff changeset
   817
    private static final BigInteger SMALL_PRIME_PRODUCT
90ce3da70b43 Initial load
duke
parents:
diff changeset
   818
                       = valueOf(3L*5*7*11*13*17*19*23*29*31*37*41);
90ce3da70b43 Initial load
duke
parents:
diff changeset
   819
90ce3da70b43 Initial load
duke
parents:
diff changeset
   820
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
   821
     * Find a random number of the specified bitLength that is probably prime.
90ce3da70b43 Initial load
duke
parents:
diff changeset
   822
     * This method is more appropriate for larger bitlengths since it uses
90ce3da70b43 Initial load
duke
parents:
diff changeset
   823
     * a sieve to eliminate most composites before using a more expensive
90ce3da70b43 Initial load
duke
parents:
diff changeset
   824
     * test.
90ce3da70b43 Initial load
duke
parents:
diff changeset
   825
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
   826
    private static BigInteger largePrime(int bitLength, int certainty, Random rnd) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   827
        BigInteger p;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   828
        p = new BigInteger(bitLength, rnd).setBit(bitLength-1);
90ce3da70b43 Initial load
duke
parents:
diff changeset
   829
        p.mag[p.mag.length-1] &= 0xfffffffe;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   830
90ce3da70b43 Initial load
duke
parents:
diff changeset
   831
        // Use a sieve length likely to contain the next prime number
21420
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
   832
        int searchLen = getPrimeSearchLen(bitLength);
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   833
        BitSieve searchSieve = new BitSieve(p, searchLen);
90ce3da70b43 Initial load
duke
parents:
diff changeset
   834
        BigInteger candidate = searchSieve.retrieve(p, certainty, rnd);
90ce3da70b43 Initial load
duke
parents:
diff changeset
   835
90ce3da70b43 Initial load
duke
parents:
diff changeset
   836
        while ((candidate == null) || (candidate.bitLength() != bitLength)) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   837
            p = p.add(BigInteger.valueOf(2*searchLen));
90ce3da70b43 Initial load
duke
parents:
diff changeset
   838
            if (p.bitLength() != bitLength)
90ce3da70b43 Initial load
duke
parents:
diff changeset
   839
                p = new BigInteger(bitLength, rnd).setBit(bitLength-1);
90ce3da70b43 Initial load
duke
parents:
diff changeset
   840
            p.mag[p.mag.length-1] &= 0xfffffffe;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   841
            searchSieve = new BitSieve(p, searchLen);
90ce3da70b43 Initial load
duke
parents:
diff changeset
   842
            candidate = searchSieve.retrieve(p, certainty, rnd);
90ce3da70b43 Initial load
duke
parents:
diff changeset
   843
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   844
        return candidate;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   845
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   846
90ce3da70b43 Initial load
duke
parents:
diff changeset
   847
   /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
   848
    * Returns the first integer greater than this {@code BigInteger} that
90ce3da70b43 Initial load
duke
parents:
diff changeset
   849
    * is probably prime.  The probability that the number returned by this
90ce3da70b43 Initial load
duke
parents:
diff changeset
   850
    * method is composite does not exceed 2<sup>-100</sup>. This method will
90ce3da70b43 Initial load
duke
parents:
diff changeset
   851
    * never skip over a prime when searching: if it returns {@code p}, there
90ce3da70b43 Initial load
duke
parents:
diff changeset
   852
    * is no prime {@code q} such that {@code this < q < p}.
90ce3da70b43 Initial load
duke
parents:
diff changeset
   853
    *
90ce3da70b43 Initial load
duke
parents:
diff changeset
   854
    * @return the first integer greater than this {@code BigInteger} that
90ce3da70b43 Initial load
duke
parents:
diff changeset
   855
    *         is probably prime.
21420
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
   856
    * @throws ArithmeticException {@code this < 0} or {@code this} is too large.
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   857
    * @since 1.5
90ce3da70b43 Initial load
duke
parents:
diff changeset
   858
    */
90ce3da70b43 Initial load
duke
parents:
diff changeset
   859
    public BigInteger nextProbablePrime() {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   860
        if (this.signum < 0)
90ce3da70b43 Initial load
duke
parents:
diff changeset
   861
            throw new ArithmeticException("start < 0: " + this);
90ce3da70b43 Initial load
duke
parents:
diff changeset
   862
90ce3da70b43 Initial load
duke
parents:
diff changeset
   863
        // Handle trivial cases
90ce3da70b43 Initial load
duke
parents:
diff changeset
   864
        if ((this.signum == 0) || this.equals(ONE))
90ce3da70b43 Initial load
duke
parents:
diff changeset
   865
            return TWO;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   866
90ce3da70b43 Initial load
duke
parents:
diff changeset
   867
        BigInteger result = this.add(ONE);
90ce3da70b43 Initial load
duke
parents:
diff changeset
   868
90ce3da70b43 Initial load
duke
parents:
diff changeset
   869
        // Fastpath for small numbers
90ce3da70b43 Initial load
duke
parents:
diff changeset
   870
        if (result.bitLength() < SMALL_PRIME_THRESHOLD) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   871
90ce3da70b43 Initial load
duke
parents:
diff changeset
   872
            // Ensure an odd number
90ce3da70b43 Initial load
duke
parents:
diff changeset
   873
            if (!result.testBit(0))
90ce3da70b43 Initial load
duke
parents:
diff changeset
   874
                result = result.add(ONE);
90ce3da70b43 Initial load
duke
parents:
diff changeset
   875
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
   876
            while (true) {
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   877
                // Do cheap "pre-test" if applicable
90ce3da70b43 Initial load
duke
parents:
diff changeset
   878
                if (result.bitLength() > 6) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   879
                    long r = result.remainder(SMALL_PRIME_PRODUCT).longValue();
90ce3da70b43 Initial load
duke
parents:
diff changeset
   880
                    if ((r%3==0)  || (r%5==0)  || (r%7==0)  || (r%11==0) ||
90ce3da70b43 Initial load
duke
parents:
diff changeset
   881
                        (r%13==0) || (r%17==0) || (r%19==0) || (r%23==0) ||
90ce3da70b43 Initial load
duke
parents:
diff changeset
   882
                        (r%29==0) || (r%31==0) || (r%37==0) || (r%41==0)) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   883
                        result = result.add(TWO);
90ce3da70b43 Initial load
duke
parents:
diff changeset
   884
                        continue; // Candidate is composite; try another
90ce3da70b43 Initial load
duke
parents:
diff changeset
   885
                    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   886
                }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   887
90ce3da70b43 Initial load
duke
parents:
diff changeset
   888
                // All candidates of bitLength 2 and 3 are prime by this point
90ce3da70b43 Initial load
duke
parents:
diff changeset
   889
                if (result.bitLength() < 4)
90ce3da70b43 Initial load
duke
parents:
diff changeset
   890
                    return result;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   891
90ce3da70b43 Initial load
duke
parents:
diff changeset
   892
                // The expensive test
90ce3da70b43 Initial load
duke
parents:
diff changeset
   893
                if (result.primeToCertainty(DEFAULT_PRIME_CERTAINTY, null))
90ce3da70b43 Initial load
duke
parents:
diff changeset
   894
                    return result;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   895
90ce3da70b43 Initial load
duke
parents:
diff changeset
   896
                result = result.add(TWO);
90ce3da70b43 Initial load
duke
parents:
diff changeset
   897
            }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   898
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   899
90ce3da70b43 Initial load
duke
parents:
diff changeset
   900
        // Start at previous even number
90ce3da70b43 Initial load
duke
parents:
diff changeset
   901
        if (result.testBit(0))
90ce3da70b43 Initial load
duke
parents:
diff changeset
   902
            result = result.subtract(ONE);
90ce3da70b43 Initial load
duke
parents:
diff changeset
   903
90ce3da70b43 Initial load
duke
parents:
diff changeset
   904
        // Looking for the next large prime
21420
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
   905
        int searchLen = getPrimeSearchLen(result.bitLength());
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   906
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
   907
        while (true) {
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   908
           BitSieve searchSieve = new BitSieve(result, searchLen);
90ce3da70b43 Initial load
duke
parents:
diff changeset
   909
           BigInteger candidate = searchSieve.retrieve(result,
90ce3da70b43 Initial load
duke
parents:
diff changeset
   910
                                                 DEFAULT_PRIME_CERTAINTY, null);
90ce3da70b43 Initial load
duke
parents:
diff changeset
   911
           if (candidate != null)
90ce3da70b43 Initial load
duke
parents:
diff changeset
   912
               return candidate;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   913
           result = result.add(BigInteger.valueOf(2 * searchLen));
90ce3da70b43 Initial load
duke
parents:
diff changeset
   914
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   915
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   916
21420
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
   917
    private static int getPrimeSearchLen(int bitLength) {
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
   918
        if (bitLength > PRIME_SEARCH_BIT_LENGTH_LIMIT + 1) {
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
   919
            throw new ArithmeticException("Prime search implementation restriction on bitLength");
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
   920
        }
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
   921
        return bitLength / 20 * 64;
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
   922
    }
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
   923
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   924
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
   925
     * Returns {@code true} if this BigInteger is probably prime,
90ce3da70b43 Initial load
duke
parents:
diff changeset
   926
     * {@code false} if it's definitely composite.
90ce3da70b43 Initial load
duke
parents:
diff changeset
   927
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
   928
     * This method assumes bitLength > 2.
90ce3da70b43 Initial load
duke
parents:
diff changeset
   929
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
   930
     * @param  certainty a measure of the uncertainty that the caller is
90ce3da70b43 Initial load
duke
parents:
diff changeset
   931
     *         willing to tolerate: if the call returns {@code true}
90ce3da70b43 Initial load
duke
parents:
diff changeset
   932
     *         the probability that this BigInteger is prime exceeds
90ce3da70b43 Initial load
duke
parents:
diff changeset
   933
     *         {@code (1 - 1/2<sup>certainty</sup>)}.  The execution time of
90ce3da70b43 Initial load
duke
parents:
diff changeset
   934
     *         this method is proportional to the value of this parameter.
90ce3da70b43 Initial load
duke
parents:
diff changeset
   935
     * @return {@code true} if this BigInteger is probably prime,
90ce3da70b43 Initial load
duke
parents:
diff changeset
   936
     *         {@code false} if it's definitely composite.
90ce3da70b43 Initial load
duke
parents:
diff changeset
   937
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
   938
    boolean primeToCertainty(int certainty, Random random) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   939
        int rounds = 0;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   940
        int n = (Math.min(certainty, Integer.MAX_VALUE-1)+1)/2;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   941
90ce3da70b43 Initial load
duke
parents:
diff changeset
   942
        // The relationship between the certainty and the number of rounds
90ce3da70b43 Initial load
duke
parents:
diff changeset
   943
        // we perform is given in the draft standard ANSI X9.80, "PRIME
90ce3da70b43 Initial load
duke
parents:
diff changeset
   944
        // NUMBER GENERATION, PRIMALITY TESTING, AND PRIMALITY CERTIFICATES".
90ce3da70b43 Initial load
duke
parents:
diff changeset
   945
        int sizeInBits = this.bitLength();
90ce3da70b43 Initial load
duke
parents:
diff changeset
   946
        if (sizeInBits < 100) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   947
            rounds = 50;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   948
            rounds = n < rounds ? n : rounds;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   949
            return passesMillerRabin(rounds, random);
90ce3da70b43 Initial load
duke
parents:
diff changeset
   950
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   951
90ce3da70b43 Initial load
duke
parents:
diff changeset
   952
        if (sizeInBits < 256) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   953
            rounds = 27;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   954
        } else if (sizeInBits < 512) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   955
            rounds = 15;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   956
        } else if (sizeInBits < 768) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   957
            rounds = 8;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   958
        } else if (sizeInBits < 1024) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   959
            rounds = 4;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   960
        } else {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   961
            rounds = 2;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   962
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   963
        rounds = n < rounds ? n : rounds;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   964
90ce3da70b43 Initial load
duke
parents:
diff changeset
   965
        return passesMillerRabin(rounds, random) && passesLucasLehmer();
90ce3da70b43 Initial load
duke
parents:
diff changeset
   966
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   967
90ce3da70b43 Initial load
duke
parents:
diff changeset
   968
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
   969
     * Returns true iff this BigInteger is a Lucas-Lehmer probable prime.
90ce3da70b43 Initial load
duke
parents:
diff changeset
   970
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
   971
     * The following assumptions are made:
90ce3da70b43 Initial load
duke
parents:
diff changeset
   972
     * This BigInteger is a positive, odd number.
90ce3da70b43 Initial load
duke
parents:
diff changeset
   973
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
   974
    private boolean passesLucasLehmer() {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   975
        BigInteger thisPlusOne = this.add(ONE);
90ce3da70b43 Initial load
duke
parents:
diff changeset
   976
90ce3da70b43 Initial load
duke
parents:
diff changeset
   977
        // Step 1
90ce3da70b43 Initial load
duke
parents:
diff changeset
   978
        int d = 5;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   979
        while (jacobiSymbol(d, this) != -1) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   980
            // 5, -7, 9, -11, ...
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
   981
            d = (d < 0) ? Math.abs(d)+2 : -(d+2);
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   982
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   983
90ce3da70b43 Initial load
duke
parents:
diff changeset
   984
        // Step 2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   985
        BigInteger u = lucasLehmerSequence(d, thisPlusOne, this);
90ce3da70b43 Initial load
duke
parents:
diff changeset
   986
90ce3da70b43 Initial load
duke
parents:
diff changeset
   987
        // Step 3
90ce3da70b43 Initial load
duke
parents:
diff changeset
   988
        return u.mod(this).equals(ZERO);
90ce3da70b43 Initial load
duke
parents:
diff changeset
   989
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   990
90ce3da70b43 Initial load
duke
parents:
diff changeset
   991
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
   992
     * Computes Jacobi(p,n).
90ce3da70b43 Initial load
duke
parents:
diff changeset
   993
     * Assumes n positive, odd, n>=3.
90ce3da70b43 Initial load
duke
parents:
diff changeset
   994
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
   995
    private static int jacobiSymbol(int p, BigInteger n) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   996
        if (p == 0)
90ce3da70b43 Initial load
duke
parents:
diff changeset
   997
            return 0;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   998
90ce3da70b43 Initial load
duke
parents:
diff changeset
   999
        // Algorithm and comments adapted from Colin Plumb's C library.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1000
        int j = 1;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1001
        int u = n.mag[n.mag.length-1];
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1002
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1003
        // Make p positive
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1004
        if (p < 0) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1005
            p = -p;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1006
            int n8 = u & 7;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1007
            if ((n8 == 3) || (n8 == 7))
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1008
                j = -j; // 3 (011) or 7 (111) mod 8
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1009
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1010
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1011
        // Get rid of factors of 2 in p
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1012
        while ((p & 3) == 0)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1013
            p >>= 2;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1014
        if ((p & 1) == 0) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1015
            p >>= 1;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1016
            if (((u ^ (u>>1)) & 2) != 0)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1017
                j = -j; // 3 (011) or 5 (101) mod 8
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1018
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1019
        if (p == 1)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1020
            return j;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1021
        // Then, apply quadratic reciprocity
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1022
        if ((p & u & 2) != 0)   // p = u = 3 (mod 4)?
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1023
            j = -j;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1024
        // And reduce u mod p
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1025
        u = n.mod(BigInteger.valueOf(p)).intValue();
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1026
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1027
        // Now compute Jacobi(u,p), u < p
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1028
        while (u != 0) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1029
            while ((u & 3) == 0)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1030
                u >>= 2;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1031
            if ((u & 1) == 0) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1032
                u >>= 1;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1033
                if (((p ^ (p>>1)) & 2) != 0)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1034
                    j = -j;     // 3 (011) or 5 (101) mod 8
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1035
            }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1036
            if (u == 1)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1037
                return j;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1038
            // Now both u and p are odd, so use quadratic reciprocity
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1039
            assert (u < p);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1040
            int t = u; u = p; p = t;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1041
            if ((u & p & 2) != 0) // u = p = 3 (mod 4)?
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1042
                j = -j;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1043
            // Now u >= p, so it can be reduced
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1044
            u %= p;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1045
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1046
        return 0;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1047
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1048
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1049
    private static BigInteger lucasLehmerSequence(int z, BigInteger k, BigInteger n) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1050
        BigInteger d = BigInteger.valueOf(z);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1051
        BigInteger u = ONE; BigInteger u2;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1052
        BigInteger v = ONE; BigInteger v2;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1053
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  1054
        for (int i=k.bitLength()-2; i >= 0; i--) {
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1055
            u2 = u.multiply(v).mod(n);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1056
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1057
            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
  1058
            if (v2.testBit(0))
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  1059
                v2 = v2.subtract(n);
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  1060
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1061
            v2 = v2.shiftRight(1);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1062
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1063
            u = u2; v = v2;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1064
            if (k.testBit(i)) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1065
                u2 = u.add(v).mod(n);
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  1066
                if (u2.testBit(0))
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  1067
                    u2 = u2.subtract(n);
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  1068
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1069
                u2 = u2.shiftRight(1);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1070
                v2 = v.add(d.multiply(u)).mod(n);
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  1071
                if (v2.testBit(0))
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  1072
                    v2 = v2.subtract(n);
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1073
                v2 = v2.shiftRight(1);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1074
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1075
                u = u2; v = v2;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1076
            }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1077
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1078
        return u;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1079
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1080
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1081
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1082
     * Returns true iff this BigInteger passes the specified number of
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1083
     * Miller-Rabin tests. This test is taken from the DSA spec (NIST FIPS
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1084
     * 186-2).
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1085
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1086
     * The following assumptions are made:
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1087
     * This BigInteger is a positive, odd number greater than 2.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1088
     * iterations<=50.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1089
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1090
    private boolean passesMillerRabin(int iterations, Random rnd) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1091
        // Find a and m such that m is odd and this == 1 + 2**a * m
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1092
        BigInteger thisMinusOne = this.subtract(ONE);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1093
        BigInteger m = thisMinusOne;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1094
        int a = m.getLowestSetBit();
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1095
        m = m.shiftRight(a);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1096
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1097
        // Do the tests
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1098
        if (rnd == null) {
20756
d998355e6a5c 7189139: BigInteger's staticRandom field can be a source of bottlenecks.
bpb
parents: 19585
diff changeset
  1099
            rnd = ThreadLocalRandom.current();
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1100
        }
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  1101
        for (int i=0; i < iterations; i++) {
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1102
            // Generate a uniform random on (1, this)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1103
            BigInteger b;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1104
            do {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1105
                b = new BigInteger(this.bitLength(), rnd);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1106
            } while (b.compareTo(ONE) <= 0 || b.compareTo(this) >= 0);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1107
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1108
            int j = 0;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1109
            BigInteger z = b.modPow(m, this);
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  1110
            while (!((j == 0 && z.equals(ONE)) || z.equals(thisMinusOne))) {
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  1111
                if (j > 0 && z.equals(ONE) || ++j == a)
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1112
                    return false;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1113
                z = z.modPow(TWO, this);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1114
            }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1115
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1116
        return true;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1117
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1118
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1119
    /**
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  1120
     * This internal constructor differs from its public cousin
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1121
     * with the arguments reversed in two ways: it assumes that its
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1122
     * arguments are correct, and it doesn't copy the magnitude array.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1123
     */
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  1124
    BigInteger(int[] magnitude, int signum) {
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  1125
        this.signum = (magnitude.length == 0 ? 0 : signum);
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1126
        this.mag = magnitude;
21420
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
  1127
        if (mag.length >= MAX_MAG_LENGTH) {
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
  1128
            checkRange();
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
  1129
        }
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1130
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1131
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1132
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1133
     * This private constructor is for internal use and assumes that its
28309
45f25a2cf942 4026465: Provide more byte array constructors for BigInteger
bpb
parents: 25859
diff changeset
  1134
     * arguments are correct.  The {@code magnitude} array is assumed to be
45f25a2cf942 4026465: Provide more byte array constructors for BigInteger
bpb
parents: 25859
diff changeset
  1135
     * unchanged for the duration of the constructor call.
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1136
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1137
    private BigInteger(byte[] magnitude, int signum) {
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  1138
        this.signum = (magnitude.length == 0 ? 0 : signum);
28309
45f25a2cf942 4026465: Provide more byte array constructors for BigInteger
bpb
parents: 25859
diff changeset
  1139
        this.mag = stripLeadingZeroBytes(magnitude, 0, magnitude.length);
21420
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
  1140
        if (mag.length >= MAX_MAG_LENGTH) {
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
  1141
            checkRange();
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
  1142
        }
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
  1143
    }
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
  1144
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
  1145
    /**
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
  1146
     * Throws an {@code ArithmeticException} if the {@code BigInteger} would be
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
  1147
     * out of the supported range.
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
  1148
     *
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
  1149
     * @throws ArithmeticException if {@code this} exceeds the supported range.
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
  1150
     */
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
  1151
    private void checkRange() {
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
  1152
        if (mag.length > MAX_MAG_LENGTH || mag.length == MAX_MAG_LENGTH && mag[0] < 0) {
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
  1153
            reportOverflow();
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
  1154
        }
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
  1155
    }
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
  1156
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
  1157
    private static void reportOverflow() {
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
  1158
        throw new ArithmeticException("BigInteger would overflow supported range");
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1159
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1160
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1161
    //Static Factory Methods
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1162
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1163
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1164
     * Returns a BigInteger whose value is equal to that of the
38553
0553095041d7 8157724: Improve javadoc tag usage in java.math
darcy
parents: 37880
diff changeset
  1165
     * specified {@code long}.
0553095041d7 8157724: Improve javadoc tag usage in java.math
darcy
parents: 37880
diff changeset
  1166
     *
0553095041d7 8157724: Improve javadoc tag usage in java.math
darcy
parents: 37880
diff changeset
  1167
     * @apiNote This static factory method is provided in preference
0553095041d7 8157724: Improve javadoc tag usage in java.math
darcy
parents: 37880
diff changeset
  1168
     * to a ({@code long}) constructor because it allows for reuse of
0553095041d7 8157724: Improve javadoc tag usage in java.math
darcy
parents: 37880
diff changeset
  1169
     * frequently used BigIntegers.
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1170
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1171
     * @param  val value of the BigInteger to return.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1172
     * @return a BigInteger with the specified value.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1173
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1174
    public static BigInteger valueOf(long val) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1175
        // If -MAX_CONSTANT < val < MAX_CONSTANT, return stashed constant
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1176
        if (val == 0)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1177
            return ZERO;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1178
        if (val > 0 && val <= MAX_CONSTANT)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1179
            return posConst[(int) val];
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1180
        else if (val < 0 && val >= -MAX_CONSTANT)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1181
            return negConst[(int) -val];
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1182
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1183
        return new BigInteger(val);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1184
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1185
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1186
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1187
     * Constructs a BigInteger with the specified value, which may not be zero.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1188
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1189
    private BigInteger(long val) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1190
        if (val < 0) {
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  1191
            val = -val;
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1192
            signum = -1;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1193
        } else {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1194
            signum = 1;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1195
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1196
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1197
        int highWord = (int)(val >>> 32);
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  1198
        if (highWord == 0) {
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1199
            mag = new int[1];
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1200
            mag[0] = (int)val;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1201
        } else {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1202
            mag = new int[2];
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1203
            mag[0] = highWord;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1204
            mag[1] = (int)val;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1205
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1206
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1207
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1208
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1209
     * Returns a BigInteger with the given two's complement representation.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1210
     * Assumes that the input array will not be modified (the returned
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1211
     * BigInteger will reference the input array if feasible).
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1212
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1213
    private static BigInteger valueOf(int val[]) {
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  1214
        return (val[0] > 0 ? new BigInteger(val, 1) : new BigInteger(val));
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
    // Constants
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1218
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1219
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1220
     * Initialize static constant array when class is loaded.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1221
     */
32649
2ee9017c7597 8136583: Core libraries should use blessed modifier order
martin
parents: 32033
diff changeset
  1222
    private static final int MAX_CONSTANT = 16;
52088
c7f7d824f2b6 8152910: Get performance improvement with Stable annotation
bpb
parents: 50062
diff changeset
  1223
    @Stable
c7f7d824f2b6 8152910: Get performance improvement with Stable annotation
bpb
parents: 50062
diff changeset
  1224
    private static final BigInteger[] posConst = new BigInteger[MAX_CONSTANT+1];
c7f7d824f2b6 8152910: Get performance improvement with Stable annotation
bpb
parents: 50062
diff changeset
  1225
    @Stable
c7f7d824f2b6 8152910: Get performance improvement with Stable annotation
bpb
parents: 50062
diff changeset
  1226
    private static final BigInteger[] negConst = new BigInteger[MAX_CONSTANT+1];
18286
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1227
18548
0b6ca9785d8c 4641897: Faster string conversion of large integers
bpb
parents: 18538
diff changeset
  1228
    /**
0b6ca9785d8c 4641897: Faster string conversion of large integers
bpb
parents: 18538
diff changeset
  1229
     * The cache of powers of each radix.  This allows us to not have to
0b6ca9785d8c 4641897: Faster string conversion of large integers
bpb
parents: 18538
diff changeset
  1230
     * recalculate powers of radix^(2^n) more than once.  This speeds
0b6ca9785d8c 4641897: Faster string conversion of large integers
bpb
parents: 18538
diff changeset
  1231
     * Schoenhage recursive base conversion significantly.
0b6ca9785d8c 4641897: Faster string conversion of large integers
bpb
parents: 18538
diff changeset
  1232
     */
18588
8aa1d5a9d447 8017540: Improve multi-threaded contention behavior of radix conversion cache
bpb
parents: 18548
diff changeset
  1233
    private static volatile BigInteger[][] powerCache;
18548
0b6ca9785d8c 4641897: Faster string conversion of large integers
bpb
parents: 18538
diff changeset
  1234
0b6ca9785d8c 4641897: Faster string conversion of large integers
bpb
parents: 18538
diff changeset
  1235
    /** The cache of logarithms of radices for base conversion. */
0b6ca9785d8c 4641897: Faster string conversion of large integers
bpb
parents: 18538
diff changeset
  1236
    private static final double[] logCache;
0b6ca9785d8c 4641897: Faster string conversion of large integers
bpb
parents: 18538
diff changeset
  1237
0b6ca9785d8c 4641897: Faster string conversion of large integers
bpb
parents: 18538
diff changeset
  1238
    /** The natural log of 2.  This is used in computing cache indices. */
0b6ca9785d8c 4641897: Faster string conversion of large integers
bpb
parents: 18538
diff changeset
  1239
    private static final double LOG_TWO = Math.log(2.0);
0b6ca9785d8c 4641897: Faster string conversion of large integers
bpb
parents: 18538
diff changeset
  1240
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1241
    static {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1242
        for (int i = 1; i <= MAX_CONSTANT; i++) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1243
            int[] magnitude = new int[1];
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1244
            magnitude[0] = i;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1245
            posConst[i] = new BigInteger(magnitude,  1);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1246
            negConst[i] = new BigInteger(magnitude, -1);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1247
        }
18548
0b6ca9785d8c 4641897: Faster string conversion of large integers
bpb
parents: 18538
diff changeset
  1248
0b6ca9785d8c 4641897: Faster string conversion of large integers
bpb
parents: 18538
diff changeset
  1249
        /*
0b6ca9785d8c 4641897: Faster string conversion of large integers
bpb
parents: 18538
diff changeset
  1250
         * Initialize the cache of radix^(2^x) values used for base conversion
0b6ca9785d8c 4641897: Faster string conversion of large integers
bpb
parents: 18538
diff changeset
  1251
         * with just the very first value.  Additional values will be created
0b6ca9785d8c 4641897: Faster string conversion of large integers
bpb
parents: 18538
diff changeset
  1252
         * on demand.
0b6ca9785d8c 4641897: Faster string conversion of large integers
bpb
parents: 18538
diff changeset
  1253
         */
18588
8aa1d5a9d447 8017540: Improve multi-threaded contention behavior of radix conversion cache
bpb
parents: 18548
diff changeset
  1254
        powerCache = new BigInteger[Character.MAX_RADIX+1][];
18548
0b6ca9785d8c 4641897: Faster string conversion of large integers
bpb
parents: 18538
diff changeset
  1255
        logCache = new double[Character.MAX_RADIX+1];
0b6ca9785d8c 4641897: Faster string conversion of large integers
bpb
parents: 18538
diff changeset
  1256
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  1257
        for (int i=Character.MIN_RADIX; i <= Character.MAX_RADIX; i++) {
18588
8aa1d5a9d447 8017540: Improve multi-threaded contention behavior of radix conversion cache
bpb
parents: 18548
diff changeset
  1258
            powerCache[i] = new BigInteger[] { BigInteger.valueOf(i) };
18548
0b6ca9785d8c 4641897: Faster string conversion of large integers
bpb
parents: 18538
diff changeset
  1259
            logCache[i] = Math.log(i);
0b6ca9785d8c 4641897: Faster string conversion of large integers
bpb
parents: 18538
diff changeset
  1260
        }
2
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
     * The BigInteger constant zero.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1265
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1266
     * @since   1.2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1267
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1268
    public static final BigInteger ZERO = new BigInteger(new int[0], 0);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1269
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1270
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1271
     * The BigInteger constant one.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1272
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1273
     * @since   1.2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1274
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1275
    public static final BigInteger ONE = valueOf(1);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1276
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1277
    /**
36671
6650d41439b6 8152237: Support BigInteger.TWO
xuelei
parents: 35302
diff changeset
  1278
     * The BigInteger constant two.
6650d41439b6 8152237: Support BigInteger.TWO
xuelei
parents: 35302
diff changeset
  1279
     *
6650d41439b6 8152237: Support BigInteger.TWO
xuelei
parents: 35302
diff changeset
  1280
     * @since   9
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1281
     */
36671
6650d41439b6 8152237: Support BigInteger.TWO
xuelei
parents: 35302
diff changeset
  1282
    public static final BigInteger TWO = valueOf(2);
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1283
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1284
    /**
18286
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1285
     * The BigInteger constant -1.  (Not exported.)
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1286
     */
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1287
    private static final BigInteger NEGATIVE_ONE = valueOf(-1);
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1288
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1289
    /**
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1290
     * The BigInteger constant ten.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1291
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1292
     * @since   1.5
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1293
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1294
    public static final BigInteger TEN = valueOf(10);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1295
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1296
    // Arithmetic Operations
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1297
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1298
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1299
     * Returns a BigInteger whose value is {@code (this + val)}.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1300
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1301
     * @param  val value to be added to this BigInteger.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1302
     * @return {@code this + val}
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1303
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1304
    public BigInteger add(BigInteger val) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1305
        if (val.signum == 0)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1306
            return this;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1307
        if (signum == 0)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1308
            return val;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1309
        if (val.signum == signum)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1310
            return new BigInteger(add(mag, val.mag), signum);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1311
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  1312
        int cmp = compareMagnitude(val);
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  1313
        if (cmp == 0)
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1314
            return ZERO;
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  1315
        int[] resultMag = (cmp > 0 ? subtract(mag, val.mag)
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1316
                           : subtract(val.mag, mag));
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1317
        resultMag = trustedStripLeadingZeroInts(resultMag);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1318
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  1319
        return new BigInteger(resultMag, cmp == signum ? 1 : -1);
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1320
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1321
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1322
    /**
10423
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1323
     * Package private methods used by BigDecimal code to add a BigInteger
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1324
     * with a long. Assumes val is not equal to INFLATED.
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1325
     */
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1326
    BigInteger add(long val) {
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1327
        if (val == 0)
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1328
            return this;
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1329
        if (signum == 0)
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1330
            return valueOf(val);
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1331
        if (Long.signum(val) == signum)
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1332
            return new BigInteger(add(mag, Math.abs(val)), signum);
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1333
        int cmp = compareMagnitude(val);
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1334
        if (cmp == 0)
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1335
            return ZERO;
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1336
        int[] resultMag = (cmp > 0 ? subtract(mag, Math.abs(val)) : subtract(Math.abs(val), mag));
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1337
        resultMag = trustedStripLeadingZeroInts(resultMag);
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1338
        return new BigInteger(resultMag, cmp == signum ? 1 : -1);
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1339
    }
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1340
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1341
    /**
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1342
     * Adds the contents of the int array x and long value val. This
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1343
     * method allocates a new int array to hold the answer and returns
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1344
     * a reference to that array.  Assumes x.length &gt; 0 and val is
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1345
     * non-negative
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1346
     */
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1347
    private static int[] add(int[] x, long val) {
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1348
        int[] y;
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1349
        long sum = 0;
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1350
        int xIndex = x.length;
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1351
        int[] result;
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1352
        int highWord = (int)(val >>> 32);
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  1353
        if (highWord == 0) {
10423
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1354
            result = new int[xIndex];
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1355
            sum = (x[--xIndex] & LONG_MASK) + val;
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1356
            result[xIndex] = (int)sum;
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1357
        } else {
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1358
            if (xIndex == 1) {
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1359
                result = new int[2];
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1360
                sum = val  + (x[0] & LONG_MASK);
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1361
                result[1] = (int)sum;
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1362
                result[0] = (int)(sum >>> 32);
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1363
                return result;
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1364
            } else {
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1365
                result = new int[xIndex];
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1366
                sum = (x[--xIndex] & LONG_MASK) + (val & LONG_MASK);
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1367
                result[xIndex] = (int)sum;
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1368
                sum = (x[--xIndex] & LONG_MASK) + (highWord & LONG_MASK) + (sum >>> 32);
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1369
                result[xIndex] = (int)sum;
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1370
            }
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1371
        }
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1372
        // Copy remainder of longer number while carry propagation is required
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1373
        boolean carry = (sum >>> 32 != 0);
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1374
        while (xIndex > 0 && carry)
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1375
            carry = ((result[--xIndex] = x[xIndex] + 1) == 0);
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1376
        // Copy remainder of longer number
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1377
        while (xIndex > 0)
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1378
            result[--xIndex] = x[xIndex];
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1379
        // Grow result if necessary
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1380
        if (carry) {
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1381
            int bigger[] = new int[result.length + 1];
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1382
            System.arraycopy(result, 0, bigger, 1, result.length);
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1383
            bigger[0] = 0x01;
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1384
            return bigger;
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1385
        }
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1386
        return result;
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1387
    }
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1388
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1389
    /**
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1390
     * Adds the contents of the int arrays x and y. This method allocates
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1391
     * a new int array to hold the answer and returns a reference to that
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1392
     * array.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1393
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1394
    private static int[] add(int[] x, int[] y) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1395
        // If x is shorter, swap the two arrays
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1396
        if (x.length < y.length) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1397
            int[] tmp = x;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1398
            x = y;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1399
            y = tmp;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1400
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1401
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1402
        int xIndex = x.length;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1403
        int yIndex = y.length;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1404
        int result[] = new int[xIndex];
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1405
        long sum = 0;
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  1406
        if (yIndex == 1) {
10423
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1407
            sum = (x[--xIndex] & LONG_MASK) + (y[0] & LONG_MASK) ;
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1408
            result[xIndex] = (int)sum;
10423
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1409
        } else {
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1410
            // Add common parts of both numbers
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  1411
            while (yIndex > 0) {
10423
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1412
                sum = (x[--xIndex] & LONG_MASK) +
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1413
                      (y[--yIndex] & LONG_MASK) + (sum >>> 32);
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1414
                result[xIndex] = (int)sum;
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1415
            }
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1416
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1417
        // Copy remainder of longer number while carry propagation is required
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1418
        boolean carry = (sum >>> 32 != 0);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1419
        while (xIndex > 0 && carry)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1420
            carry = ((result[--xIndex] = x[xIndex] + 1) == 0);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1421
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1422
        // Copy remainder of longer number
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1423
        while (xIndex > 0)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1424
            result[--xIndex] = x[xIndex];
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1425
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1426
        // Grow result if necessary
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1427
        if (carry) {
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  1428
            int bigger[] = new int[result.length + 1];
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  1429
            System.arraycopy(result, 0, bigger, 1, result.length);
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  1430
            bigger[0] = 0x01;
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  1431
            return bigger;
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1432
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1433
        return result;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1434
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1435
10423
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1436
    private static int[] subtract(long val, int[] little) {
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1437
        int highWord = (int)(val >>> 32);
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  1438
        if (highWord == 0) {
10423
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1439
            int result[] = new int[1];
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1440
            result[0] = (int)(val - (little[0] & LONG_MASK));
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1441
            return result;
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1442
        } else {
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1443
            int result[] = new int[2];
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  1444
            if (little.length == 1) {
10423
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1445
                long difference = ((int)val & LONG_MASK) - (little[0] & LONG_MASK);
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1446
                result[1] = (int)difference;
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1447
                // Subtract remainder of longer number while borrow propagates
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1448
                boolean borrow = (difference >> 32 != 0);
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  1449
                if (borrow) {
10423
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1450
                    result[0] = highWord - 1;
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1451
                } else {        // Copy remainder of longer number
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1452
                    result[0] = highWord;
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1453
                }
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1454
                return result;
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  1455
            } else { // little.length == 2
10423
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1456
                long difference = ((int)val & LONG_MASK) - (little[1] & LONG_MASK);
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1457
                result[1] = (int)difference;
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1458
                difference = (highWord & LONG_MASK) - (little[0] & LONG_MASK) + (difference >> 32);
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1459
                result[0] = (int)difference;
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1460
                return result;
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1461
            }
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1462
        }
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1463
    }
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1464
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1465
    /**
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1466
     * Subtracts the contents of the second argument (val) from the
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1467
     * first (big).  The first int array (big) must represent a larger number
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1468
     * than the second.  This method allocates the space necessary to hold the
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1469
     * answer.
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1470
     * assumes val &gt;= 0
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1471
     */
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1472
    private static int[] subtract(int[] big, long val) {
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1473
        int highWord = (int)(val >>> 32);
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1474
        int bigIndex = big.length;
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1475
        int result[] = new int[bigIndex];
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1476
        long difference = 0;
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1477
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  1478
        if (highWord == 0) {
10423
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1479
            difference = (big[--bigIndex] & LONG_MASK) - val;
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1480
            result[bigIndex] = (int)difference;
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1481
        } else {
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1482
            difference = (big[--bigIndex] & LONG_MASK) - (val & LONG_MASK);
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1483
            result[bigIndex] = (int)difference;
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1484
            difference = (big[--bigIndex] & LONG_MASK) - (highWord & LONG_MASK) + (difference >> 32);
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1485
            result[bigIndex] = (int)difference;
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1486
        }
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1487
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1488
        // Subtract remainder of longer number while borrow propagates
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1489
        boolean borrow = (difference >> 32 != 0);
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1490
        while (bigIndex > 0 && borrow)
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1491
            borrow = ((result[--bigIndex] = big[bigIndex] - 1) == -1);
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1492
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1493
        // Copy remainder of longer number
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1494
        while (bigIndex > 0)
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1495
            result[--bigIndex] = big[bigIndex];
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1496
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1497
        return result;
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1498
    }
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1499
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1500
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1501
     * Returns a BigInteger whose value is {@code (this - val)}.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1502
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1503
     * @param  val value to be subtracted from this BigInteger.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1504
     * @return {@code this - val}
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1505
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1506
    public BigInteger subtract(BigInteger val) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1507
        if (val.signum == 0)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1508
            return this;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1509
        if (signum == 0)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1510
            return val.negate();
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1511
        if (val.signum != signum)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1512
            return new BigInteger(add(mag, val.mag), signum);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1513
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  1514
        int cmp = compareMagnitude(val);
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  1515
        if (cmp == 0)
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1516
            return ZERO;
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  1517
        int[] resultMag = (cmp > 0 ? subtract(mag, val.mag)
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1518
                           : subtract(val.mag, mag));
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1519
        resultMag = trustedStripLeadingZeroInts(resultMag);
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  1520
        return new BigInteger(resultMag, cmp == signum ? 1 : -1);
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1521
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1522
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1523
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1524
     * Subtracts the contents of the second int arrays (little) from the
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1525
     * first (big).  The first int array (big) must represent a larger number
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1526
     * than the second.  This method allocates the space necessary to hold the
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1527
     * answer.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1528
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1529
    private static int[] subtract(int[] big, int[] little) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1530
        int bigIndex = big.length;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1531
        int result[] = new int[bigIndex];
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1532
        int littleIndex = little.length;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1533
        long difference = 0;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1534
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1535
        // Subtract common parts of both numbers
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  1536
        while (littleIndex > 0) {
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1537
            difference = (big[--bigIndex] & LONG_MASK) -
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1538
                         (little[--littleIndex] & LONG_MASK) +
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1539
                         (difference >> 32);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1540
            result[bigIndex] = (int)difference;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1541
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1542
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1543
        // Subtract remainder of longer number while borrow propagates
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1544
        boolean borrow = (difference >> 32 != 0);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1545
        while (bigIndex > 0 && borrow)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1546
            borrow = ((result[--bigIndex] = big[bigIndex] - 1) == -1);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1547
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1548
        // Copy remainder of longer number
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1549
        while (bigIndex > 0)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1550
            result[--bigIndex] = big[bigIndex];
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1551
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1552
        return result;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1553
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1554
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1555
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1556
     * Returns a BigInteger whose value is {@code (this * val)}.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1557
     *
22042
98541fec9c62 4891331: BigInteger a.multiply(a) should use squaring code
bpb
parents: 21984
diff changeset
  1558
     * @implNote An implementation may offer better algorithmic
98541fec9c62 4891331: BigInteger a.multiply(a) should use squaring code
bpb
parents: 21984
diff changeset
  1559
     * performance when {@code val == this}.
98541fec9c62 4891331: BigInteger a.multiply(a) should use squaring code
bpb
parents: 21984
diff changeset
  1560
     *
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1561
     * @param  val value to be multiplied by this BigInteger.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1562
     * @return {@code this * val}
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1563
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1564
    public BigInteger multiply(BigInteger val) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1565
        if (val.signum == 0 || signum == 0)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1566
            return ZERO;
18286
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1567
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1568
        int xlen = mag.length;
22042
98541fec9c62 4891331: BigInteger a.multiply(a) should use squaring code
bpb
parents: 21984
diff changeset
  1569
98541fec9c62 4891331: BigInteger a.multiply(a) should use squaring code
bpb
parents: 21984
diff changeset
  1570
        if (val == this && xlen > MULTIPLY_SQUARE_THRESHOLD) {
98541fec9c62 4891331: BigInteger a.multiply(a) should use squaring code
bpb
parents: 21984
diff changeset
  1571
            return square();
98541fec9c62 4891331: BigInteger a.multiply(a) should use squaring code
bpb
parents: 21984
diff changeset
  1572
        }
98541fec9c62 4891331: BigInteger a.multiply(a) should use squaring code
bpb
parents: 21984
diff changeset
  1573
18286
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1574
        int ylen = val.mag.length;
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1575
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  1576
        if ((xlen < KARATSUBA_THRESHOLD) || (ylen < KARATSUBA_THRESHOLD)) {
18286
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1577
            int resultSign = signum == val.signum ? 1 : -1;
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1578
            if (val.mag.length == 1) {
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1579
                return multiplyByInt(mag,val.mag[0], resultSign);
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1580
            }
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  1581
            if (mag.length == 1) {
18286
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1582
                return multiplyByInt(val.mag,mag[0], resultSign);
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1583
            }
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1584
            int[] result = multiplyToLen(mag, xlen,
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1585
                                         val.mag, ylen, null);
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1586
            result = trustedStripLeadingZeroInts(result);
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1587
            return new BigInteger(result, resultSign);
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  1588
        } else {
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  1589
            if ((xlen < TOOM_COOK_THRESHOLD) && (ylen < TOOM_COOK_THRESHOLD)) {
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  1590
                return multiplyKaratsuba(this, val);
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  1591
            } else {
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  1592
                return multiplyToomCook3(this, val);
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  1593
            }
10423
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1594
        }
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1595
    }
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1596
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1597
    private static BigInteger multiplyByInt(int[] x, int y, int sign) {
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  1598
        if (Integer.bitCount(y) == 1) {
10423
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1599
            return new BigInteger(shiftLeft(x,Integer.numberOfTrailingZeros(y)), sign);
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1600
        }
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1601
        int xlen = x.length;
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1602
        int[] rmag =  new int[xlen + 1];
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1603
        long carry = 0;
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1604
        long yl = y & LONG_MASK;
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1605
        int rstart = rmag.length - 1;
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1606
        for (int i = xlen - 1; i >= 0; i--) {
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1607
            long product = (x[i] & LONG_MASK) * yl + carry;
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1608
            rmag[rstart--] = (int)product;
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1609
            carry = product >>> 32;
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1610
        }
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1611
        if (carry == 0L) {
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1612
            rmag = java.util.Arrays.copyOfRange(rmag, 1, rmag.length);
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1613
        } else {
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1614
            rmag[rstart] = (int)carry;
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1615
        }
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  1616
        return new BigInteger(rmag, sign);
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  1617
    }
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  1618
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  1619
    /**
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  1620
     * 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
  1621
     * with a long. Assumes v is not equal to INFLATED.
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  1622
     */
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  1623
    BigInteger multiply(long v) {
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  1624
        if (v == 0 || signum == 0)
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  1625
          return ZERO;
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  1626
        if (v == BigDecimal.INFLATED)
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  1627
            return multiply(BigInteger.valueOf(v));
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  1628
        int rsign = (v > 0 ? signum : -signum);
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  1629
        if (v < 0)
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  1630
            v = -v;
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  1631
        long dh = v >>> 32;      // higher order bits
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  1632
        long dl = v & LONG_MASK; // lower order bits
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  1633
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  1634
        int xlen = mag.length;
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  1635
        int[] value = mag;
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  1636
        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
  1637
        long carry = 0;
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  1638
        int rstart = rmag.length - 1;
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  1639
        for (int i = xlen - 1; i >= 0; i--) {
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  1640
            long product = (value[i] & LONG_MASK) * dl + carry;
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  1641
            rmag[rstart--] = (int)product;
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  1642
            carry = product >>> 32;
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  1643
        }
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  1644
        rmag[rstart] = (int)carry;
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  1645
        if (dh != 0L) {
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  1646
            carry = 0;
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  1647
            rstart = rmag.length - 2;
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  1648
            for (int i = xlen - 1; i >= 0; i--) {
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  1649
                long product = (value[i] & LONG_MASK) * dh +
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  1650
                    (rmag[rstart] & LONG_MASK) + carry;
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  1651
                rmag[rstart--] = (int)product;
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  1652
                carry = product >>> 32;
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  1653
            }
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  1654
            rmag[0] = (int)carry;
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  1655
        }
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  1656
        if (carry == 0L)
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  1657
            rmag = java.util.Arrays.copyOfRange(rmag, 1, rmag.length);
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  1658
        return new BigInteger(rmag, rsign);
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1659
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1660
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1661
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1662
     * 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
  1663
     * the result into z. There will be no leading zeros in the resultant array.
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1664
     */
31667
15a14e8fcfb0 8130150: Implement BigInteger.montgomeryMultiply intrinsic
aph
parents: 31146
diff changeset
  1665
    private static int[] multiplyToLen(int[] x, int xlen, int[] y, int ylen, int[] z) {
31671
362e0c0acece 8076112: Add @HotSpotIntrinsicCandidate annotation to indicate methods for which Java Runtime has intrinsics
zmajo
parents: 31667
diff changeset
  1666
        multiplyToLenCheck(x, xlen);
362e0c0acece 8076112: Add @HotSpotIntrinsicCandidate annotation to indicate methods for which Java Runtime has intrinsics
zmajo
parents: 31667
diff changeset
  1667
        multiplyToLenCheck(y, ylen);
362e0c0acece 8076112: Add @HotSpotIntrinsicCandidate annotation to indicate methods for which Java Runtime has intrinsics
zmajo
parents: 31667
diff changeset
  1668
        return implMultiplyToLen(x, xlen, y, ylen, z);
362e0c0acece 8076112: Add @HotSpotIntrinsicCandidate annotation to indicate methods for which Java Runtime has intrinsics
zmajo
parents: 31667
diff changeset
  1669
    }
362e0c0acece 8076112: Add @HotSpotIntrinsicCandidate annotation to indicate methods for which Java Runtime has intrinsics
zmajo
parents: 31667
diff changeset
  1670
362e0c0acece 8076112: Add @HotSpotIntrinsicCandidate annotation to indicate methods for which Java Runtime has intrinsics
zmajo
parents: 31667
diff changeset
  1671
    @HotSpotIntrinsicCandidate
362e0c0acece 8076112: Add @HotSpotIntrinsicCandidate annotation to indicate methods for which Java Runtime has intrinsics
zmajo
parents: 31667
diff changeset
  1672
    private static int[] implMultiplyToLen(int[] x, int xlen, int[] y, int ylen, int[] z) {
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1673
        int xstart = xlen - 1;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1674
        int ystart = ylen - 1;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1675
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1676
        if (z == null || z.length < (xlen+ ylen))
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1677
            z = new int[xlen+ylen];
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1678
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1679
        long carry = 0;
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  1680
        for (int j=ystart, k=ystart+1+xstart; j >= 0; j--, k--) {
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1681
            long product = (y[j] & LONG_MASK) *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1682
                           (x[xstart] & LONG_MASK) + carry;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1683
            z[k] = (int)product;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1684
            carry = product >>> 32;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1685
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1686
        z[xstart] = (int)carry;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1687
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1688
        for (int i = xstart-1; i >= 0; i--) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1689
            carry = 0;
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  1690
            for (int j=ystart, k=ystart+1+i; j >= 0; j--, k--) {
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1691
                long product = (y[j] & LONG_MASK) *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1692
                               (x[i] & LONG_MASK) +
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1693
                               (z[k] & LONG_MASK) + carry;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1694
                z[k] = (int)product;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1695
                carry = product >>> 32;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1696
            }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1697
            z[i] = (int)carry;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1698
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1699
        return z;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1700
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1701
31671
362e0c0acece 8076112: Add @HotSpotIntrinsicCandidate annotation to indicate methods for which Java Runtime has intrinsics
zmajo
parents: 31667
diff changeset
  1702
    private static void multiplyToLenCheck(int[] array, int length) {
362e0c0acece 8076112: Add @HotSpotIntrinsicCandidate annotation to indicate methods for which Java Runtime has intrinsics
zmajo
parents: 31667
diff changeset
  1703
        if (length <= 0) {
362e0c0acece 8076112: Add @HotSpotIntrinsicCandidate annotation to indicate methods for which Java Runtime has intrinsics
zmajo
parents: 31667
diff changeset
  1704
            return;  // not an error because multiplyToLen won't execute if len <= 0
362e0c0acece 8076112: Add @HotSpotIntrinsicCandidate annotation to indicate methods for which Java Runtime has intrinsics
zmajo
parents: 31667
diff changeset
  1705
        }
362e0c0acece 8076112: Add @HotSpotIntrinsicCandidate annotation to indicate methods for which Java Runtime has intrinsics
zmajo
parents: 31667
diff changeset
  1706
362e0c0acece 8076112: Add @HotSpotIntrinsicCandidate annotation to indicate methods for which Java Runtime has intrinsics
zmajo
parents: 31667
diff changeset
  1707
        Objects.requireNonNull(array);
362e0c0acece 8076112: Add @HotSpotIntrinsicCandidate annotation to indicate methods for which Java Runtime has intrinsics
zmajo
parents: 31667
diff changeset
  1708
362e0c0acece 8076112: Add @HotSpotIntrinsicCandidate annotation to indicate methods for which Java Runtime has intrinsics
zmajo
parents: 31667
diff changeset
  1709
        if (length > array.length) {
362e0c0acece 8076112: Add @HotSpotIntrinsicCandidate annotation to indicate methods for which Java Runtime has intrinsics
zmajo
parents: 31667
diff changeset
  1710
            throw new ArrayIndexOutOfBoundsException(length - 1);
362e0c0acece 8076112: Add @HotSpotIntrinsicCandidate annotation to indicate methods for which Java Runtime has intrinsics
zmajo
parents: 31667
diff changeset
  1711
        }
362e0c0acece 8076112: Add @HotSpotIntrinsicCandidate annotation to indicate methods for which Java Runtime has intrinsics
zmajo
parents: 31667
diff changeset
  1712
    }
362e0c0acece 8076112: Add @HotSpotIntrinsicCandidate annotation to indicate methods for which Java Runtime has intrinsics
zmajo
parents: 31667
diff changeset
  1713
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1714
    /**
18286
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1715
     * Multiplies two BigIntegers using the Karatsuba multiplication
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1716
     * algorithm.  This is a recursive divide-and-conquer algorithm which is
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1717
     * more efficient for large numbers than what is commonly called the
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1718
     * "grade-school" algorithm used in multiplyToLen.  If the numbers to be
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1719
     * multiplied have length n, the "grade-school" algorithm has an
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1720
     * asymptotic complexity of O(n^2).  In contrast, the Karatsuba algorithm
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1721
     * has complexity of O(n^(log2(3))), or O(n^1.585).  It achieves this
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1722
     * increased performance by doing 3 multiplies instead of 4 when
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1723
     * evaluating the product.  As it has some overhead, should be used when
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1724
     * both numbers are larger than a certain threshold (found
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1725
     * experimentally).
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1726
     *
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1727
     * See:  http://en.wikipedia.org/wiki/Karatsuba_algorithm
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1728
     */
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  1729
    private static BigInteger multiplyKaratsuba(BigInteger x, BigInteger y) {
18286
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1730
        int xlen = x.mag.length;
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1731
        int ylen = y.mag.length;
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1732
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1733
        // The number of ints in each half of the number.
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1734
        int half = (Math.max(xlen, ylen)+1) / 2;
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1735
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1736
        // xl and yl are the lower halves of x and y respectively,
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1737
        // xh and yh are the upper halves.
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1738
        BigInteger xl = x.getLower(half);
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1739
        BigInteger xh = x.getUpper(half);
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1740
        BigInteger yl = y.getLower(half);
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1741
        BigInteger yh = y.getUpper(half);
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1742
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1743
        BigInteger p1 = xh.multiply(yh);  // p1 = xh*yh
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1744
        BigInteger p2 = xl.multiply(yl);  // p2 = xl*yl
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1745
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1746
        // p3=(xh+xl)*(yh+yl)
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1747
        BigInteger p3 = xh.add(xl).multiply(yh.add(yl));
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1748
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1749
        // result = p1 * 2^(32*2*half) + (p3 - p1 - p2) * 2^(32*half) + p2
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1750
        BigInteger result = p1.shiftLeft(32*half).add(p3.subtract(p1).subtract(p2)).shiftLeft(32*half).add(p2);
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1751
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  1752
        if (x.signum != y.signum) {
18286
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1753
            return result.negate();
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  1754
        } else {
18286
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1755
            return result;
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  1756
        }
18286
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1757
    }
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1758
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1759
    /**
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1760
     * Multiplies two BigIntegers using a 3-way Toom-Cook multiplication
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1761
     * algorithm.  This is a recursive divide-and-conquer algorithm which is
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1762
     * more efficient for large numbers than what is commonly called the
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1763
     * "grade-school" algorithm used in multiplyToLen.  If the numbers to be
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1764
     * multiplied have length n, the "grade-school" algorithm has an
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1765
     * asymptotic complexity of O(n^2).  In contrast, 3-way Toom-Cook has a
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1766
     * complexity of about O(n^1.465).  It achieves this increased asymptotic
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1767
     * performance by breaking each number into three parts and by doing 5
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1768
     * multiplies instead of 9 when evaluating the product.  Due to overhead
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1769
     * (additions, shifts, and one division) in the Toom-Cook algorithm, it
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1770
     * should only be used when both numbers are larger than a certain
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1771
     * threshold (found experimentally).  This threshold is generally larger
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1772
     * than that for Karatsuba multiplication, so this algorithm is generally
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1773
     * only used when numbers become significantly larger.
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1774
     *
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1775
     * The algorithm used is the "optimal" 3-way Toom-Cook algorithm outlined
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1776
     * by Marco Bodrato.
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1777
     *
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1778
     *  See: http://bodrato.it/toom-cook/
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1779
     *       http://bodrato.it/papers/#WAIFI2007
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1780
     *
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1781
     * "Towards Optimal Toom-Cook Multiplication for Univariate and
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1782
     * Multivariate Polynomials in Characteristic 2 and 0." by Marco BODRATO;
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1783
     * In C.Carlet and B.Sunar, Eds., "WAIFI'07 proceedings", p. 116-133,
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1784
     * LNCS #4547. Springer, Madrid, Spain, June 21-22, 2007.
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1785
     *
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1786
     */
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  1787
    private static BigInteger multiplyToomCook3(BigInteger a, BigInteger b) {
18286
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1788
        int alen = a.mag.length;
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1789
        int blen = b.mag.length;
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1790
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1791
        int largest = Math.max(alen, blen);
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1792
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1793
        // k is the size (in ints) of the lower-order slices.
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1794
        int k = (largest+2)/3;   // Equal to ceil(largest/3)
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1795
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1796
        // r is the size (in ints) of the highest-order slice.
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1797
        int r = largest - 2*k;
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1798
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1799
        // Obtain slices of the numbers. a2 and b2 are the most significant
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1800
        // bits of the numbers a and b, and a0 and b0 the least significant.
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1801
        BigInteger a0, a1, a2, b0, b1, b2;
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1802
        a2 = a.getToomSlice(k, r, 0, largest);
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1803
        a1 = a.getToomSlice(k, r, 1, largest);
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1804
        a0 = a.getToomSlice(k, r, 2, largest);
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1805
        b2 = b.getToomSlice(k, r, 0, largest);
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1806
        b1 = b.getToomSlice(k, r, 1, largest);
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1807
        b0 = b.getToomSlice(k, r, 2, largest);
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1808
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1809
        BigInteger v0, v1, v2, vm1, vinf, t1, t2, tm1, da1, db1;
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1810
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1811
        v0 = a0.multiply(b0);
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1812
        da1 = a2.add(a0);
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1813
        db1 = b2.add(b0);
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1814
        vm1 = da1.subtract(a1).multiply(db1.subtract(b1));
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1815
        da1 = da1.add(a1);
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1816
        db1 = db1.add(b1);
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1817
        v1 = da1.multiply(db1);
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1818
        v2 = da1.add(a2).shiftLeft(1).subtract(a0).multiply(
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1819
             db1.add(b2).shiftLeft(1).subtract(b0));
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1820
        vinf = a2.multiply(b2);
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1821
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  1822
        // The algorithm requires two divisions by 2 and one by 3.
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  1823
        // All divisions are known to be exact, that is, they do not produce
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  1824
        // remainders, and all results are positive.  The divisions by 2 are
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  1825
        // implemented as right shifts which are relatively efficient, leaving
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  1826
        // only an exact division by 3, which is done by a specialized
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  1827
        // linear-time algorithm.
18286
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1828
        t2 = v2.subtract(vm1).exactDivideBy3();
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1829
        tm1 = v1.subtract(vm1).shiftRight(1);
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1830
        t1 = v1.subtract(v0);
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1831
        t2 = t2.subtract(t1).shiftRight(1);
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1832
        t1 = t1.subtract(tm1).subtract(vinf);
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1833
        t2 = t2.subtract(vinf.shiftLeft(1));
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1834
        tm1 = tm1.subtract(t2);
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1835
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1836
        // Number of bits to shift left.
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1837
        int ss = k*32;
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1838
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1839
        BigInteger result = vinf.shiftLeft(ss).add(t2).shiftLeft(ss).add(t1).shiftLeft(ss).add(tm1).shiftLeft(ss).add(v0);
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1840
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  1841
        if (a.signum != b.signum) {
18286
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1842
            return result.negate();
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  1843
        } else {
18286
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1844
            return result;
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  1845
        }
18286
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1846
    }
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1847
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1848
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1849
    /**
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1850
     * Returns a slice of a BigInteger for use in Toom-Cook multiplication.
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1851
     *
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1852
     * @param lowerSize The size of the lower-order bit slices.
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1853
     * @param upperSize The size of the higher-order bit slices.
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1854
     * @param slice The index of which slice is requested, which must be a
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1855
     * number from 0 to size-1. Slice 0 is the highest-order bits, and slice
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1856
     * size-1 are the lowest-order bits. Slice 0 may be of different size than
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1857
     * the other slices.
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1858
     * @param fullsize The size of the larger integer array, used to align
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1859
     * slices to the appropriate position when multiplying different-sized
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1860
     * numbers.
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1861
     */
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1862
    private BigInteger getToomSlice(int lowerSize, int upperSize, int slice,
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  1863
                                    int fullsize) {
18286
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1864
        int start, end, sliceSize, len, offset;
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1865
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1866
        len = mag.length;
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1867
        offset = fullsize - len;
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1868
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  1869
        if (slice == 0) {
18286
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1870
            start = 0 - offset;
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1871
            end = upperSize - 1 - offset;
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  1872
        } else {
18286
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1873
            start = upperSize + (slice-1)*lowerSize - offset;
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1874
            end = start + lowerSize - 1;
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1875
        }
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1876
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  1877
        if (start < 0) {
18286
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1878
            start = 0;
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  1879
        }
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  1880
        if (end < 0) {
18286
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1881
           return ZERO;
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  1882
        }
18286
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1883
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1884
        sliceSize = (end-start) + 1;
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1885
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  1886
        if (sliceSize <= 0) {
18286
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1887
            return ZERO;
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  1888
        }
18286
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1889
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1890
        // While performing Toom-Cook, all slices are positive and
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1891
        // the sign is adjusted when the final number is composed.
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  1892
        if (start == 0 && sliceSize >= len) {
18286
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1893
            return this.abs();
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  1894
        }
18286
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1895
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1896
        int intSlice[] = new int[sliceSize];
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1897
        System.arraycopy(mag, start, intSlice, 0, sliceSize);
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1898
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1899
        return new BigInteger(trustedStripLeadingZeroInts(intSlice), 1);
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1900
    }
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1901
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1902
    /**
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1903
     * Does an exact division (that is, the remainder is known to be zero)
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1904
     * of the specified number by 3.  This is used in Toom-Cook
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1905
     * multiplication.  This is an efficient algorithm that runs in linear
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1906
     * time.  If the argument is not exactly divisible by 3, results are
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1907
     * undefined.  Note that this is expected to be called with positive
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1908
     * arguments only.
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1909
     */
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  1910
    private BigInteger exactDivideBy3() {
18286
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1911
        int len = mag.length;
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1912
        int[] result = new int[len];
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1913
        long x, w, q, borrow;
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1914
        borrow = 0L;
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  1915
        for (int i=len-1; i >= 0; i--) {
18286
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1916
            x = (mag[i] & LONG_MASK);
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1917
            w = x - borrow;
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  1918
            if (borrow > x) {      // Did we make the number go negative?
18286
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1919
                borrow = 1L;
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  1920
            } else {
18286
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1921
                borrow = 0L;
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  1922
            }
18286
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1923
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1924
            // 0xAAAAAAAB is the modular inverse of 3 (mod 2^32).  Thus,
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1925
            // the effect of this is to divide by 3 (mod 2^32).
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1926
            // This is much faster than division on most architectures.
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1927
            q = (w * 0xAAAAAAABL) & LONG_MASK;
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1928
            result[i] = (int) q;
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1929
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1930
            // Now check the borrow. The second check can of course be
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1931
            // eliminated if the first fails.
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  1932
            if (q >= 0x55555556L) {
18286
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1933
                borrow++;
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1934
                if (q >= 0xAAAAAAABL)
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1935
                    borrow++;
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1936
            }
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1937
        }
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1938
        result = trustedStripLeadingZeroInts(result);
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1939
        return new BigInteger(result, signum);
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1940
    }
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1941
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1942
    /**
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1943
     * Returns a new BigInteger representing n lower ints of the number.
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1944
     * This is used by Karatsuba multiplication and Karatsuba squaring.
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1945
     */
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1946
    private BigInteger getLower(int n) {
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1947
        int len = mag.length;
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1948
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  1949
        if (len <= n) {
21983
586d25bfe206 8029514: java/math/BigInteger/BigIntegerTest.java failing since thresholds adjusted in 8022181
bpb
parents: 21956
diff changeset
  1950
            return abs();
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  1951
        }
18286
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1952
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1953
        int lowerInts[] = new int[n];
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1954
        System.arraycopy(mag, len-n, lowerInts, 0, n);
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1955
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1956
        return new BigInteger(trustedStripLeadingZeroInts(lowerInts), 1);
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1957
    }
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1958
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1959
    /**
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1960
     * Returns a new BigInteger representing mag.length-n upper
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1961
     * ints of the number.  This is used by Karatsuba multiplication and
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1962
     * Karatsuba squaring.
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1963
     */
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1964
    private BigInteger getUpper(int n) {
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1965
        int len = mag.length;
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1966
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  1967
        if (len <= n) {
18286
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1968
            return ZERO;
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  1969
        }
18286
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1970
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1971
        int upperLen = len - n;
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1972
        int upperInts[] = new int[upperLen];
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1973
        System.arraycopy(mag, 0, upperInts, 0, upperLen);
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1974
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1975
        return new BigInteger(trustedStripLeadingZeroInts(upperInts), 1);
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1976
    }
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1977
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1978
    // Squaring
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1979
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1980
    /**
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1981
     * Returns a BigInteger whose value is {@code (this<sup>2</sup>)}.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1982
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1983
     * @return {@code this<sup>2</sup>}
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1984
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1985
    private BigInteger square() {
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  1986
        if (signum == 0) {
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1987
            return ZERO;
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  1988
        }
18286
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1989
        int len = mag.length;
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1990
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  1991
        if (len < KARATSUBA_SQUARE_THRESHOLD) {
18286
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1992
            int[] z = squareToLen(mag, len, null);
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  1993
            return new BigInteger(trustedStripLeadingZeroInts(z), 1);
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  1994
        } else {
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  1995
            if (len < TOOM_COOK_SQUARE_THRESHOLD) {
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  1996
                return squareKaratsuba();
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  1997
            } else {
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  1998
                return squareToomCook3();
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  1999
            }
18286
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  2000
        }
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2001
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2002
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2003
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2004
     * Squares the contents of the int array x. The result is placed into the
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2005
     * int array z.  The contents of x are not changed.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2006
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2007
    private static final int[] squareToLen(int[] x, int len, int[] z) {
31146
22d69730ee60 8081778: Use Intel x64 CPU instructions for RSA acceleration
kvn
parents: 29220
diff changeset
  2008
         int zlen = len << 1;
22d69730ee60 8081778: Use Intel x64 CPU instructions for RSA acceleration
kvn
parents: 29220
diff changeset
  2009
         if (z == null || z.length < zlen)
22d69730ee60 8081778: Use Intel x64 CPU instructions for RSA acceleration
kvn
parents: 29220
diff changeset
  2010
             z = new int[zlen];
22d69730ee60 8081778: Use Intel x64 CPU instructions for RSA acceleration
kvn
parents: 29220
diff changeset
  2011
22d69730ee60 8081778: Use Intel x64 CPU instructions for RSA acceleration
kvn
parents: 29220
diff changeset
  2012
         // Execute checks before calling intrinsified method.
22d69730ee60 8081778: Use Intel x64 CPU instructions for RSA acceleration
kvn
parents: 29220
diff changeset
  2013
         implSquareToLenChecks(x, len, z, zlen);
22d69730ee60 8081778: Use Intel x64 CPU instructions for RSA acceleration
kvn
parents: 29220
diff changeset
  2014
         return implSquareToLen(x, len, z, zlen);
22d69730ee60 8081778: Use Intel x64 CPU instructions for RSA acceleration
kvn
parents: 29220
diff changeset
  2015
     }
22d69730ee60 8081778: Use Intel x64 CPU instructions for RSA acceleration
kvn
parents: 29220
diff changeset
  2016
22d69730ee60 8081778: Use Intel x64 CPU instructions for RSA acceleration
kvn
parents: 29220
diff changeset
  2017
     /**
22d69730ee60 8081778: Use Intel x64 CPU instructions for RSA acceleration
kvn
parents: 29220
diff changeset
  2018
      * Parameters validation.
22d69730ee60 8081778: Use Intel x64 CPU instructions for RSA acceleration
kvn
parents: 29220
diff changeset
  2019
      */
22d69730ee60 8081778: Use Intel x64 CPU instructions for RSA acceleration
kvn
parents: 29220
diff changeset
  2020
     private static void implSquareToLenChecks(int[] x, int len, int[] z, int zlen) throws RuntimeException {
22d69730ee60 8081778: Use Intel x64 CPU instructions for RSA acceleration
kvn
parents: 29220
diff changeset
  2021
         if (len < 1) {
22d69730ee60 8081778: Use Intel x64 CPU instructions for RSA acceleration
kvn
parents: 29220
diff changeset
  2022
             throw new IllegalArgumentException("invalid input length: " + len);
22d69730ee60 8081778: Use Intel x64 CPU instructions for RSA acceleration
kvn
parents: 29220
diff changeset
  2023
         }
22d69730ee60 8081778: Use Intel x64 CPU instructions for RSA acceleration
kvn
parents: 29220
diff changeset
  2024
         if (len > x.length) {
22d69730ee60 8081778: Use Intel x64 CPU instructions for RSA acceleration
kvn
parents: 29220
diff changeset
  2025
             throw new IllegalArgumentException("input length out of bound: " +
22d69730ee60 8081778: Use Intel x64 CPU instructions for RSA acceleration
kvn
parents: 29220
diff changeset
  2026
                                        len + " > " + x.length);
22d69730ee60 8081778: Use Intel x64 CPU instructions for RSA acceleration
kvn
parents: 29220
diff changeset
  2027
         }
22d69730ee60 8081778: Use Intel x64 CPU instructions for RSA acceleration
kvn
parents: 29220
diff changeset
  2028
         if (len * 2 > z.length) {
22d69730ee60 8081778: Use Intel x64 CPU instructions for RSA acceleration
kvn
parents: 29220
diff changeset
  2029
             throw new IllegalArgumentException("input length out of bound: " +
22d69730ee60 8081778: Use Intel x64 CPU instructions for RSA acceleration
kvn
parents: 29220
diff changeset
  2030
                                        (len * 2) + " > " + z.length);
22d69730ee60 8081778: Use Intel x64 CPU instructions for RSA acceleration
kvn
parents: 29220
diff changeset
  2031
         }
22d69730ee60 8081778: Use Intel x64 CPU instructions for RSA acceleration
kvn
parents: 29220
diff changeset
  2032
         if (zlen < 1) {
22d69730ee60 8081778: Use Intel x64 CPU instructions for RSA acceleration
kvn
parents: 29220
diff changeset
  2033
             throw new IllegalArgumentException("invalid input length: " + zlen);
22d69730ee60 8081778: Use Intel x64 CPU instructions for RSA acceleration
kvn
parents: 29220
diff changeset
  2034
         }
22d69730ee60 8081778: Use Intel x64 CPU instructions for RSA acceleration
kvn
parents: 29220
diff changeset
  2035
         if (zlen > z.length) {
22d69730ee60 8081778: Use Intel x64 CPU instructions for RSA acceleration
kvn
parents: 29220
diff changeset
  2036
             throw new IllegalArgumentException("input length out of bound: " +
22d69730ee60 8081778: Use Intel x64 CPU instructions for RSA acceleration
kvn
parents: 29220
diff changeset
  2037
                                        len + " > " + z.length);
22d69730ee60 8081778: Use Intel x64 CPU instructions for RSA acceleration
kvn
parents: 29220
diff changeset
  2038
         }
22d69730ee60 8081778: Use Intel x64 CPU instructions for RSA acceleration
kvn
parents: 29220
diff changeset
  2039
     }
22d69730ee60 8081778: Use Intel x64 CPU instructions for RSA acceleration
kvn
parents: 29220
diff changeset
  2040
22d69730ee60 8081778: Use Intel x64 CPU instructions for RSA acceleration
kvn
parents: 29220
diff changeset
  2041
     /**
22d69730ee60 8081778: Use Intel x64 CPU instructions for RSA acceleration
kvn
parents: 29220
diff changeset
  2042
      * Java Runtime may use intrinsic for this method.
22d69730ee60 8081778: Use Intel x64 CPU instructions for RSA acceleration
kvn
parents: 29220
diff changeset
  2043
      */
31671
362e0c0acece 8076112: Add @HotSpotIntrinsicCandidate annotation to indicate methods for which Java Runtime has intrinsics
zmajo
parents: 31667
diff changeset
  2044
     @HotSpotIntrinsicCandidate
31146
22d69730ee60 8081778: Use Intel x64 CPU instructions for RSA acceleration
kvn
parents: 29220
diff changeset
  2045
     private static final int[] implSquareToLen(int[] x, int len, int[] z, int zlen) {
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2046
        /*
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2047
         * The algorithm used here is adapted from Colin Plumb's C library.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2048
         * Technique: Consider the partial products in the multiplication
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2049
         * of "abcde" by itself:
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2050
         *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2051
         *               a  b  c  d  e
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2052
         *            *  a  b  c  d  e
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2053
         *          ==================
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2054
         *              ae be ce de ee
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2055
         *           ad bd cd dd de
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2056
         *        ac bc cc cd ce
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2057
         *     ab bb bc bd be
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2058
         *  aa ab ac ad ae
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2059
         *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2060
         * Note that everything above the main diagonal:
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2061
         *              ae be ce de = (abcd) * e
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2062
         *           ad bd cd       = (abc) * d
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2063
         *        ac bc             = (ab) * c
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2064
         *     ab                   = (a) * b
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2065
         *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2066
         * is a copy of everything below the main diagonal:
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2067
         *                       de
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2068
         *                 cd ce
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2069
         *           bc bd be
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2070
         *     ab ac ad ae
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2071
         *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2072
         * Thus, the sum is 2 * (off the diagonal) + diagonal.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2073
         *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2074
         * This is accumulated beginning with the diagonal (which
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2075
         * consist of the squares of the digits of the input), which is then
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2076
         * divided by two, the off-diagonal added, and multiplied by two
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2077
         * again.  The low bit is simply a copy of the low bit of the
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2078
         * input, so it doesn't need special care.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2079
         */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2080
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2081
        // Store the squares, right shifted one bit (i.e., divided by 2)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2082
        int lastProductLowWord = 0;
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  2083
        for (int j=0, i=0; j < len; j++) {
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2084
            long piece = (x[j] & LONG_MASK);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2085
            long product = piece * piece;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2086
            z[i++] = (lastProductLowWord << 31) | (int)(product >>> 33);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2087
            z[i++] = (int)(product >>> 1);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2088
            lastProductLowWord = (int)product;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2089
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2090
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2091
        // Add in off-diagonal sums
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  2092
        for (int i=len, offset=1; i > 0; i--, offset+=2) {
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2093
            int t = x[i-1];
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2094
            t = mulAdd(z, x, offset, i-1, t);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2095
            addOne(z, offset-1, i, t);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2096
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2097
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2098
        // Shift back up and set low bit
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2099
        primitiveLeftShift(z, zlen, 1);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2100
        z[zlen-1] |= x[len-1] & 1;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2101
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2102
        return z;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2103
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2104
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2105
    /**
18286
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  2106
     * Squares a BigInteger using the Karatsuba squaring algorithm.  It should
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  2107
     * be used when both numbers are larger than a certain threshold (found
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  2108
     * experimentally).  It is a recursive divide-and-conquer algorithm that
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  2109
     * has better asymptotic performance than the algorithm used in
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  2110
     * squareToLen.
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  2111
     */
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  2112
    private BigInteger squareKaratsuba() {
18286
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  2113
        int half = (mag.length+1) / 2;
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  2114
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  2115
        BigInteger xl = getLower(half);
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  2116
        BigInteger xh = getUpper(half);
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  2117
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  2118
        BigInteger xhs = xh.square();  // xhs = xh^2
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  2119
        BigInteger xls = xl.square();  // xls = xl^2
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  2120
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  2121
        // xh^2 << 64  +  (((xl+xh)^2 - (xh^2 + xl^2)) << 32) + xl^2
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  2122
        return xhs.shiftLeft(half*32).add(xl.add(xh).square().subtract(xhs.add(xls))).shiftLeft(half*32).add(xls);
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  2123
    }
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  2124
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  2125
    /**
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  2126
     * Squares a BigInteger using the 3-way Toom-Cook squaring algorithm.  It
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  2127
     * should be used when both numbers are larger than a certain threshold
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  2128
     * (found experimentally).  It is a recursive divide-and-conquer algorithm
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  2129
     * that has better asymptotic performance than the algorithm used in
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  2130
     * squareToLen or squareKaratsuba.
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  2131
     */
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  2132
    private BigInteger squareToomCook3() {
18286
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  2133
        int len = mag.length;
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  2134
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  2135
        // k is the size (in ints) of the lower-order slices.
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  2136
        int k = (len+2)/3;   // Equal to ceil(largest/3)
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  2137
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  2138
        // r is the size (in ints) of the highest-order slice.
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  2139
        int r = len - 2*k;
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  2140
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  2141
        // Obtain slices of the numbers. a2 is the most significant
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  2142
        // bits of the number, and a0 the least significant.
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  2143
        BigInteger a0, a1, a2;
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  2144
        a2 = getToomSlice(k, r, 0, len);
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  2145
        a1 = getToomSlice(k, r, 1, len);
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  2146
        a0 = getToomSlice(k, r, 2, len);
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  2147
        BigInteger v0, v1, v2, vm1, vinf, t1, t2, tm1, da1;
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  2148
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  2149
        v0 = a0.square();
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  2150
        da1 = a2.add(a0);
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  2151
        vm1 = da1.subtract(a1).square();
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  2152
        da1 = da1.add(a1);
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  2153
        v1 = da1.square();
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  2154
        vinf = a2.square();
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  2155
        v2 = da1.add(a2).shiftLeft(1).subtract(a0).square();
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  2156
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  2157
        // The algorithm requires two divisions by 2 and one by 3.
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  2158
        // All divisions are known to be exact, that is, they do not produce
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  2159
        // remainders, and all results are positive.  The divisions by 2 are
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  2160
        // implemented as right shifts which are relatively efficient, leaving
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  2161
        // only a division by 3.
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  2162
        // The division by 3 is done by an optimized algorithm for this case.
18286
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  2163
        t2 = v2.subtract(vm1).exactDivideBy3();
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  2164
        tm1 = v1.subtract(vm1).shiftRight(1);
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  2165
        t1 = v1.subtract(v0);
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  2166
        t2 = t2.subtract(t1).shiftRight(1);
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  2167
        t1 = t1.subtract(tm1).subtract(vinf);
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  2168
        t2 = t2.subtract(vinf.shiftLeft(1));
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  2169
        tm1 = tm1.subtract(t2);
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  2170
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  2171
        // Number of bits to shift left.
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  2172
        int ss = k*32;
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  2173
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  2174
        return vinf.shiftLeft(ss).add(t2).shiftLeft(ss).add(t1).shiftLeft(ss).add(tm1).shiftLeft(ss).add(v0);
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  2175
    }
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  2176
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  2177
    // Division
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  2178
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  2179
    /**
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2180
     * Returns a BigInteger whose value is {@code (this / val)}.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2181
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2182
     * @param  val value by which this BigInteger is to be divided.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2183
     * @return {@code this / val}
4160
bda0a85afcb7 6560935: BigInteger.modPow() throws ArithmeticException for negative exponent
darcy
parents: 4151
diff changeset
  2184
     * @throws ArithmeticException if {@code val} is zero.
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2185
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2186
    public BigInteger divide(BigInteger val) {
21984
4dff16390b67 8029501: BigInteger division algorithm selection heuristic is incorrect
bpb
parents: 21983
diff changeset
  2187
        if (val.mag.length < BURNIKEL_ZIEGLER_THRESHOLD ||
4dff16390b67 8029501: BigInteger division algorithm selection heuristic is incorrect
bpb
parents: 21983
diff changeset
  2188
                mag.length - val.mag.length < BURNIKEL_ZIEGLER_OFFSET) {
19060
4d949a65ad7f 8014319: Faster division of large integers
bpb
parents: 18588
diff changeset
  2189
            return divideKnuth(val);
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  2190
        } else {
19060
4d949a65ad7f 8014319: Faster division of large integers
bpb
parents: 18588
diff changeset
  2191
            return divideBurnikelZiegler(val);
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  2192
        }
19060
4d949a65ad7f 8014319: Faster division of large integers
bpb
parents: 18588
diff changeset
  2193
    }
4d949a65ad7f 8014319: Faster division of large integers
bpb
parents: 18588
diff changeset
  2194
4d949a65ad7f 8014319: Faster division of large integers
bpb
parents: 18588
diff changeset
  2195
    /**
4d949a65ad7f 8014319: Faster division of large integers
bpb
parents: 18588
diff changeset
  2196
     * Returns a BigInteger whose value is {@code (this / val)} using an O(n^2) algorithm from Knuth.
4d949a65ad7f 8014319: Faster division of large integers
bpb
parents: 18588
diff changeset
  2197
     *
4d949a65ad7f 8014319: Faster division of large integers
bpb
parents: 18588
diff changeset
  2198
     * @param  val value by which this BigInteger is to be divided.
4d949a65ad7f 8014319: Faster division of large integers
bpb
parents: 18588
diff changeset
  2199
     * @return {@code this / val}
4d949a65ad7f 8014319: Faster division of large integers
bpb
parents: 18588
diff changeset
  2200
     * @throws ArithmeticException if {@code val} is zero.
4d949a65ad7f 8014319: Faster division of large integers
bpb
parents: 18588
diff changeset
  2201
     * @see MutableBigInteger#divideKnuth(MutableBigInteger, MutableBigInteger, boolean)
4d949a65ad7f 8014319: Faster division of large integers
bpb
parents: 18588
diff changeset
  2202
     */
4d949a65ad7f 8014319: Faster division of large integers
bpb
parents: 18588
diff changeset
  2203
    private BigInteger divideKnuth(BigInteger val) {
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2204
        MutableBigInteger q = new MutableBigInteger(),
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2205
                          a = new MutableBigInteger(this.mag),
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2206
                          b = new MutableBigInteger(val.mag);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2207
19060
4d949a65ad7f 8014319: Faster division of large integers
bpb
parents: 18588
diff changeset
  2208
        a.divideKnuth(b, q, false);
10423
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  2209
        return q.toBigInteger(this.signum * val.signum);
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2210
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2211
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2212
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2213
     * Returns an array of two BigIntegers containing {@code (this / val)}
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2214
     * followed by {@code (this % val)}.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2215
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2216
     * @param  val value by which this BigInteger is to be divided, and the
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2217
     *         remainder computed.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2218
     * @return an array of two BigIntegers: the quotient {@code (this / val)}
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2219
     *         is the initial element, and the remainder {@code (this % val)}
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2220
     *         is the final element.
4160
bda0a85afcb7 6560935: BigInteger.modPow() throws ArithmeticException for negative exponent
darcy
parents: 4151
diff changeset
  2221
     * @throws ArithmeticException if {@code val} is zero.
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2222
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2223
    public BigInteger[] divideAndRemainder(BigInteger val) {
21984
4dff16390b67 8029501: BigInteger division algorithm selection heuristic is incorrect
bpb
parents: 21983
diff changeset
  2224
        if (val.mag.length < BURNIKEL_ZIEGLER_THRESHOLD ||
4dff16390b67 8029501: BigInteger division algorithm selection heuristic is incorrect
bpb
parents: 21983
diff changeset
  2225
                mag.length - val.mag.length < BURNIKEL_ZIEGLER_OFFSET) {
19060
4d949a65ad7f 8014319: Faster division of large integers
bpb
parents: 18588
diff changeset
  2226
            return divideAndRemainderKnuth(val);
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  2227
        } else {
19060
4d949a65ad7f 8014319: Faster division of large integers
bpb
parents: 18588
diff changeset
  2228
            return divideAndRemainderBurnikelZiegler(val);
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  2229
        }
19060
4d949a65ad7f 8014319: Faster division of large integers
bpb
parents: 18588
diff changeset
  2230
    }
4d949a65ad7f 8014319: Faster division of large integers
bpb
parents: 18588
diff changeset
  2231
4d949a65ad7f 8014319: Faster division of large integers
bpb
parents: 18588
diff changeset
  2232
    /** Long division */
4d949a65ad7f 8014319: Faster division of large integers
bpb
parents: 18588
diff changeset
  2233
    private BigInteger[] divideAndRemainderKnuth(BigInteger val) {
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2234
        BigInteger[] result = new BigInteger[2];
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2235
        MutableBigInteger q = new MutableBigInteger(),
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2236
                          a = new MutableBigInteger(this.mag),
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2237
                          b = new MutableBigInteger(val.mag);
19060
4d949a65ad7f 8014319: Faster division of large integers
bpb
parents: 18588
diff changeset
  2238
        MutableBigInteger r = a.divideKnuth(b, q);
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  2239
        result[0] = q.toBigInteger(this.signum == val.signum ? 1 : -1);
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  2240
        result[1] = r.toBigInteger(this.signum);
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2241
        return result;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2242
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2243
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2244
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2245
     * Returns a BigInteger whose value is {@code (this % val)}.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2246
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2247
     * @param  val value by which this BigInteger is to be divided, and the
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2248
     *         remainder computed.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2249
     * @return {@code this % val}
4160
bda0a85afcb7 6560935: BigInteger.modPow() throws ArithmeticException for negative exponent
darcy
parents: 4151
diff changeset
  2250
     * @throws ArithmeticException if {@code val} is zero.
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2251
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2252
    public BigInteger remainder(BigInteger val) {
21984
4dff16390b67 8029501: BigInteger division algorithm selection heuristic is incorrect
bpb
parents: 21983
diff changeset
  2253
        if (val.mag.length < BURNIKEL_ZIEGLER_THRESHOLD ||
4dff16390b67 8029501: BigInteger division algorithm selection heuristic is incorrect
bpb
parents: 21983
diff changeset
  2254
                mag.length - val.mag.length < BURNIKEL_ZIEGLER_OFFSET) {
19060
4d949a65ad7f 8014319: Faster division of large integers
bpb
parents: 18588
diff changeset
  2255
            return remainderKnuth(val);
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  2256
        } else {
19060
4d949a65ad7f 8014319: Faster division of large integers
bpb
parents: 18588
diff changeset
  2257
            return remainderBurnikelZiegler(val);
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  2258
        }
19060
4d949a65ad7f 8014319: Faster division of large integers
bpb
parents: 18588
diff changeset
  2259
    }
4d949a65ad7f 8014319: Faster division of large integers
bpb
parents: 18588
diff changeset
  2260
4d949a65ad7f 8014319: Faster division of large integers
bpb
parents: 18588
diff changeset
  2261
    /** Long division */
4d949a65ad7f 8014319: Faster division of large integers
bpb
parents: 18588
diff changeset
  2262
    private BigInteger remainderKnuth(BigInteger val) {
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2263
        MutableBigInteger q = new MutableBigInteger(),
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2264
                          a = new MutableBigInteger(this.mag),
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2265
                          b = new MutableBigInteger(val.mag);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2266
19060
4d949a65ad7f 8014319: Faster division of large integers
bpb
parents: 18588
diff changeset
  2267
        return a.divideKnuth(b, q).toBigInteger(this.signum);
4d949a65ad7f 8014319: Faster division of large integers
bpb
parents: 18588
diff changeset
  2268
    }
4d949a65ad7f 8014319: Faster division of large integers
bpb
parents: 18588
diff changeset
  2269
4d949a65ad7f 8014319: Faster division of large integers
bpb
parents: 18588
diff changeset
  2270
    /**
4d949a65ad7f 8014319: Faster division of large integers
bpb
parents: 18588
diff changeset
  2271
     * Calculates {@code this / val} using the Burnikel-Ziegler algorithm.
4d949a65ad7f 8014319: Faster division of large integers
bpb
parents: 18588
diff changeset
  2272
     * @param  val the divisor
4d949a65ad7f 8014319: Faster division of large integers
bpb
parents: 18588
diff changeset
  2273
     * @return {@code this / val}
4d949a65ad7f 8014319: Faster division of large integers
bpb
parents: 18588
diff changeset
  2274
     */
4d949a65ad7f 8014319: Faster division of large integers
bpb
parents: 18588
diff changeset
  2275
    private BigInteger divideBurnikelZiegler(BigInteger val) {
4d949a65ad7f 8014319: Faster division of large integers
bpb
parents: 18588
diff changeset
  2276
        return divideAndRemainderBurnikelZiegler(val)[0];
4d949a65ad7f 8014319: Faster division of large integers
bpb
parents: 18588
diff changeset
  2277
    }
4d949a65ad7f 8014319: Faster division of large integers
bpb
parents: 18588
diff changeset
  2278
4d949a65ad7f 8014319: Faster division of large integers
bpb
parents: 18588
diff changeset
  2279
    /**
4d949a65ad7f 8014319: Faster division of large integers
bpb
parents: 18588
diff changeset
  2280
     * Calculates {@code this % val} using the Burnikel-Ziegler algorithm.
4d949a65ad7f 8014319: Faster division of large integers
bpb
parents: 18588
diff changeset
  2281
     * @param val the divisor
4d949a65ad7f 8014319: Faster division of large integers
bpb
parents: 18588
diff changeset
  2282
     * @return {@code this % val}
4d949a65ad7f 8014319: Faster division of large integers
bpb
parents: 18588
diff changeset
  2283
     */
4d949a65ad7f 8014319: Faster division of large integers
bpb
parents: 18588
diff changeset
  2284
    private BigInteger remainderBurnikelZiegler(BigInteger val) {
4d949a65ad7f 8014319: Faster division of large integers
bpb
parents: 18588
diff changeset
  2285
        return divideAndRemainderBurnikelZiegler(val)[1];
4d949a65ad7f 8014319: Faster division of large integers
bpb
parents: 18588
diff changeset
  2286
    }
4d949a65ad7f 8014319: Faster division of large integers
bpb
parents: 18588
diff changeset
  2287
4d949a65ad7f 8014319: Faster division of large integers
bpb
parents: 18588
diff changeset
  2288
    /**
4d949a65ad7f 8014319: Faster division of large integers
bpb
parents: 18588
diff changeset
  2289
     * Computes {@code this / val} and {@code this % val} using the
4d949a65ad7f 8014319: Faster division of large integers
bpb
parents: 18588
diff changeset
  2290
     * Burnikel-Ziegler algorithm.
4d949a65ad7f 8014319: Faster division of large integers
bpb
parents: 18588
diff changeset
  2291
     * @param val the divisor
4d949a65ad7f 8014319: Faster division of large integers
bpb
parents: 18588
diff changeset
  2292
     * @return an array containing the quotient and remainder
4d949a65ad7f 8014319: Faster division of large integers
bpb
parents: 18588
diff changeset
  2293
     */
4d949a65ad7f 8014319: Faster division of large integers
bpb
parents: 18588
diff changeset
  2294
    private BigInteger[] divideAndRemainderBurnikelZiegler(BigInteger val) {
4d949a65ad7f 8014319: Faster division of large integers
bpb
parents: 18588
diff changeset
  2295
        MutableBigInteger q = new MutableBigInteger();
4d949a65ad7f 8014319: Faster division of large integers
bpb
parents: 18588
diff changeset
  2296
        MutableBigInteger r = new MutableBigInteger(this).divideAndRemainderBurnikelZiegler(new MutableBigInteger(val), q);
4d949a65ad7f 8014319: Faster division of large integers
bpb
parents: 18588
diff changeset
  2297
        BigInteger qBigInt = q.isZero() ? ZERO : q.toBigInteger(signum*val.signum);
4d949a65ad7f 8014319: Faster division of large integers
bpb
parents: 18588
diff changeset
  2298
        BigInteger rBigInt = r.isZero() ? ZERO : r.toBigInteger(signum);
4d949a65ad7f 8014319: Faster division of large integers
bpb
parents: 18588
diff changeset
  2299
        return new BigInteger[] {qBigInt, rBigInt};
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2300
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2301
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2302
    /**
32033
bf24e33c7919 8132468: docs: replace <tt> tags (obsolete in html5) for java.io, java.lang, java.math
avstepan
parents: 31671
diff changeset
  2303
     * Returns a BigInteger whose value is <code>(this<sup>exponent</sup>)</code>.
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2304
     * Note that {@code exponent} is an integer rather than a BigInteger.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2305
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2306
     * @param  exponent exponent to which this BigInteger is to be raised.
32033
bf24e33c7919 8132468: docs: replace <tt> tags (obsolete in html5) for java.io, java.lang, java.math
avstepan
parents: 31671
diff changeset
  2307
     * @return <code>this<sup>exponent</sup></code>
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2308
     * @throws ArithmeticException {@code exponent} is negative.  (This would
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2309
     *         cause the operation to yield a non-integer value.)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2310
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2311
    public BigInteger pow(int exponent) {
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  2312
        if (exponent < 0) {
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2313
            throw new ArithmeticException("Negative exponent");
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  2314
        }
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  2315
        if (signum == 0) {
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  2316
            return (exponent == 0 ? ONE : this);
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  2317
        }
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2318
18286
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  2319
        BigInteger partToSquare = this.abs();
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  2320
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  2321
        // Factor out powers of two from the base, as the exponentiation of
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  2322
        // these can be done by left shifts only.
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  2323
        // The remaining part can then be exponentiated faster.  The
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  2324
        // powers of two will be multiplied back at the end.
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  2325
        int powersOfTwo = partToSquare.getLowestSetBit();
21420
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
  2326
        long bitsToShift = (long)powersOfTwo * exponent;
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
  2327
        if (bitsToShift > Integer.MAX_VALUE) {
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
  2328
            reportOverflow();
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
  2329
        }
18286
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  2330
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  2331
        int remainingBits;
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  2332
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  2333
        // Factor the powers of two out quickly by shifting right, if needed.
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  2334
        if (powersOfTwo > 0) {
18286
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  2335
            partToSquare = partToSquare.shiftRight(powersOfTwo);
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  2336
            remainingBits = partToSquare.bitLength();
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  2337
            if (remainingBits == 1) {  // Nothing left but +/- 1?
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  2338
                if (signum < 0 && (exponent&1) == 1) {
18286
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  2339
                    return NEGATIVE_ONE.shiftLeft(powersOfTwo*exponent);
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  2340
                } else {
18286
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  2341
                    return ONE.shiftLeft(powersOfTwo*exponent);
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  2342
                }
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  2343
            }
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  2344
        } else {
18286
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  2345
            remainingBits = partToSquare.bitLength();
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  2346
            if (remainingBits == 1) { // Nothing left but +/- 1?
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  2347
                if (signum < 0  && (exponent&1) == 1) {
18286
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  2348
                    return NEGATIVE_ONE;
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  2349
                } else {
18286
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  2350
                    return ONE;
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  2351
                }
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  2352
            }
18286
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  2353
        }
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  2354
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  2355
        // This is a quick way to approximate the size of the result,
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  2356
        // similar to doing log2[n] * exponent.  This will give an upper bound
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  2357
        // of how big the result can be, and which algorithm to use.
19585
b57abf89019f 6378503: In java.math.BigDecimal, division by one returns zero
bpb
parents: 19061
diff changeset
  2358
        long scaleFactor = (long)remainingBits * exponent;
18286
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  2359
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  2360
        // Use slightly different algorithms for small and large operands.
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  2361
        // See if the result will safely fit into a long. (Largest 2^63-1)
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  2362
        if (partToSquare.mag.length == 1 && scaleFactor <= 62) {
18286
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  2363
            // Small number algorithm.  Everything fits into a long.
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  2364
            int newSign = (signum <0  && (exponent&1) == 1 ? -1 : 1);
18286
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  2365
            long result = 1;
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  2366
            long baseToPow2 = partToSquare.mag[0] & LONG_MASK;
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  2367
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  2368
            int workingExponent = exponent;
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  2369
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  2370
            // Perform exponentiation using repeated squaring trick
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  2371
            while (workingExponent != 0) {
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  2372
                if ((workingExponent & 1) == 1) {
18286
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  2373
                    result = result * baseToPow2;
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  2374
                }
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  2375
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  2376
                if ((workingExponent >>>= 1) != 0) {
18286
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  2377
                    baseToPow2 = baseToPow2 * baseToPow2;
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  2378
                }
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2379
            }
18286
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  2380
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  2381
            // Multiply back the powers of two (quickly, by shifting left)
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  2382
            if (powersOfTwo > 0) {
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  2383
                if (bitsToShift + scaleFactor <= 62) { // Fits in long?
18286
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  2384
                    return valueOf((result << bitsToShift) * newSign);
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  2385
                } else {
21420
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
  2386
                    return valueOf(result*newSign).shiftLeft((int) bitsToShift);
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  2387
                }
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2388
            }
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  2389
            else {
18286
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  2390
                return valueOf(result*newSign);
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  2391
            }
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  2392
        } else {
18286
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  2393
            // Large number algorithm.  This is basically identical to
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  2394
            // the algorithm above, but calls multiply() and square()
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  2395
            // which may use more efficient algorithms for large numbers.
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  2396
            BigInteger answer = ONE;
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  2397
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  2398
            int workingExponent = exponent;
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  2399
            // Perform exponentiation using repeated squaring trick
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  2400
            while (workingExponent != 0) {
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  2401
                if ((workingExponent & 1) == 1) {
18286
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  2402
                    answer = answer.multiply(partToSquare);
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  2403
                }
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  2404
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  2405
                if ((workingExponent >>>= 1) != 0) {
18286
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  2406
                    partToSquare = partToSquare.square();
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  2407
                }
18286
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  2408
            }
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  2409
            // Multiply back the (exponentiated) powers of two (quickly,
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  2410
            // by shifting left)
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  2411
            if (powersOfTwo > 0) {
18286
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  2412
                answer = answer.shiftLeft(powersOfTwo*exponent);
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  2413
            }
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  2414
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  2415
            if (signum < 0 && (exponent&1) == 1) {
18286
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  2416
                return answer.negate();
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  2417
            } else {
18286
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  2418
                return answer;
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  2419
            }
18286
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  2420
        }
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2421
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2422
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2423
    /**
34538
b0705127fbba 8032027: Add BigInteger square root methods
bpb
parents: 33674
diff changeset
  2424
     * Returns the integer square root of this BigInteger.  The integer square
b0705127fbba 8032027: Add BigInteger square root methods
bpb
parents: 33674
diff changeset
  2425
     * root of the corresponding mathematical integer {@code n} is the largest
b0705127fbba 8032027: Add BigInteger square root methods
bpb
parents: 33674
diff changeset
  2426
     * mathematical integer {@code s} such that {@code s*s <= n}.  It is equal
b0705127fbba 8032027: Add BigInteger square root methods
bpb
parents: 33674
diff changeset
  2427
     * to the value of {@code floor(sqrt(n))}, where {@code sqrt(n)} denotes the
b0705127fbba 8032027: Add BigInteger square root methods
bpb
parents: 33674
diff changeset
  2428
     * real square root of {@code n} treated as a real.  Note that the integer
b0705127fbba 8032027: Add BigInteger square root methods
bpb
parents: 33674
diff changeset
  2429
     * square root will be less than the real square root if the latter is not
b0705127fbba 8032027: Add BigInteger square root methods
bpb
parents: 33674
diff changeset
  2430
     * representable as an integral value.
b0705127fbba 8032027: Add BigInteger square root methods
bpb
parents: 33674
diff changeset
  2431
     *
b0705127fbba 8032027: Add BigInteger square root methods
bpb
parents: 33674
diff changeset
  2432
     * @return the integer square root of {@code this}
b0705127fbba 8032027: Add BigInteger square root methods
bpb
parents: 33674
diff changeset
  2433
     * @throws ArithmeticException if {@code this} is negative.  (The square
b0705127fbba 8032027: Add BigInteger square root methods
bpb
parents: 33674
diff changeset
  2434
     *         root of a negative integer {@code val} is
b0705127fbba 8032027: Add BigInteger square root methods
bpb
parents: 33674
diff changeset
  2435
     *         {@code (i * sqrt(-val))} where <i>i</i> is the
b0705127fbba 8032027: Add BigInteger square root methods
bpb
parents: 33674
diff changeset
  2436
     *         <i>imaginary unit</i> and is equal to
b0705127fbba 8032027: Add BigInteger square root methods
bpb
parents: 33674
diff changeset
  2437
     *         {@code sqrt(-1)}.)
35302
e4d2275861c3 8136494: Update "@since 1.9" to "@since 9" to match java.version.specification
iris
parents: 34781
diff changeset
  2438
     * @since  9
34538
b0705127fbba 8032027: Add BigInteger square root methods
bpb
parents: 33674
diff changeset
  2439
     */
b0705127fbba 8032027: Add BigInteger square root methods
bpb
parents: 33674
diff changeset
  2440
    public BigInteger sqrt() {
b0705127fbba 8032027: Add BigInteger square root methods
bpb
parents: 33674
diff changeset
  2441
        if (this.signum < 0) {
b0705127fbba 8032027: Add BigInteger square root methods
bpb
parents: 33674
diff changeset
  2442
            throw new ArithmeticException("Negative BigInteger");
b0705127fbba 8032027: Add BigInteger square root methods
bpb
parents: 33674
diff changeset
  2443
        }
b0705127fbba 8032027: Add BigInteger square root methods
bpb
parents: 33674
diff changeset
  2444
b0705127fbba 8032027: Add BigInteger square root methods
bpb
parents: 33674
diff changeset
  2445
        return new MutableBigInteger(this.mag).sqrt().toBigInteger();
b0705127fbba 8032027: Add BigInteger square root methods
bpb
parents: 33674
diff changeset
  2446
    }
b0705127fbba 8032027: Add BigInteger square root methods
bpb
parents: 33674
diff changeset
  2447
b0705127fbba 8032027: Add BigInteger square root methods
bpb
parents: 33674
diff changeset
  2448
    /**
b0705127fbba 8032027: Add BigInteger square root methods
bpb
parents: 33674
diff changeset
  2449
     * Returns an array of two BigIntegers containing the integer square root
b0705127fbba 8032027: Add BigInteger square root methods
bpb
parents: 33674
diff changeset
  2450
     * {@code s} of {@code this} and its remainder {@code this - s*s},
b0705127fbba 8032027: Add BigInteger square root methods
bpb
parents: 33674
diff changeset
  2451
     * respectively.
b0705127fbba 8032027: Add BigInteger square root methods
bpb
parents: 33674
diff changeset
  2452
     *
b0705127fbba 8032027: Add BigInteger square root methods
bpb
parents: 33674
diff changeset
  2453
     * @return an array of two BigIntegers with the integer square root at
b0705127fbba 8032027: Add BigInteger square root methods
bpb
parents: 33674
diff changeset
  2454
     *         offset 0 and the remainder at offset 1
b0705127fbba 8032027: Add BigInteger square root methods
bpb
parents: 33674
diff changeset
  2455
     * @throws ArithmeticException if {@code this} is negative.  (The square
b0705127fbba 8032027: Add BigInteger square root methods
bpb
parents: 33674
diff changeset
  2456
     *         root of a negative integer {@code val} is
b0705127fbba 8032027: Add BigInteger square root methods
bpb
parents: 33674
diff changeset
  2457
     *         {@code (i * sqrt(-val))} where <i>i</i> is the
b0705127fbba 8032027: Add BigInteger square root methods
bpb
parents: 33674
diff changeset
  2458
     *         <i>imaginary unit</i> and is equal to
b0705127fbba 8032027: Add BigInteger square root methods
bpb
parents: 33674
diff changeset
  2459
     *         {@code sqrt(-1)}.)
b0705127fbba 8032027: Add BigInteger square root methods
bpb
parents: 33674
diff changeset
  2460
     * @see #sqrt()
35302
e4d2275861c3 8136494: Update "@since 1.9" to "@since 9" to match java.version.specification
iris
parents: 34781
diff changeset
  2461
     * @since  9
34538
b0705127fbba 8032027: Add BigInteger square root methods
bpb
parents: 33674
diff changeset
  2462
     */
b0705127fbba 8032027: Add BigInteger square root methods
bpb
parents: 33674
diff changeset
  2463
    public BigInteger[] sqrtAndRemainder() {
b0705127fbba 8032027: Add BigInteger square root methods
bpb
parents: 33674
diff changeset
  2464
        BigInteger s = sqrt();
b0705127fbba 8032027: Add BigInteger square root methods
bpb
parents: 33674
diff changeset
  2465
        BigInteger r = this.subtract(s.square());
b0705127fbba 8032027: Add BigInteger square root methods
bpb
parents: 33674
diff changeset
  2466
        assert r.compareTo(BigInteger.ZERO) >= 0;
b0705127fbba 8032027: Add BigInteger square root methods
bpb
parents: 33674
diff changeset
  2467
        return new BigInteger[] {s, r};
b0705127fbba 8032027: Add BigInteger square root methods
bpb
parents: 33674
diff changeset
  2468
    }
b0705127fbba 8032027: Add BigInteger square root methods
bpb
parents: 33674
diff changeset
  2469
b0705127fbba 8032027: Add BigInteger square root methods
bpb
parents: 33674
diff changeset
  2470
    /**
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2471
     * Returns a BigInteger whose value is the greatest common divisor of
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2472
     * {@code abs(this)} and {@code abs(val)}.  Returns 0 if
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  2473
     * {@code this == 0 && val == 0}.
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2474
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2475
     * @param  val value with which the GCD is to be computed.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2476
     * @return {@code GCD(abs(this), abs(val))}
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2477
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2478
    public BigInteger gcd(BigInteger val) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2479
        if (val.signum == 0)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2480
            return this.abs();
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2481
        else if (this.signum == 0)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2482
            return val.abs();
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2483
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2484
        MutableBigInteger a = new MutableBigInteger(this);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2485
        MutableBigInteger b = new MutableBigInteger(val);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2486
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2487
        MutableBigInteger result = a.hybridGCD(b);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2488
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  2489
        return result.toBigInteger(1);
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  2490
    }
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  2491
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  2492
    /**
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  2493
     * Package private method to return bit length for an integer.
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  2494
     */
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  2495
    static int bitLengthForInt(int n) {
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  2496
        return 32 - Integer.numberOfLeadingZeros(n);
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2497
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2498
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2499
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2500
     * Left shift int array a up to len by n bits. Returns the array that
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2501
     * results from the shift since space may have to be reallocated.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2502
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2503
    private static int[] leftShift(int[] a, int len, int n) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2504
        int nInts = n >>> 5;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2505
        int nBits = n&0x1F;
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  2506
        int bitsInHighWord = bitLengthForInt(a[0]);
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2507
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2508
        // If shift can be done without recopy, do so
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2509
        if (n <= (32-bitsInHighWord)) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2510
            primitiveLeftShift(a, len, nBits);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2511
            return a;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2512
        } else { // Array must be resized
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2513
            if (nBits <= (32-bitsInHighWord)) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2514
                int result[] = new int[nInts+len];
10425
7903cf45f96f 6989067: BigInteger's array copiers should be converted to System.arraycopy()
darcy
parents: 10423
diff changeset
  2515
                System.arraycopy(a, 0, result, 0, len);
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2516
                primitiveLeftShift(result, result.length, nBits);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2517
                return result;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2518
            } else {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2519
                int result[] = new int[nInts+len+1];
10425
7903cf45f96f 6989067: BigInteger's array copiers should be converted to System.arraycopy()
darcy
parents: 10423
diff changeset
  2520
                System.arraycopy(a, 0, result, 0, len);
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2521
                primitiveRightShift(result, result.length, 32 - nBits);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2522
                return result;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2523
            }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2524
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2525
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2526
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2527
    // shifts a up to len right n bits assumes no leading zeros, 0<n<32
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2528
    static void primitiveRightShift(int[] a, int len, int n) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2529
        int n2 = 32 - n;
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  2530
        for (int i=len-1, c=a[i]; i > 0; i--) {
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2531
            int b = c;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2532
            c = a[i-1];
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2533
            a[i] = (c << n2) | (b >>> n);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2534
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2535
        a[0] >>>= n;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2536
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2537
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2538
    // shifts a up to len left n bits assumes no leading zeros, 0<=n<32
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2539
    static void primitiveLeftShift(int[] a, int len, int n) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2540
        if (len == 0 || n == 0)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2541
            return;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2542
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2543
        int n2 = 32 - n;
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  2544
        for (int i=0, c=a[i], m=i+len-1; i < m; i++) {
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2545
            int b = c;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2546
            c = a[i+1];
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2547
            a[i] = (b << n) | (c >>> n2);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2548
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2549
        a[len-1] <<= n;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2550
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2551
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2552
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2553
     * Calculate bitlength of contents of the first len elements an int array,
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2554
     * assuming there are no leading zero ints.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2555
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2556
    private static int bitLength(int[] val, int len) {
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  2557
        if (len == 0)
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2558
            return 0;
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  2559
        return ((len - 1) << 5) + bitLengthForInt(val[0]);
2
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 a BigInteger whose value is the absolute value of this
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2564
     * BigInteger.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2565
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2566
     * @return {@code abs(this)}
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2567
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2568
    public BigInteger abs() {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2569
        return (signum >= 0 ? this : this.negate());
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2570
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2571
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2572
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2573
     * Returns a BigInteger whose value is {@code (-this)}.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2574
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2575
     * @return {@code -this}
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2576
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2577
    public BigInteger negate() {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2578
        return new BigInteger(this.mag, -this.signum);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2579
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2580
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2581
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2582
     * Returns the signum function of this BigInteger.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2583
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2584
     * @return -1, 0 or 1 as the value of this BigInteger is negative, zero or
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2585
     *         positive.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2586
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2587
    public int signum() {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2588
        return this.signum;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2589
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2590
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2591
    // Modular Arithmetic Operations
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2592
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2593
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2594
     * Returns a BigInteger whose value is {@code (this mod m}).  This method
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2595
     * differs from {@code remainder} in that it always returns a
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2596
     * <i>non-negative</i> BigInteger.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2597
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2598
     * @param  m the modulus.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2599
     * @return {@code this mod m}
4160
bda0a85afcb7 6560935: BigInteger.modPow() throws ArithmeticException for negative exponent
darcy
parents: 4151
diff changeset
  2600
     * @throws ArithmeticException {@code m} &le; 0
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2601
     * @see    #remainder
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2602
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2603
    public BigInteger mod(BigInteger m) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2604
        if (m.signum <= 0)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2605
            throw new ArithmeticException("BigInteger: modulus not positive");
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2606
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2607
        BigInteger result = this.remainder(m);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2608
        return (result.signum >= 0 ? result : result.add(m));
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2609
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2610
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2611
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2612
     * Returns a BigInteger whose value is
32033
bf24e33c7919 8132468: docs: replace <tt> tags (obsolete in html5) for java.io, java.lang, java.math
avstepan
parents: 31671
diff changeset
  2613
     * <code>(this<sup>exponent</sup> mod m)</code>.  (Unlike {@code pow}, this
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2614
     * method permits negative exponents.)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2615
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2616
     * @param  exponent the exponent.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2617
     * @param  m the modulus.
32033
bf24e33c7919 8132468: docs: replace <tt> tags (obsolete in html5) for java.io, java.lang, java.math
avstepan
parents: 31671
diff changeset
  2618
     * @return <code>this<sup>exponent</sup> mod m</code>
4160
bda0a85afcb7 6560935: BigInteger.modPow() throws ArithmeticException for negative exponent
darcy
parents: 4151
diff changeset
  2619
     * @throws ArithmeticException {@code m} &le; 0 or the exponent is
bda0a85afcb7 6560935: BigInteger.modPow() throws ArithmeticException for negative exponent
darcy
parents: 4151
diff changeset
  2620
     *         negative and this BigInteger is not <i>relatively
bda0a85afcb7 6560935: BigInteger.modPow() throws ArithmeticException for negative exponent
darcy
parents: 4151
diff changeset
  2621
     *         prime</i> to {@code m}.
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2622
     * @see    #modInverse
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2623
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2624
    public BigInteger modPow(BigInteger exponent, BigInteger m) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2625
        if (m.signum <= 0)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2626
            throw new ArithmeticException("BigInteger: modulus not positive");
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2627
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2628
        // Trivial cases
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2629
        if (exponent.signum == 0)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2630
            return (m.equals(ONE) ? ZERO : ONE);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2631
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2632
        if (this.equals(ONE))
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2633
            return (m.equals(ONE) ? ZERO : ONE);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2634
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2635
        if (this.equals(ZERO) && exponent.signum >= 0)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2636
            return ZERO;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2637
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2638
        if (this.equals(negConst[1]) && (!exponent.testBit(0)))
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2639
            return (m.equals(ONE) ? ZERO : ONE);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2640
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2641
        boolean invertResult;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2642
        if ((invertResult = (exponent.signum < 0)))
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2643
            exponent = exponent.negate();
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2644
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2645
        BigInteger base = (this.signum < 0 || this.compareTo(m) >= 0
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2646
                           ? this.mod(m) : this);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2647
        BigInteger result;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2648
        if (m.testBit(0)) { // odd modulus
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2649
            result = base.oddModPow(exponent, m);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2650
        } else {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2651
            /*
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2652
             * Even modulus.  Tear it into an "odd part" (m1) and power of two
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2653
             * (m2), exponentiate mod m1, manually exponentiate mod m2, and
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2654
             * use Chinese Remainder Theorem to combine results.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2655
             */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2656
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2657
            // Tear m apart into odd part (m1) and power of 2 (m2)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2658
            int p = m.getLowestSetBit();   // Max pow of 2 that divides m
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2659
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2660
            BigInteger m1 = m.shiftRight(p);  // m/2**p
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2661
            BigInteger m2 = ONE.shiftLeft(p); // 2**p
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2662
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2663
            // Calculate new base from m1
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2664
            BigInteger base2 = (this.signum < 0 || this.compareTo(m1) >= 0
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2665
                                ? this.mod(m1) : this);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2666
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2667
            // Caculate (base ** exponent) mod m1.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2668
            BigInteger a1 = (m1.equals(ONE) ? ZERO :
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2669
                             base2.oddModPow(exponent, m1));
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2670
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2671
            // Calculate (this ** exponent) mod m2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2672
            BigInteger a2 = base.modPow2(exponent, p);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2673
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2674
            // Combine results using Chinese Remainder Theorem
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2675
            BigInteger y1 = m2.modInverse(m1);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2676
            BigInteger y2 = m1.modInverse(m2);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2677
21420
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
  2678
            if (m.mag.length < MAX_MAG_LENGTH / 2) {
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
  2679
                result = a1.multiply(m2).multiply(y1).add(a2.multiply(m1).multiply(y2)).mod(m);
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
  2680
            } else {
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
  2681
                MutableBigInteger t1 = new MutableBigInteger();
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
  2682
                new MutableBigInteger(a1.multiply(m2)).multiply(new MutableBigInteger(y1), t1);
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
  2683
                MutableBigInteger t2 = new MutableBigInteger();
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
  2684
                new MutableBigInteger(a2.multiply(m1)).multiply(new MutableBigInteger(y2), t2);
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
  2685
                t1.add(t2);
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
  2686
                MutableBigInteger q = new MutableBigInteger();
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
  2687
                result = t1.divide(new MutableBigInteger(m), q).toBigInteger();
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
  2688
            }
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2689
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2690
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2691
        return (invertResult ? result.modInverse(m) : result);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2692
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2693
31667
15a14e8fcfb0 8130150: Implement BigInteger.montgomeryMultiply intrinsic
aph
parents: 31146
diff changeset
  2694
    // Montgomery multiplication.  These are wrappers for
15a14e8fcfb0 8130150: Implement BigInteger.montgomeryMultiply intrinsic
aph
parents: 31146
diff changeset
  2695
    // implMontgomeryXX routines which are expected to be replaced by
15a14e8fcfb0 8130150: Implement BigInteger.montgomeryMultiply intrinsic
aph
parents: 31146
diff changeset
  2696
    // virtual machine intrinsics.  We don't use the intrinsics for
15a14e8fcfb0 8130150: Implement BigInteger.montgomeryMultiply intrinsic
aph
parents: 31146
diff changeset
  2697
    // very large operands: MONTGOMERY_INTRINSIC_THRESHOLD should be
15a14e8fcfb0 8130150: Implement BigInteger.montgomeryMultiply intrinsic
aph
parents: 31146
diff changeset
  2698
    // larger than any reasonable crypto key.
15a14e8fcfb0 8130150: Implement BigInteger.montgomeryMultiply intrinsic
aph
parents: 31146
diff changeset
  2699
    private static int[] montgomeryMultiply(int[] a, int[] b, int[] n, int len, long inv,
15a14e8fcfb0 8130150: Implement BigInteger.montgomeryMultiply intrinsic
aph
parents: 31146
diff changeset
  2700
                                            int[] product) {
15a14e8fcfb0 8130150: Implement BigInteger.montgomeryMultiply intrinsic
aph
parents: 31146
diff changeset
  2701
        implMontgomeryMultiplyChecks(a, b, n, len, product);
15a14e8fcfb0 8130150: Implement BigInteger.montgomeryMultiply intrinsic
aph
parents: 31146
diff changeset
  2702
        if (len > MONTGOMERY_INTRINSIC_THRESHOLD) {
15a14e8fcfb0 8130150: Implement BigInteger.montgomeryMultiply intrinsic
aph
parents: 31146
diff changeset
  2703
            // Very long argument: do not use an intrinsic
15a14e8fcfb0 8130150: Implement BigInteger.montgomeryMultiply intrinsic
aph
parents: 31146
diff changeset
  2704
            product = multiplyToLen(a, len, b, len, product);
15a14e8fcfb0 8130150: Implement BigInteger.montgomeryMultiply intrinsic
aph
parents: 31146
diff changeset
  2705
            return montReduce(product, n, len, (int)inv);
15a14e8fcfb0 8130150: Implement BigInteger.montgomeryMultiply intrinsic
aph
parents: 31146
diff changeset
  2706
        } else {
15a14e8fcfb0 8130150: Implement BigInteger.montgomeryMultiply intrinsic
aph
parents: 31146
diff changeset
  2707
            return implMontgomeryMultiply(a, b, n, len, inv, materialize(product, len));
15a14e8fcfb0 8130150: Implement BigInteger.montgomeryMultiply intrinsic
aph
parents: 31146
diff changeset
  2708
        }
15a14e8fcfb0 8130150: Implement BigInteger.montgomeryMultiply intrinsic
aph
parents: 31146
diff changeset
  2709
    }
15a14e8fcfb0 8130150: Implement BigInteger.montgomeryMultiply intrinsic
aph
parents: 31146
diff changeset
  2710
    private static int[] montgomerySquare(int[] a, int[] n, int len, long inv,
15a14e8fcfb0 8130150: Implement BigInteger.montgomeryMultiply intrinsic
aph
parents: 31146
diff changeset
  2711
                                          int[] product) {
15a14e8fcfb0 8130150: Implement BigInteger.montgomeryMultiply intrinsic
aph
parents: 31146
diff changeset
  2712
        implMontgomeryMultiplyChecks(a, a, n, len, product);
15a14e8fcfb0 8130150: Implement BigInteger.montgomeryMultiply intrinsic
aph
parents: 31146
diff changeset
  2713
        if (len > MONTGOMERY_INTRINSIC_THRESHOLD) {
15a14e8fcfb0 8130150: Implement BigInteger.montgomeryMultiply intrinsic
aph
parents: 31146
diff changeset
  2714
            // Very long argument: do not use an intrinsic
15a14e8fcfb0 8130150: Implement BigInteger.montgomeryMultiply intrinsic
aph
parents: 31146
diff changeset
  2715
            product = squareToLen(a, len, product);
15a14e8fcfb0 8130150: Implement BigInteger.montgomeryMultiply intrinsic
aph
parents: 31146
diff changeset
  2716
            return montReduce(product, n, len, (int)inv);
15a14e8fcfb0 8130150: Implement BigInteger.montgomeryMultiply intrinsic
aph
parents: 31146
diff changeset
  2717
        } else {
15a14e8fcfb0 8130150: Implement BigInteger.montgomeryMultiply intrinsic
aph
parents: 31146
diff changeset
  2718
            return implMontgomerySquare(a, n, len, inv, materialize(product, len));
15a14e8fcfb0 8130150: Implement BigInteger.montgomeryMultiply intrinsic
aph
parents: 31146
diff changeset
  2719
        }
15a14e8fcfb0 8130150: Implement BigInteger.montgomeryMultiply intrinsic
aph
parents: 31146
diff changeset
  2720
    }
15a14e8fcfb0 8130150: Implement BigInteger.montgomeryMultiply intrinsic
aph
parents: 31146
diff changeset
  2721
15a14e8fcfb0 8130150: Implement BigInteger.montgomeryMultiply intrinsic
aph
parents: 31146
diff changeset
  2722
    // Range-check everything.
15a14e8fcfb0 8130150: Implement BigInteger.montgomeryMultiply intrinsic
aph
parents: 31146
diff changeset
  2723
    private static void implMontgomeryMultiplyChecks
15a14e8fcfb0 8130150: Implement BigInteger.montgomeryMultiply intrinsic
aph
parents: 31146
diff changeset
  2724
        (int[] a, int[] b, int[] n, int len, int[] product) throws RuntimeException {
15a14e8fcfb0 8130150: Implement BigInteger.montgomeryMultiply intrinsic
aph
parents: 31146
diff changeset
  2725
        if (len % 2 != 0) {
15a14e8fcfb0 8130150: Implement BigInteger.montgomeryMultiply intrinsic
aph
parents: 31146
diff changeset
  2726
            throw new IllegalArgumentException("input array length must be even: " + len);
15a14e8fcfb0 8130150: Implement BigInteger.montgomeryMultiply intrinsic
aph
parents: 31146
diff changeset
  2727
        }
15a14e8fcfb0 8130150: Implement BigInteger.montgomeryMultiply intrinsic
aph
parents: 31146
diff changeset
  2728
15a14e8fcfb0 8130150: Implement BigInteger.montgomeryMultiply intrinsic
aph
parents: 31146
diff changeset
  2729
        if (len < 1) {
15a14e8fcfb0 8130150: Implement BigInteger.montgomeryMultiply intrinsic
aph
parents: 31146
diff changeset
  2730
            throw new IllegalArgumentException("invalid input length: " + len);
15a14e8fcfb0 8130150: Implement BigInteger.montgomeryMultiply intrinsic
aph
parents: 31146
diff changeset
  2731
        }
15a14e8fcfb0 8130150: Implement BigInteger.montgomeryMultiply intrinsic
aph
parents: 31146
diff changeset
  2732
15a14e8fcfb0 8130150: Implement BigInteger.montgomeryMultiply intrinsic
aph
parents: 31146
diff changeset
  2733
        if (len > a.length ||
15a14e8fcfb0 8130150: Implement BigInteger.montgomeryMultiply intrinsic
aph
parents: 31146
diff changeset
  2734
            len > b.length ||
15a14e8fcfb0 8130150: Implement BigInteger.montgomeryMultiply intrinsic
aph
parents: 31146
diff changeset
  2735
            len > n.length ||
15a14e8fcfb0 8130150: Implement BigInteger.montgomeryMultiply intrinsic
aph
parents: 31146
diff changeset
  2736
            (product != null && len > product.length)) {
15a14e8fcfb0 8130150: Implement BigInteger.montgomeryMultiply intrinsic
aph
parents: 31146
diff changeset
  2737
            throw new IllegalArgumentException("input array length out of bound: " + len);
15a14e8fcfb0 8130150: Implement BigInteger.montgomeryMultiply intrinsic
aph
parents: 31146
diff changeset
  2738
        }
15a14e8fcfb0 8130150: Implement BigInteger.montgomeryMultiply intrinsic
aph
parents: 31146
diff changeset
  2739
    }
15a14e8fcfb0 8130150: Implement BigInteger.montgomeryMultiply intrinsic
aph
parents: 31146
diff changeset
  2740
15a14e8fcfb0 8130150: Implement BigInteger.montgomeryMultiply intrinsic
aph
parents: 31146
diff changeset
  2741
    // Make sure that the int array z (which is expected to contain
15a14e8fcfb0 8130150: Implement BigInteger.montgomeryMultiply intrinsic
aph
parents: 31146
diff changeset
  2742
    // the result of a Montgomery multiplication) is present and
15a14e8fcfb0 8130150: Implement BigInteger.montgomeryMultiply intrinsic
aph
parents: 31146
diff changeset
  2743
    // sufficiently large.
15a14e8fcfb0 8130150: Implement BigInteger.montgomeryMultiply intrinsic
aph
parents: 31146
diff changeset
  2744
    private static int[] materialize(int[] z, int len) {
15a14e8fcfb0 8130150: Implement BigInteger.montgomeryMultiply intrinsic
aph
parents: 31146
diff changeset
  2745
         if (z == null || z.length < len)
15a14e8fcfb0 8130150: Implement BigInteger.montgomeryMultiply intrinsic
aph
parents: 31146
diff changeset
  2746
             z = new int[len];
15a14e8fcfb0 8130150: Implement BigInteger.montgomeryMultiply intrinsic
aph
parents: 31146
diff changeset
  2747
         return z;
15a14e8fcfb0 8130150: Implement BigInteger.montgomeryMultiply intrinsic
aph
parents: 31146
diff changeset
  2748
    }
15a14e8fcfb0 8130150: Implement BigInteger.montgomeryMultiply intrinsic
aph
parents: 31146
diff changeset
  2749
47866
39db80b32b69 8191632: Typos in comments due to duplicating words
igerasim
parents: 47216
diff changeset
  2750
    // These methods are intended to be replaced by virtual machine
31667
15a14e8fcfb0 8130150: Implement BigInteger.montgomeryMultiply intrinsic
aph
parents: 31146
diff changeset
  2751
    // intrinsics.
31671
362e0c0acece 8076112: Add @HotSpotIntrinsicCandidate annotation to indicate methods for which Java Runtime has intrinsics
zmajo
parents: 31667
diff changeset
  2752
    @HotSpotIntrinsicCandidate
31667
15a14e8fcfb0 8130150: Implement BigInteger.montgomeryMultiply intrinsic
aph
parents: 31146
diff changeset
  2753
    private static int[] implMontgomeryMultiply(int[] a, int[] b, int[] n, int len,
15a14e8fcfb0 8130150: Implement BigInteger.montgomeryMultiply intrinsic
aph
parents: 31146
diff changeset
  2754
                                         long inv, int[] product) {
15a14e8fcfb0 8130150: Implement BigInteger.montgomeryMultiply intrinsic
aph
parents: 31146
diff changeset
  2755
        product = multiplyToLen(a, len, b, len, product);
15a14e8fcfb0 8130150: Implement BigInteger.montgomeryMultiply intrinsic
aph
parents: 31146
diff changeset
  2756
        return montReduce(product, n, len, (int)inv);
15a14e8fcfb0 8130150: Implement BigInteger.montgomeryMultiply intrinsic
aph
parents: 31146
diff changeset
  2757
    }
31671
362e0c0acece 8076112: Add @HotSpotIntrinsicCandidate annotation to indicate methods for which Java Runtime has intrinsics
zmajo
parents: 31667
diff changeset
  2758
    @HotSpotIntrinsicCandidate
31667
15a14e8fcfb0 8130150: Implement BigInteger.montgomeryMultiply intrinsic
aph
parents: 31146
diff changeset
  2759
    private static int[] implMontgomerySquare(int[] a, int[] n, int len,
15a14e8fcfb0 8130150: Implement BigInteger.montgomeryMultiply intrinsic
aph
parents: 31146
diff changeset
  2760
                                       long inv, int[] product) {
15a14e8fcfb0 8130150: Implement BigInteger.montgomeryMultiply intrinsic
aph
parents: 31146
diff changeset
  2761
        product = squareToLen(a, len, product);
15a14e8fcfb0 8130150: Implement BigInteger.montgomeryMultiply intrinsic
aph
parents: 31146
diff changeset
  2762
        return montReduce(product, n, len, (int)inv);
15a14e8fcfb0 8130150: Implement BigInteger.montgomeryMultiply intrinsic
aph
parents: 31146
diff changeset
  2763
    }
15a14e8fcfb0 8130150: Implement BigInteger.montgomeryMultiply intrinsic
aph
parents: 31146
diff changeset
  2764
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2765
    static int[] bnExpModThreshTable = {7, 25, 81, 241, 673, 1793,
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2766
                                                Integer.MAX_VALUE}; // Sentinel
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2767
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2768
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2769
     * Returns a BigInteger whose value is x to the power of y mod z.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2770
     * Assumes: z is odd && x < z.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2771
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2772
    private BigInteger oddModPow(BigInteger y, BigInteger z) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2773
    /*
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2774
     * The algorithm is adapted from Colin Plumb's C library.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2775
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2776
     * The window algorithm:
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2777
     * The idea is to keep a running product of b1 = n^(high-order bits of exp)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2778
     * and then keep appending exponent bits to it.  The following patterns
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2779
     * apply to a 3-bit window (k = 3):
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2780
     * To append   0: square
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2781
     * To append   1: square, multiply by n^1
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2782
     * To append  10: square, multiply by n^1, square
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2783
     * To append  11: square, square, multiply by n^3
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2784
     * To append 100: square, multiply by n^1, square, square
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2785
     * To append 101: square, square, square, multiply by n^5
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2786
     * To append 110: square, square, multiply by n^3, square
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2787
     * To append 111: square, square, square, multiply by n^7
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2788
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2789
     * Since each pattern involves only one multiply, the longer the pattern
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2790
     * the better, except that a 0 (no multiplies) can be appended directly.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2791
     * We precompute a table of odd powers of n, up to 2^k, and can then
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2792
     * multiply k bits of exponent at a time.  Actually, assuming random
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2793
     * exponents, there is on average one zero bit between needs to
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2794
     * multiply (1/2 of the time there's none, 1/4 of the time there's 1,
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2795
     * 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
  2796
     * you have to do one multiply per k+1 bits of exponent.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2797
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2798
     * The loop walks down the exponent, squaring the result buffer as
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2799
     * it goes.  There is a wbits+1 bit lookahead buffer, buf, that is
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2800
     * filled with the upcoming exponent bits.  (What is read after the
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2801
     * end of the exponent is unimportant, but it is filled with zero here.)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2802
     * When the most-significant bit of this buffer becomes set, i.e.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2803
     * (buf & tblmask) != 0, we have to decide what pattern to multiply
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2804
     * by, and when to do it.  We decide, remember to do it in future
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2805
     * after a suitable number of squarings have passed (e.g. a pattern
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2806
     * of "100" in the buffer requires that we multiply by n^1 immediately;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2807
     * a pattern of "110" calls for multiplying by n^3 after one more
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2808
     * squaring), clear the buffer, and continue.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2809
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2810
     * When we start, there is one more optimization: the result buffer
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2811
     * is implcitly one, so squaring it or multiplying by it can be
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2812
     * optimized away.  Further, if we start with a pattern like "100"
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2813
     * in the lookahead window, rather than placing n into the buffer
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2814
     * and then starting to square it, we have already computed n^2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2815
     * to compute the odd-powers table, so we can place that into
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2816
     * the buffer and save a squaring.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2817
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2818
     * This means that if you have a k-bit window, to compute n^z,
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2819
     * where z is the high k bits of the exponent, 1/2 of the time
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2820
     * it requires no squarings.  1/4 of the time, it requires 1
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2821
     * squaring, ... 1/2^(k-1) of the time, it reqires k-2 squarings.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2822
     * And the remaining 1/2^(k-1) of the time, the top k bits are a
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2823
     * 1 followed by k-1 0 bits, so it again only requires k-2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2824
     * squarings, not k-1.  The average of these is 1.  Add that
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2825
     * to the one squaring we have to do to compute the table,
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2826
     * and you'll see that a k-bit window saves k-2 squarings
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2827
     * as well as reducing the multiplies.  (It actually doesn't
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2828
     * hurt in the case k = 1, either.)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2829
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2830
        // Special case for exponent of one
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2831
        if (y.equals(ONE))
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2832
            return this;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2833
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2834
        // Special case for base of zero
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  2835
        if (signum == 0)
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2836
            return ZERO;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2837
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2838
        int[] base = mag.clone();
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2839
        int[] exp = y.mag;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2840
        int[] mod = z.mag;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2841
        int modLen = mod.length;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2842
31667
15a14e8fcfb0 8130150: Implement BigInteger.montgomeryMultiply intrinsic
aph
parents: 31146
diff changeset
  2843
        // Make modLen even. It is conventional to use a cryptographic
15a14e8fcfb0 8130150: Implement BigInteger.montgomeryMultiply intrinsic
aph
parents: 31146
diff changeset
  2844
        // modulus that is 512, 768, 1024, or 2048 bits, so this code
15a14e8fcfb0 8130150: Implement BigInteger.montgomeryMultiply intrinsic
aph
parents: 31146
diff changeset
  2845
        // will not normally be executed. However, it is necessary for
15a14e8fcfb0 8130150: Implement BigInteger.montgomeryMultiply intrinsic
aph
parents: 31146
diff changeset
  2846
        // the correct functioning of the HotSpot intrinsics.
15a14e8fcfb0 8130150: Implement BigInteger.montgomeryMultiply intrinsic
aph
parents: 31146
diff changeset
  2847
        if ((modLen & 1) != 0) {
15a14e8fcfb0 8130150: Implement BigInteger.montgomeryMultiply intrinsic
aph
parents: 31146
diff changeset
  2848
            int[] x = new int[modLen + 1];
15a14e8fcfb0 8130150: Implement BigInteger.montgomeryMultiply intrinsic
aph
parents: 31146
diff changeset
  2849
            System.arraycopy(mod, 0, x, 1, modLen);
15a14e8fcfb0 8130150: Implement BigInteger.montgomeryMultiply intrinsic
aph
parents: 31146
diff changeset
  2850
            mod = x;
15a14e8fcfb0 8130150: Implement BigInteger.montgomeryMultiply intrinsic
aph
parents: 31146
diff changeset
  2851
            modLen++;
15a14e8fcfb0 8130150: Implement BigInteger.montgomeryMultiply intrinsic
aph
parents: 31146
diff changeset
  2852
        }
15a14e8fcfb0 8130150: Implement BigInteger.montgomeryMultiply intrinsic
aph
parents: 31146
diff changeset
  2853
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2854
        // Select an appropriate window size
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2855
        int wbits = 0;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2856
        int ebits = bitLength(exp, exp.length);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2857
        // if exponent is 65537 (0x10001), use minimum window size
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2858
        if ((ebits != 17) || (exp[0] != 65537)) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2859
            while (ebits > bnExpModThreshTable[wbits]) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2860
                wbits++;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2861
            }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2862
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2863
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2864
        // Calculate appropriate table size
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2865
        int tblmask = 1 << wbits;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2866
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2867
        // Allocate table for precomputed odd powers of base in Montgomery form
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2868
        int[][] table = new int[tblmask][];
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  2869
        for (int i=0; i < tblmask; i++)
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2870
            table[i] = new int[modLen];
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2871
31667
15a14e8fcfb0 8130150: Implement BigInteger.montgomeryMultiply intrinsic
aph
parents: 31146
diff changeset
  2872
        // Compute the modular inverse of the least significant 64-bit
15a14e8fcfb0 8130150: Implement BigInteger.montgomeryMultiply intrinsic
aph
parents: 31146
diff changeset
  2873
        // digit of the modulus
15a14e8fcfb0 8130150: Implement BigInteger.montgomeryMultiply intrinsic
aph
parents: 31146
diff changeset
  2874
        long n0 = (mod[modLen-1] & LONG_MASK) + ((mod[modLen-2] & LONG_MASK) << 32);
15a14e8fcfb0 8130150: Implement BigInteger.montgomeryMultiply intrinsic
aph
parents: 31146
diff changeset
  2875
        long inv = -MutableBigInteger.inverseMod64(n0);
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2876
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2877
        // Convert base to Montgomery form
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2878
        int[] a = leftShift(base, base.length, modLen << 5);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2879
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2880
        MutableBigInteger q = new MutableBigInteger(),
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2881
                          a2 = new MutableBigInteger(a),
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2882
                          b2 = new MutableBigInteger(mod);
31667
15a14e8fcfb0 8130150: Implement BigInteger.montgomeryMultiply intrinsic
aph
parents: 31146
diff changeset
  2883
        b2.normalize(); // MutableBigInteger.divide() assumes that its
15a14e8fcfb0 8130150: Implement BigInteger.montgomeryMultiply intrinsic
aph
parents: 31146
diff changeset
  2884
                        // divisor is in normal form.
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2885
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  2886
        MutableBigInteger r= a2.divide(b2, q);
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2887
        table[0] = r.toIntArray();
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2888
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2889
        // Pad table[0] with leading zeros so its length is at least modLen
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2890
        if (table[0].length < modLen) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2891
           int offset = modLen - table[0].length;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2892
           int[] t2 = new int[modLen];
31667
15a14e8fcfb0 8130150: Implement BigInteger.montgomeryMultiply intrinsic
aph
parents: 31146
diff changeset
  2893
           System.arraycopy(table[0], 0, t2, offset, table[0].length);
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2894
           table[0] = t2;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2895
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2896
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2897
        // Set b to the square of the base
31667
15a14e8fcfb0 8130150: Implement BigInteger.montgomeryMultiply intrinsic
aph
parents: 31146
diff changeset
  2898
        int[] b = montgomerySquare(table[0], mod, modLen, inv, null);
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2899
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2900
        // Set t to high half of b
10425
7903cf45f96f 6989067: BigInteger's array copiers should be converted to System.arraycopy()
darcy
parents: 10423
diff changeset
  2901
        int[] t = Arrays.copyOf(b, modLen);
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2902
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2903
        // Fill in the table with odd powers of the base
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  2904
        for (int i=1; i < tblmask; i++) {
31667
15a14e8fcfb0 8130150: Implement BigInteger.montgomeryMultiply intrinsic
aph
parents: 31146
diff changeset
  2905
            table[i] = montgomeryMultiply(t, table[i-1], mod, modLen, inv, null);
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2906
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2907
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2908
        // Pre load the window that slides over the exponent
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2909
        int bitpos = 1 << ((ebits-1) & (32-1));
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2910
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2911
        int buf = 0;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2912
        int elen = exp.length;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2913
        int eIndex = 0;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2914
        for (int i = 0; i <= wbits; i++) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2915
            buf = (buf << 1) | (((exp[eIndex] & bitpos) != 0)?1:0);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2916
            bitpos >>>= 1;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2917
            if (bitpos == 0) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2918
                eIndex++;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2919
                bitpos = 1 << (32-1);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2920
                elen--;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2921
            }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2922
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2923
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2924
        int multpos = ebits;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2925
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2926
        // The first iteration, which is hoisted out of the main loop
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2927
        ebits--;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2928
        boolean isone = true;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2929
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2930
        multpos = ebits - wbits;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2931
        while ((buf & 1) == 0) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2932
            buf >>>= 1;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2933
            multpos++;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2934
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2935
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2936
        int[] mult = table[buf >>> 1];
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2937
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2938
        buf = 0;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2939
        if (multpos == ebits)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2940
            isone = false;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2941
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2942
        // The main loop
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  2943
        while (true) {
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2944
            ebits--;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2945
            // Advance the window
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2946
            buf <<= 1;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2947
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2948
            if (elen != 0) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2949
                buf |= ((exp[eIndex] & bitpos) != 0) ? 1 : 0;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2950
                bitpos >>>= 1;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2951
                if (bitpos == 0) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2952
                    eIndex++;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2953
                    bitpos = 1 << (32-1);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2954
                    elen--;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2955
                }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2956
            }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2957
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2958
            // Examine the window for pending multiplies
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2959
            if ((buf & tblmask) != 0) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2960
                multpos = ebits - wbits;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2961
                while ((buf & 1) == 0) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2962
                    buf >>>= 1;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2963
                    multpos++;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2964
                }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2965
                mult = table[buf >>> 1];
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2966
                buf = 0;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2967
            }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2968
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2969
            // Perform multiply
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2970
            if (ebits == multpos) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2971
                if (isone) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2972
                    b = mult.clone();
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2973
                    isone = false;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2974
                } else {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2975
                    t = b;
31667
15a14e8fcfb0 8130150: Implement BigInteger.montgomeryMultiply intrinsic
aph
parents: 31146
diff changeset
  2976
                    a = montgomeryMultiply(t, mult, mod, modLen, inv, a);
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2977
                    t = a; a = b; b = t;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2978
                }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2979
            }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2980
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2981
            // Check if done
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2982
            if (ebits == 0)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2983
                break;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2984
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2985
            // Square the input
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2986
            if (!isone) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2987
                t = b;
31667
15a14e8fcfb0 8130150: Implement BigInteger.montgomeryMultiply intrinsic
aph
parents: 31146
diff changeset
  2988
                a = montgomerySquare(t, mod, modLen, inv, a);
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2989
                t = a; a = b; b = t;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2990
            }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2991
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2992
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2993
        // Convert result out of Montgomery form and return
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2994
        int[] t2 = new int[2*modLen];
10425
7903cf45f96f 6989067: BigInteger's array copiers should be converted to System.arraycopy()
darcy
parents: 10423
diff changeset
  2995
        System.arraycopy(b, 0, t2, modLen, modLen);
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2996
31667
15a14e8fcfb0 8130150: Implement BigInteger.montgomeryMultiply intrinsic
aph
parents: 31146
diff changeset
  2997
        b = montReduce(t2, mod, modLen, (int)inv);
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2998
10425
7903cf45f96f 6989067: BigInteger's array copiers should be converted to System.arraycopy()
darcy
parents: 10423
diff changeset
  2999
        t2 = Arrays.copyOf(b, modLen);
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3000
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3001
        return new BigInteger(1, t2);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3002
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3003
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3004
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3005
     * Montgomery reduce n, modulo mod.  This reduces modulo mod and divides
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3006
     * by 2^(32*mlen). Adapted from Colin Plumb's C library.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3007
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3008
    private static int[] montReduce(int[] n, int[] mod, int mlen, int inv) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3009
        int c=0;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3010
        int len = mlen;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3011
        int offset=0;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3012
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3013
        do {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3014
            int nEnd = n[n.length-1-offset];
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3015
            int carry = mulAdd(n, mod, offset, mlen, inv * nEnd);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3016
            c += addOne(n, offset, mlen, carry);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3017
            offset++;
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  3018
        } while (--len > 0);
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  3019
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  3020
        while (c > 0)
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3021
            c += subN(n, mod, mlen);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3022
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3023
        while (intArrayCmpToLen(n, mod, mlen) >= 0)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3024
            subN(n, mod, mlen);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3025
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3026
        return n;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3027
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3028
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3029
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3030
    /*
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3031
     * Returns -1, 0 or +1 as big-endian unsigned int array arg1 is less than,
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3032
     * equal to, or greater than arg2 up to length len.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3033
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3034
    private static int intArrayCmpToLen(int[] arg1, int[] arg2, int len) {
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  3035
        for (int i=0; i < len; i++) {
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3036
            long b1 = arg1[i] & LONG_MASK;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3037
            long b2 = arg2[i] & LONG_MASK;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3038
            if (b1 < b2)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3039
                return -1;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3040
            if (b1 > b2)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3041
                return 1;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3042
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3043
        return 0;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3044
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3045
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3046
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3047
     * Subtracts two numbers of same length, returning borrow.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3048
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3049
    private static int subN(int[] a, int[] b, int len) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3050
        long sum = 0;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3051
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  3052
        while (--len >= 0) {
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3053
            sum = (a[len] & LONG_MASK) -
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3054
                 (b[len] & LONG_MASK) + (sum >> 32);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3055
            a[len] = (int)sum;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3056
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3057
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3058
        return (int)(sum >> 32);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3059
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3060
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3061
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3062
     * Multiply an array by one word k and add to result, return the carry
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3063
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3064
    static int mulAdd(int[] out, int[] in, int offset, int len, int k) {
31146
22d69730ee60 8081778: Use Intel x64 CPU instructions for RSA acceleration
kvn
parents: 29220
diff changeset
  3065
        implMulAddCheck(out, in, offset, len, k);
22d69730ee60 8081778: Use Intel x64 CPU instructions for RSA acceleration
kvn
parents: 29220
diff changeset
  3066
        return implMulAdd(out, in, offset, len, k);
22d69730ee60 8081778: Use Intel x64 CPU instructions for RSA acceleration
kvn
parents: 29220
diff changeset
  3067
    }
22d69730ee60 8081778: Use Intel x64 CPU instructions for RSA acceleration
kvn
parents: 29220
diff changeset
  3068
22d69730ee60 8081778: Use Intel x64 CPU instructions for RSA acceleration
kvn
parents: 29220
diff changeset
  3069
    /**
22d69730ee60 8081778: Use Intel x64 CPU instructions for RSA acceleration
kvn
parents: 29220
diff changeset
  3070
     * Parameters validation.
22d69730ee60 8081778: Use Intel x64 CPU instructions for RSA acceleration
kvn
parents: 29220
diff changeset
  3071
     */
22d69730ee60 8081778: Use Intel x64 CPU instructions for RSA acceleration
kvn
parents: 29220
diff changeset
  3072
    private static void implMulAddCheck(int[] out, int[] in, int offset, int len, int k) {
22d69730ee60 8081778: Use Intel x64 CPU instructions for RSA acceleration
kvn
parents: 29220
diff changeset
  3073
        if (len > in.length) {
22d69730ee60 8081778: Use Intel x64 CPU instructions for RSA acceleration
kvn
parents: 29220
diff changeset
  3074
            throw new IllegalArgumentException("input length is out of bound: " + len + " > " + in.length);
22d69730ee60 8081778: Use Intel x64 CPU instructions for RSA acceleration
kvn
parents: 29220
diff changeset
  3075
        }
22d69730ee60 8081778: Use Intel x64 CPU instructions for RSA acceleration
kvn
parents: 29220
diff changeset
  3076
        if (offset < 0) {
22d69730ee60 8081778: Use Intel x64 CPU instructions for RSA acceleration
kvn
parents: 29220
diff changeset
  3077
            throw new IllegalArgumentException("input offset is invalid: " + offset);
22d69730ee60 8081778: Use Intel x64 CPU instructions for RSA acceleration
kvn
parents: 29220
diff changeset
  3078
        }
22d69730ee60 8081778: Use Intel x64 CPU instructions for RSA acceleration
kvn
parents: 29220
diff changeset
  3079
        if (offset > (out.length - 1)) {
22d69730ee60 8081778: Use Intel x64 CPU instructions for RSA acceleration
kvn
parents: 29220
diff changeset
  3080
            throw new IllegalArgumentException("input offset is out of bound: " + offset + " > " + (out.length - 1));
22d69730ee60 8081778: Use Intel x64 CPU instructions for RSA acceleration
kvn
parents: 29220
diff changeset
  3081
        }
22d69730ee60 8081778: Use Intel x64 CPU instructions for RSA acceleration
kvn
parents: 29220
diff changeset
  3082
        if (len > (out.length - offset)) {
22d69730ee60 8081778: Use Intel x64 CPU instructions for RSA acceleration
kvn
parents: 29220
diff changeset
  3083
            throw new IllegalArgumentException("input len is out of bound: " + len + " > " + (out.length - offset));
22d69730ee60 8081778: Use Intel x64 CPU instructions for RSA acceleration
kvn
parents: 29220
diff changeset
  3084
        }
22d69730ee60 8081778: Use Intel x64 CPU instructions for RSA acceleration
kvn
parents: 29220
diff changeset
  3085
    }
22d69730ee60 8081778: Use Intel x64 CPU instructions for RSA acceleration
kvn
parents: 29220
diff changeset
  3086
22d69730ee60 8081778: Use Intel x64 CPU instructions for RSA acceleration
kvn
parents: 29220
diff changeset
  3087
    /**
22d69730ee60 8081778: Use Intel x64 CPU instructions for RSA acceleration
kvn
parents: 29220
diff changeset
  3088
     * Java Runtime may use intrinsic for this method.
22d69730ee60 8081778: Use Intel x64 CPU instructions for RSA acceleration
kvn
parents: 29220
diff changeset
  3089
     */
31671
362e0c0acece 8076112: Add @HotSpotIntrinsicCandidate annotation to indicate methods for which Java Runtime has intrinsics
zmajo
parents: 31667
diff changeset
  3090
    @HotSpotIntrinsicCandidate
31146
22d69730ee60 8081778: Use Intel x64 CPU instructions for RSA acceleration
kvn
parents: 29220
diff changeset
  3091
    private static int implMulAdd(int[] out, int[] in, int offset, int len, int k) {
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3092
        long kLong = k & LONG_MASK;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3093
        long carry = 0;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3094
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3095
        offset = out.length-offset - 1;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3096
        for (int j=len-1; j >= 0; j--) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3097
            long product = (in[j] & LONG_MASK) * kLong +
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3098
                           (out[offset] & LONG_MASK) + carry;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3099
            out[offset--] = (int)product;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3100
            carry = product >>> 32;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3101
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3102
        return (int)carry;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3103
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3104
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3105
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3106
     * Add one word to the number a mlen words into a. Return the resulting
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3107
     * carry.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3108
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3109
    static int addOne(int[] a, int offset, int mlen, int carry) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3110
        offset = a.length-1-mlen-offset;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3111
        long t = (a[offset] & LONG_MASK) + (carry & LONG_MASK);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3112
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3113
        a[offset] = (int)t;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3114
        if ((t >>> 32) == 0)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3115
            return 0;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3116
        while (--mlen >= 0) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3117
            if (--offset < 0) { // Carry out of number
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3118
                return 1;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3119
            } else {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3120
                a[offset]++;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3121
                if (a[offset] != 0)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3122
                    return 0;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3123
            }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3124
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3125
        return 1;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3126
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3127
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3128
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3129
     * Returns a BigInteger whose value is (this ** exponent) mod (2**p)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3130
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3131
    private BigInteger modPow2(BigInteger exponent, int p) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3132
        /*
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3133
         * Perform exponentiation using repeated squaring trick, chopping off
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3134
         * high order bits as indicated by modulus.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3135
         */
18286
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  3136
        BigInteger result = ONE;
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3137
        BigInteger baseToPow2 = this.mod2(p);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3138
        int expOffset = 0;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3139
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3140
        int limit = exponent.bitLength();
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3141
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3142
        if (this.testBit(0))
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3143
           limit = (p-1) < limit ? (p-1) : limit;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3144
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3145
        while (expOffset < limit) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3146
            if (exponent.testBit(expOffset))
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3147
                result = result.multiply(baseToPow2).mod2(p);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3148
            expOffset++;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3149
            if (expOffset < limit)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3150
                baseToPow2 = baseToPow2.square().mod2(p);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3151
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3152
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3153
        return result;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3154
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3155
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3156
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3157
     * Returns a BigInteger whose value is this mod(2**p).
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3158
     * Assumes that this {@code BigInteger >= 0} and {@code p > 0}.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3159
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3160
    private BigInteger mod2(int p) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3161
        if (bitLength() <= p)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3162
            return this;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3163
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3164
        // Copy remaining ints of mag
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  3165
        int numInts = (p + 31) >>> 5;
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3166
        int[] mag = new int[numInts];
10425
7903cf45f96f 6989067: BigInteger's array copiers should be converted to System.arraycopy()
darcy
parents: 10423
diff changeset
  3167
        System.arraycopy(this.mag, (this.mag.length - numInts), mag, 0, numInts);
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3168
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3169
        // Mask out any excess bits
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3170
        int excessBits = (numInts << 5) - p;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3171
        mag[0] &= (1L << (32-excessBits)) - 1;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3172
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  3173
        return (mag[0] == 0 ? new BigInteger(1, mag) : new BigInteger(mag, 1));
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3174
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3175
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3176
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3177
     * Returns a BigInteger whose value is {@code (this}<sup>-1</sup> {@code mod m)}.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3178
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3179
     * @param  m the modulus.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3180
     * @return {@code this}<sup>-1</sup> {@code mod m}.
4160
bda0a85afcb7 6560935: BigInteger.modPow() throws ArithmeticException for negative exponent
darcy
parents: 4151
diff changeset
  3181
     * @throws ArithmeticException {@code  m} &le; 0, or this BigInteger
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3182
     *         has no multiplicative inverse mod m (that is, this BigInteger
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3183
     *         is not <i>relatively prime</i> to m).
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3184
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3185
    public BigInteger modInverse(BigInteger m) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3186
        if (m.signum != 1)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3187
            throw new ArithmeticException("BigInteger: modulus not positive");
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3188
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3189
        if (m.equals(ONE))
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3190
            return ZERO;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3191
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3192
        // Calculate (this mod m)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3193
        BigInteger modVal = this;
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  3194
        if (signum < 0 || (this.compareMagnitude(m) >= 0))
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3195
            modVal = this.mod(m);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3196
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3197
        if (modVal.equals(ONE))
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3198
            return ONE;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3199
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3200
        MutableBigInteger a = new MutableBigInteger(modVal);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3201
        MutableBigInteger b = new MutableBigInteger(m);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3202
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3203
        MutableBigInteger result = a.mutableModInverse(b);
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  3204
        return result.toBigInteger(1);
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3205
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3206
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3207
    // Shift Operations
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3208
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3209
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3210
     * Returns a BigInteger whose value is {@code (this << n)}.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3211
     * The shift distance, {@code n}, may be negative, in which case
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3212
     * this method performs a right shift.
32033
bf24e33c7919 8132468: docs: replace <tt> tags (obsolete in html5) for java.io, java.lang, java.math
avstepan
parents: 31671
diff changeset
  3213
     * (Computes <code>floor(this * 2<sup>n</sup>)</code>.)
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3214
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3215
     * @param  n shift distance, in bits.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3216
     * @return {@code this << n}
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3217
     * @see #shiftRight
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3218
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3219
    public BigInteger shiftLeft(int n) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3220
        if (signum == 0)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3221
            return ZERO;
21420
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
  3222
        if (n > 0) {
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
  3223
            return new BigInteger(shiftLeft(mag, n), signum);
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
  3224
        } else if (n == 0) {
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3225
            return this;
21420
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
  3226
        } else {
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
  3227
            // Possible int overflow in (-n) is not a trouble,
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
  3228
            // because shiftRightImpl considers its argument unsigned
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
  3229
            return shiftRightImpl(-n);
4151
db7d59c0b0e6 6371401: java.math.BigInteger.shift(Integer.MIN_VALUE) throws StackOverflowError
darcy
parents: 2922
diff changeset
  3230
        }
10423
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  3231
    }
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  3232
21420
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
  3233
    /**
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
  3234
     * Returns a magnitude array whose value is {@code (mag << n)}.
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
  3235
     * The shift distance, {@code n}, is considered unnsigned.
32033
bf24e33c7919 8132468: docs: replace <tt> tags (obsolete in html5) for java.io, java.lang, java.math
avstepan
parents: 31671
diff changeset
  3236
     * (Computes <code>this * 2<sup>n</sup></code>.)
21420
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
  3237
     *
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
  3238
     * @param mag magnitude, the most-significant int ({@code mag[0]}) must be non-zero.
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
  3239
     * @param  n unsigned shift distance, in bits.
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
  3240
     * @return {@code mag << n}
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
  3241
     */
10423
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  3242
    private static int[] shiftLeft(int[] mag, int n) {
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3243
        int nInts = n >>> 5;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3244
        int nBits = n & 0x1f;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3245
        int magLen = mag.length;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3246
        int newMag[] = null;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3247
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3248
        if (nBits == 0) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3249
            newMag = new int[magLen + nInts];
10425
7903cf45f96f 6989067: BigInteger's array copiers should be converted to System.arraycopy()
darcy
parents: 10423
diff changeset
  3250
            System.arraycopy(mag, 0, newMag, 0, magLen);
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3251
        } else {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3252
            int i = 0;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3253
            int nBits2 = 32 - nBits;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3254
            int highBits = mag[0] >>> nBits2;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3255
            if (highBits != 0) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3256
                newMag = new int[magLen + nInts + 1];
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3257
                newMag[i++] = highBits;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3258
            } else {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3259
                newMag = new int[magLen + nInts];
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3260
            }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3261
            int j=0;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3262
            while (j < magLen-1)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3263
                newMag[i++] = mag[j++] << nBits | mag[j] >>> nBits2;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3264
            newMag[i] = mag[j] << nBits;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3265
        }
10423
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  3266
        return newMag;
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3267
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3268
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3269
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3270
     * Returns a BigInteger whose value is {@code (this >> n)}.  Sign
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3271
     * extension is performed.  The shift distance, {@code n}, may be
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3272
     * negative, in which case this method performs a left shift.
32033
bf24e33c7919 8132468: docs: replace <tt> tags (obsolete in html5) for java.io, java.lang, java.math
avstepan
parents: 31671
diff changeset
  3273
     * (Computes <code>floor(this / 2<sup>n</sup>)</code>.)
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3274
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3275
     * @param  n shift distance, in bits.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3276
     * @return {@code this >> n}
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3277
     * @see #shiftLeft
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3278
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3279
    public BigInteger shiftRight(int n) {
21420
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
  3280
        if (signum == 0)
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
  3281
            return ZERO;
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
  3282
        if (n > 0) {
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
  3283
            return shiftRightImpl(n);
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
  3284
        } else if (n == 0) {
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3285
            return this;
21420
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
  3286
        } else {
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
  3287
            // Possible int overflow in {@code -n} is not a trouble,
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
  3288
            // because shiftLeft considers its argument unsigned
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
  3289
            return new BigInteger(shiftLeft(mag, -n), signum);
4151
db7d59c0b0e6 6371401: java.math.BigInteger.shift(Integer.MIN_VALUE) throws StackOverflowError
darcy
parents: 2922
diff changeset
  3290
        }
21420
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
  3291
    }
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
  3292
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
  3293
    /**
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
  3294
     * Returns a BigInteger whose value is {@code (this >> n)}. The shift
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
  3295
     * distance, {@code n}, is considered unsigned.
32033
bf24e33c7919 8132468: docs: replace <tt> tags (obsolete in html5) for java.io, java.lang, java.math
avstepan
parents: 31671
diff changeset
  3296
     * (Computes <code>floor(this * 2<sup>-n</sup>)</code>.)
21420
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
  3297
     *
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
  3298
     * @param  n unsigned shift distance, in bits.
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
  3299
     * @return {@code this >> n}
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
  3300
     */
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
  3301
    private BigInteger shiftRightImpl(int n) {
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3302
        int nInts = n >>> 5;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3303
        int nBits = n & 0x1f;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3304
        int magLen = mag.length;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3305
        int newMag[] = null;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3306
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3307
        // Special case: entire contents shifted off the end
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3308
        if (nInts >= magLen)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3309
            return (signum >= 0 ? ZERO : negConst[1]);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3310
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3311
        if (nBits == 0) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3312
            int newMagLen = magLen - nInts;
10425
7903cf45f96f 6989067: BigInteger's array copiers should be converted to System.arraycopy()
darcy
parents: 10423
diff changeset
  3313
            newMag = Arrays.copyOf(mag, newMagLen);
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3314
        } else {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3315
            int i = 0;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3316
            int highBits = mag[0] >>> nBits;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3317
            if (highBits != 0) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3318
                newMag = new int[magLen - nInts];
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3319
                newMag[i++] = highBits;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3320
            } else {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3321
                newMag = new int[magLen - nInts -1];
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3322
            }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3323
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3324
            int nBits2 = 32 - nBits;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3325
            int j=0;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3326
            while (j < magLen - nInts - 1)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3327
                newMag[i++] = (mag[j++] << nBits2) | (mag[j] >>> nBits);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3328
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3329
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3330
        if (signum < 0) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3331
            // Find out whether any one-bits were shifted off the end.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3332
            boolean onesLost = false;
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  3333
            for (int i=magLen-1, j=magLen-nInts; i >= j && !onesLost; i--)
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3334
                onesLost = (mag[i] != 0);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3335
            if (!onesLost && nBits != 0)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3336
                onesLost = (mag[magLen - nInts - 1] << (32 - nBits) != 0);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3337
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3338
            if (onesLost)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3339
                newMag = javaIncrement(newMag);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3340
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3341
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3342
        return new BigInteger(newMag, signum);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3343
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3344
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3345
    int[] javaIncrement(int[] val) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3346
        int lastSum = 0;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3347
        for (int i=val.length-1;  i >= 0 && lastSum == 0; i--)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3348
            lastSum = (val[i] += 1);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3349
        if (lastSum == 0) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3350
            val = new int[val.length+1];
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3351
            val[0] = 1;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3352
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3353
        return val;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3354
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3355
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3356
    // Bitwise Operations
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3357
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3358
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3359
     * Returns a BigInteger whose value is {@code (this & val)}.  (This
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3360
     * method returns a negative BigInteger if and only if this and val are
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3361
     * both negative.)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3362
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3363
     * @param val value to be AND'ed with this BigInteger.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3364
     * @return {@code this & val}
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3365
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3366
    public BigInteger and(BigInteger val) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3367
        int[] result = new int[Math.max(intLength(), val.intLength())];
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  3368
        for (int i=0; i < result.length; i++)
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3369
            result[i] = (getInt(result.length-i-1)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3370
                         & val.getInt(result.length-i-1));
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3371
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3372
        return valueOf(result);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3373
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3374
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3375
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3376
     * Returns a BigInteger whose value is {@code (this | val)}.  (This method
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3377
     * returns a negative BigInteger if and only if either this or val is
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3378
     * negative.)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3379
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3380
     * @param val value to be OR'ed with this BigInteger.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3381
     * @return {@code this | val}
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3382
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3383
    public BigInteger or(BigInteger val) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3384
        int[] result = new int[Math.max(intLength(), val.intLength())];
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  3385
        for (int i=0; i < result.length; i++)
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3386
            result[i] = (getInt(result.length-i-1)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3387
                         | val.getInt(result.length-i-1));
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3388
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3389
        return valueOf(result);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3390
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3391
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3392
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3393
     * Returns a BigInteger whose value is {@code (this ^ val)}.  (This method
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3394
     * returns a negative BigInteger if and only if exactly one of this and
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3395
     * val are negative.)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3396
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3397
     * @param val value to be XOR'ed with this BigInteger.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3398
     * @return {@code this ^ val}
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3399
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3400
    public BigInteger xor(BigInteger val) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3401
        int[] result = new int[Math.max(intLength(), val.intLength())];
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  3402
        for (int i=0; i < result.length; i++)
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3403
            result[i] = (getInt(result.length-i-1)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3404
                         ^ val.getInt(result.length-i-1));
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3405
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3406
        return valueOf(result);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3407
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3408
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3409
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3410
     * Returns a BigInteger whose value is {@code (~this)}.  (This method
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3411
     * returns a negative value if and only if this BigInteger is
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3412
     * non-negative.)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3413
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3414
     * @return {@code ~this}
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3415
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3416
    public BigInteger not() {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3417
        int[] result = new int[intLength()];
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  3418
        for (int i=0; i < result.length; i++)
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3419
            result[i] = ~getInt(result.length-i-1);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3420
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3421
        return valueOf(result);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3422
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3423
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3424
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3425
     * Returns a BigInteger whose value is {@code (this & ~val)}.  This
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3426
     * method, which is equivalent to {@code and(val.not())}, is provided as
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3427
     * a convenience for masking operations.  (This method returns a negative
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3428
     * BigInteger if and only if {@code this} is negative and {@code val} is
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3429
     * positive.)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3430
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3431
     * @param val value to be complemented and AND'ed with this BigInteger.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3432
     * @return {@code this & ~val}
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3433
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3434
    public BigInteger andNot(BigInteger val) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3435
        int[] result = new int[Math.max(intLength(), val.intLength())];
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  3436
        for (int i=0; i < result.length; i++)
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3437
            result[i] = (getInt(result.length-i-1)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3438
                         & ~val.getInt(result.length-i-1));
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3439
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3440
        return valueOf(result);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3441
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3442
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3443
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3444
    // Single Bit Operations
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3445
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3446
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3447
     * Returns {@code true} if and only if the designated bit is set.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3448
     * (Computes {@code ((this & (1<<n)) != 0)}.)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3449
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3450
     * @param  n index of bit to test.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3451
     * @return {@code true} if and only if the designated bit is set.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3452
     * @throws ArithmeticException {@code n} is negative.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3453
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3454
    public boolean testBit(int n) {
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  3455
        if (n < 0)
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3456
            throw new ArithmeticException("Negative bit address");
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3457
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  3458
        return (getInt(n >>> 5) & (1 << (n & 31))) != 0;
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3459
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3460
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3461
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3462
     * Returns a BigInteger whose value is equivalent to this BigInteger
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3463
     * with the designated bit set.  (Computes {@code (this | (1<<n))}.)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3464
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3465
     * @param  n index of bit to set.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3466
     * @return {@code this | (1<<n)}
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3467
     * @throws ArithmeticException {@code n} is negative.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3468
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3469
    public BigInteger setBit(int n) {
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  3470
        if (n < 0)
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3471
            throw new ArithmeticException("Negative bit address");
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3472
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  3473
        int intNum = n >>> 5;
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3474
        int[] result = new int[Math.max(intLength(), intNum+2)];
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3475
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  3476
        for (int i=0; i < result.length; i++)
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3477
            result[result.length-i-1] = getInt(i);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3478
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  3479
        result[result.length-intNum-1] |= (1 << (n & 31));
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3480
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3481
        return valueOf(result);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3482
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3483
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3484
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3485
     * Returns a BigInteger whose value is equivalent to this BigInteger
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3486
     * with the designated bit cleared.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3487
     * (Computes {@code (this & ~(1<<n))}.)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3488
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3489
     * @param  n index of bit to clear.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3490
     * @return {@code this & ~(1<<n)}
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3491
     * @throws ArithmeticException {@code n} is negative.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3492
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3493
    public BigInteger clearBit(int n) {
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  3494
        if (n < 0)
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3495
            throw new ArithmeticException("Negative bit address");
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3496
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  3497
        int intNum = n >>> 5;
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  3498
        int[] result = new int[Math.max(intLength(), ((n + 1) >>> 5) + 1)];
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3499
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  3500
        for (int i=0; i < result.length; i++)
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3501
            result[result.length-i-1] = getInt(i);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3502
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  3503
        result[result.length-intNum-1] &= ~(1 << (n & 31));
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3504
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3505
        return valueOf(result);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3506
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3507
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3508
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3509
     * Returns a BigInteger whose value is equivalent to this BigInteger
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3510
     * with the designated bit flipped.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3511
     * (Computes {@code (this ^ (1<<n))}.)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3512
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3513
     * @param  n index of bit to flip.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3514
     * @return {@code this ^ (1<<n)}
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3515
     * @throws ArithmeticException {@code n} is negative.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3516
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3517
    public BigInteger flipBit(int n) {
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  3518
        if (n < 0)
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3519
            throw new ArithmeticException("Negative bit address");
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3520
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  3521
        int intNum = n >>> 5;
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3522
        int[] result = new int[Math.max(intLength(), intNum+2)];
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3523
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  3524
        for (int i=0; i < result.length; i++)
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3525
            result[result.length-i-1] = getInt(i);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3526
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  3527
        result[result.length-intNum-1] ^= (1 << (n & 31));
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3528
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3529
        return valueOf(result);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3530
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3531
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3532
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3533
     * Returns the index of the rightmost (lowest-order) one bit in this
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3534
     * BigInteger (the number of zero bits to the right of the rightmost
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3535
     * one bit).  Returns -1 if this BigInteger contains no one bits.
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  3536
     * (Computes {@code (this == 0? -1 : log2(this & -this))}.)
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3537
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3538
     * @return index of the rightmost one bit in this BigInteger.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3539
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3540
    public int getLowestSetBit() {
23332
c36c4773fe96 8035279: Clean up internal deprecations in BigInteger
bpb
parents: 22042
diff changeset
  3541
        int lsb = lowestSetBitPlusTwo - 2;
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  3542
        if (lsb == -2) {  // lowestSetBit not initialized yet
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  3543
            lsb = 0;
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3544
            if (signum == 0) {
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  3545
                lsb -= 1;
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3546
            } else {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3547
                // Search for lowest order nonzero int
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3548
                int i,b;
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  3549
                for (i=0; (b = getInt(i)) == 0; i++)
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3550
                    ;
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  3551
                lsb += (i << 5) + Integer.numberOfTrailingZeros(b);
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3552
            }
23332
c36c4773fe96 8035279: Clean up internal deprecations in BigInteger
bpb
parents: 22042
diff changeset
  3553
            lowestSetBitPlusTwo = lsb + 2;
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3554
        }
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  3555
        return lsb;
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3556
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3557
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3558
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3559
    // Miscellaneous Bit Operations
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3560
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3561
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3562
     * Returns the number of bits in the minimal two's-complement
38553
0553095041d7 8157724: Improve javadoc tag usage in java.math
darcy
parents: 37880
diff changeset
  3563
     * representation of this BigInteger, <em>excluding</em> a sign bit.
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3564
     * For positive BigIntegers, this is equivalent to the number of bits in
49237
6e6c3a755b89 8199258: BigInteger.bitLength() should explicitly specify behavior when the value is zero
bpb
parents: 47866
diff changeset
  3565
     * the ordinary binary representation.  For zero this method returns
6e6c3a755b89 8199258: BigInteger.bitLength() should explicitly specify behavior when the value is zero
bpb
parents: 47866
diff changeset
  3566
     * {@code 0}.  (Computes {@code (ceil(log2(this < 0 ? -this : this+1)))}.)
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3567
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3568
     * @return number of bits in the minimal two's-complement
38553
0553095041d7 8157724: Improve javadoc tag usage in java.math
darcy
parents: 37880
diff changeset
  3569
     *         representation of this BigInteger, <em>excluding</em> a sign bit.
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3570
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3571
    public int bitLength() {
23332
c36c4773fe96 8035279: Clean up internal deprecations in BigInteger
bpb
parents: 22042
diff changeset
  3572
        int n = bitLengthPlusOne - 1;
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  3573
        if (n == -1) { // bitLength not initialized yet
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  3574
            int[] m = mag;
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  3575
            int len = m.length;
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  3576
            if (len == 0) {
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  3577
                n = 0; // offset by one to initialize
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  3578
            }  else {
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3579
                // Calculate the bit length of the magnitude
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  3580
                int magBitLength = ((len - 1) << 5) + bitLengthForInt(mag[0]);
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  3581
                 if (signum < 0) {
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  3582
                     // Check if magnitude is a power of two
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  3583
                     boolean pow2 = (Integer.bitCount(mag[0]) == 1);
10425
7903cf45f96f 6989067: BigInteger's array copiers should be converted to System.arraycopy()
darcy
parents: 10423
diff changeset
  3584
                     for (int i=1; i< len && pow2; i++)
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  3585
                         pow2 = (mag[i] == 0);
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  3586
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  3587
                     n = (pow2 ? magBitLength -1 : magBitLength);
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  3588
                 } else {
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  3589
                     n = magBitLength;
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  3590
                 }
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3591
            }
23332
c36c4773fe96 8035279: Clean up internal deprecations in BigInteger
bpb
parents: 22042
diff changeset
  3592
            bitLengthPlusOne = n + 1;
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3593
        }
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  3594
        return n;
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3595
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3596
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3597
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3598
     * Returns the number of bits in the two's complement representation
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3599
     * of this BigInteger that differ from its sign bit.  This method is
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3600
     * useful when implementing bit-vector style sets atop BigIntegers.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3601
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3602
     * @return number of bits in the two's complement representation
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3603
     *         of this BigInteger that differ from its sign bit.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3604
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3605
    public int bitCount() {
23332
c36c4773fe96 8035279: Clean up internal deprecations in BigInteger
bpb
parents: 22042
diff changeset
  3606
        int bc = bitCountPlusOne - 1;
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  3607
        if (bc == -1) {  // bitCount not initialized yet
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  3608
            bc = 0;      // offset by one to initialize
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3609
            // Count the bits in the magnitude
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  3610
            for (int i=0; i < mag.length; i++)
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  3611
                bc += Integer.bitCount(mag[i]);
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3612
            if (signum < 0) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3613
                // Count the trailing zeros in the magnitude
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3614
                int magTrailingZeroCount = 0, j;
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  3615
                for (j=mag.length-1; mag[j] == 0; j--)
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3616
                    magTrailingZeroCount += 32;
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  3617
                magTrailingZeroCount += Integer.numberOfTrailingZeros(mag[j]);
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  3618
                bc += magTrailingZeroCount - 1;
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3619
            }
23332
c36c4773fe96 8035279: Clean up internal deprecations in BigInteger
bpb
parents: 22042
diff changeset
  3620
            bitCountPlusOne = bc + 1;
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3621
        }
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  3622
        return bc;
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3623
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3624
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3625
    // Primality Testing
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3626
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3627
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3628
     * Returns {@code true} if this BigInteger is probably prime,
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3629
     * {@code false} if it's definitely composite.  If
4160
bda0a85afcb7 6560935: BigInteger.modPow() throws ArithmeticException for negative exponent
darcy
parents: 4151
diff changeset
  3630
     * {@code certainty} is &le; 0, {@code true} is
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3631
     * returned.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3632
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3633
     * @param  certainty a measure of the uncertainty that the caller is
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3634
     *         willing to tolerate: if the call returns {@code true}
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3635
     *         the probability that this BigInteger is prime exceeds
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3636
     *         (1 - 1/2<sup>{@code certainty}</sup>).  The execution time of
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3637
     *         this method is proportional to the value of this parameter.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3638
     * @return {@code true} if this BigInteger is probably prime,
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3639
     *         {@code false} if it's definitely composite.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3640
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3641
    public boolean isProbablePrime(int certainty) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3642
        if (certainty <= 0)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3643
            return true;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3644
        BigInteger w = this.abs();
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3645
        if (w.equals(TWO))
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3646
            return true;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3647
        if (!w.testBit(0) || w.equals(ONE))
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3648
            return false;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3649
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3650
        return w.primeToCertainty(certainty, null);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3651
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3652
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3653
    // Comparison Operations
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3654
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3655
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3656
     * Compares this BigInteger with the specified BigInteger.  This
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3657
     * method is provided in preference to individual methods for each
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3658
     * of the six boolean comparison operators ({@literal <}, ==,
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3659
     * {@literal >}, {@literal >=}, !=, {@literal <=}).  The suggested
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3660
     * idiom for performing these comparisons is: {@code
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3661
     * (x.compareTo(y)} &lt;<i>op</i>&gt; {@code 0)}, where
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3662
     * &lt;<i>op</i>&gt; is one of the six comparison operators.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3663
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3664
     * @param  val BigInteger to which this BigInteger is to be compared.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3665
     * @return -1, 0 or 1 as this BigInteger is numerically less than, equal
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3666
     *         to, or greater than {@code val}.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3667
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3668
    public int compareTo(BigInteger val) {
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  3669
        if (signum == val.signum) {
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  3670
            switch (signum) {
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  3671
            case 1:
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  3672
                return compareMagnitude(val);
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  3673
            case -1:
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  3674
                return val.compareMagnitude(this);
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  3675
            default:
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  3676
                return 0;
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  3677
            }
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  3678
        }
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  3679
        return signum > val.signum ? 1 : -1;
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3680
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3681
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  3682
    /**
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  3683
     * Compares the magnitude array of this BigInteger with the specified
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  3684
     * BigInteger's. This is the version of compareTo ignoring sign.
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  3685
     *
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  3686
     * @param val BigInteger whose magnitude array to be compared.
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  3687
     * @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
  3688
     *         greater than the magnitude aray for the specified BigInteger's.
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3689
     */
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  3690
    final int compareMagnitude(BigInteger val) {
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  3691
        int[] m1 = mag;
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  3692
        int len1 = m1.length;
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  3693
        int[] m2 = val.mag;
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  3694
        int len2 = m2.length;
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  3695
        if (len1 < len2)
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3696
            return -1;
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  3697
        if (len1 > len2)
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3698
            return 1;
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  3699
        for (int i = 0; i < len1; i++) {
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  3700
            int a = m1[i];
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  3701
            int b = m2[i];
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  3702
            if (a != b)
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  3703
                return ((a & LONG_MASK) < (b & LONG_MASK)) ? -1 : 1;
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3704
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3705
        return 0;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3706
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3707
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3708
    /**
10423
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  3709
     * Version of compareMagnitude that compares magnitude with long value.
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  3710
     * val can't be Long.MIN_VALUE.
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  3711
     */
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  3712
    final int compareMagnitude(long val) {
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  3713
        assert val != Long.MIN_VALUE;
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  3714
        int[] m1 = mag;
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  3715
        int len = m1.length;
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  3716
        if (len > 2) {
10423
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  3717
            return 1;
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  3718
        }
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  3719
        if (val < 0) {
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  3720
            val = -val;
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  3721
        }
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  3722
        int highWord = (int)(val >>> 32);
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  3723
        if (highWord == 0) {
10423
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  3724
            if (len < 1)
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  3725
                return -1;
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  3726
            if (len > 1)
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  3727
                return 1;
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  3728
            int a = m1[0];
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  3729
            int b = (int)val;
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  3730
            if (a != b) {
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  3731
                return ((a & LONG_MASK) < (b & LONG_MASK))? -1 : 1;
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  3732
            }
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  3733
            return 0;
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  3734
        } else {
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  3735
            if (len < 2)
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  3736
                return -1;
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  3737
            int a = m1[0];
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  3738
            int b = highWord;
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  3739
            if (a != b) {
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  3740
                return ((a & LONG_MASK) < (b & LONG_MASK))? -1 : 1;
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  3741
            }
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  3742
            a = m1[1];
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  3743
            b = (int)val;
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  3744
            if (a != b) {
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  3745
                return ((a & LONG_MASK) < (b & LONG_MASK))? -1 : 1;
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  3746
            }
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  3747
            return 0;
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  3748
        }
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  3749
    }
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  3750
2c852092a4e5 7082971: More performance tuning of BigDecimal and other java.math classes
darcy
parents: 9266
diff changeset
  3751
    /**
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3752
     * Compares this BigInteger with the specified Object for equality.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3753
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3754
     * @param  x Object to which this BigInteger is to be compared.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3755
     * @return {@code true} if and only if the specified Object is a
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3756
     *         BigInteger whose value is numerically equal to this BigInteger.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3757
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3758
    public boolean equals(Object x) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3759
        // This test is just an optimization, which may or may not help
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3760
        if (x == this)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3761
            return true;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3762
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3763
        if (!(x instanceof BigInteger))
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3764
            return false;
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  3765
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3766
        BigInteger xInt = (BigInteger) x;
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  3767
        if (xInt.signum != signum)
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3768
            return false;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3769
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  3770
        int[] m = mag;
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  3771
        int len = m.length;
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  3772
        int[] xm = xInt.mag;
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  3773
        if (len != xm.length)
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  3774
            return false;
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  3775
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  3776
        for (int i = 0; i < len; i++)
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  3777
            if (xm[i] != m[i])
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3778
                return false;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3779
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3780
        return true;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3781
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3782
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3783
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3784
     * Returns the minimum of this BigInteger and {@code val}.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3785
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3786
     * @param  val value with which the minimum is to be computed.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3787
     * @return the BigInteger whose value is the lesser of this BigInteger and
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3788
     *         {@code val}.  If they are equal, either may be returned.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3789
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3790
    public BigInteger min(BigInteger val) {
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  3791
        return (compareTo(val) < 0 ? this : val);
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3792
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3793
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3794
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3795
     * Returns the maximum of this BigInteger and {@code val}.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3796
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3797
     * @param  val value with which the maximum is to be computed.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3798
     * @return the BigInteger whose value is the greater of this and
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3799
     *         {@code val}.  If they are equal, either may be returned.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3800
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3801
    public BigInteger max(BigInteger val) {
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  3802
        return (compareTo(val) > 0 ? this : val);
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3803
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3804
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3805
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3806
    // Hash Function
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3807
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3808
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3809
     * Returns the hash code for this BigInteger.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3810
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3811
     * @return hash code for this BigInteger.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3812
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3813
    public int hashCode() {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3814
        int hashCode = 0;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3815
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  3816
        for (int i=0; i < mag.length; i++)
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3817
            hashCode = (int)(31*hashCode + (mag[i] & LONG_MASK));
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3818
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3819
        return hashCode * signum;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3820
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3821
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3822
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3823
     * Returns the String representation of this BigInteger in the
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3824
     * given radix.  If the radix is outside the range from {@link
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3825
     * Character#MIN_RADIX} to {@link Character#MAX_RADIX} inclusive,
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3826
     * it will default to 10 (as is the case for
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3827
     * {@code Integer.toString}).  The digit-to-character mapping
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3828
     * provided by {@code Character.forDigit} is used, and a minus
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3829
     * sign is prepended if appropriate.  (This representation is
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3830
     * compatible with the {@link #BigInteger(String, int) (String,
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3831
     * int)} constructor.)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3832
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3833
     * @param  radix  radix of the String representation.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3834
     * @return String representation of this BigInteger in the given radix.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3835
     * @see    Integer#toString
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3836
     * @see    Character#forDigit
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3837
     * @see    #BigInteger(java.lang.String, int)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3838
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3839
    public String toString(int radix) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3840
        if (signum == 0)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3841
            return "0";
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3842
        if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3843
            radix = 10;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3844
18548
0b6ca9785d8c 4641897: Faster string conversion of large integers
bpb
parents: 18538
diff changeset
  3845
        // If it's small enough, use smallToString.
0b6ca9785d8c 4641897: Faster string conversion of large integers
bpb
parents: 18538
diff changeset
  3846
        if (mag.length <= SCHOENHAGE_BASE_CONVERSION_THRESHOLD)
0b6ca9785d8c 4641897: Faster string conversion of large integers
bpb
parents: 18538
diff changeset
  3847
           return smallToString(radix);
0b6ca9785d8c 4641897: Faster string conversion of large integers
bpb
parents: 18538
diff changeset
  3848
0b6ca9785d8c 4641897: Faster string conversion of large integers
bpb
parents: 18538
diff changeset
  3849
        // Otherwise use recursive toString, which requires positive arguments.
0b6ca9785d8c 4641897: Faster string conversion of large integers
bpb
parents: 18538
diff changeset
  3850
        // The results will be concatenated into this StringBuilder
0b6ca9785d8c 4641897: Faster string conversion of large integers
bpb
parents: 18538
diff changeset
  3851
        StringBuilder sb = new StringBuilder();
0b6ca9785d8c 4641897: Faster string conversion of large integers
bpb
parents: 18538
diff changeset
  3852
        if (signum < 0) {
0b6ca9785d8c 4641897: Faster string conversion of large integers
bpb
parents: 18538
diff changeset
  3853
            toString(this.negate(), sb, radix, 0);
0b6ca9785d8c 4641897: Faster string conversion of large integers
bpb
parents: 18538
diff changeset
  3854
            sb.insert(0, '-');
0b6ca9785d8c 4641897: Faster string conversion of large integers
bpb
parents: 18538
diff changeset
  3855
        }
0b6ca9785d8c 4641897: Faster string conversion of large integers
bpb
parents: 18538
diff changeset
  3856
        else
0b6ca9785d8c 4641897: Faster string conversion of large integers
bpb
parents: 18538
diff changeset
  3857
            toString(this, sb, radix, 0);
0b6ca9785d8c 4641897: Faster string conversion of large integers
bpb
parents: 18538
diff changeset
  3858
0b6ca9785d8c 4641897: Faster string conversion of large integers
bpb
parents: 18538
diff changeset
  3859
        return sb.toString();
0b6ca9785d8c 4641897: Faster string conversion of large integers
bpb
parents: 18538
diff changeset
  3860
    }
0b6ca9785d8c 4641897: Faster string conversion of large integers
bpb
parents: 18538
diff changeset
  3861
0b6ca9785d8c 4641897: Faster string conversion of large integers
bpb
parents: 18538
diff changeset
  3862
    /** This method is used to perform toString when arguments are small. */
0b6ca9785d8c 4641897: Faster string conversion of large integers
bpb
parents: 18538
diff changeset
  3863
    private String smallToString(int radix) {
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  3864
        if (signum == 0) {
18548
0b6ca9785d8c 4641897: Faster string conversion of large integers
bpb
parents: 18538
diff changeset
  3865
            return "0";
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  3866
        }
18548
0b6ca9785d8c 4641897: Faster string conversion of large integers
bpb
parents: 18538
diff changeset
  3867
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3868
        // Compute upper bound on number of digit groups and allocate space
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3869
        int maxNumDigitGroups = (4*mag.length + 6)/7;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3870
        String digitGroup[] = new String[maxNumDigitGroups];
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3871
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3872
        // Translate number to string, a digit group at a time
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3873
        BigInteger tmp = this.abs();
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3874
        int numGroups = 0;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3875
        while (tmp.signum != 0) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3876
            BigInteger d = longRadix[radix];
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3877
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3878
            MutableBigInteger q = new MutableBigInteger(),
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3879
                              a = new MutableBigInteger(tmp.mag),
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3880
                              b = new MutableBigInteger(d.mag);
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  3881
            MutableBigInteger r = a.divide(b, q);
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  3882
            BigInteger q2 = q.toBigInteger(tmp.signum * d.signum);
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  3883
            BigInteger r2 = r.toBigInteger(tmp.signum * d.signum);
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3884
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3885
            digitGroup[numGroups++] = Long.toString(r2.longValue(), radix);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3886
            tmp = q2;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3887
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3888
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3889
        // Put sign (if any) and first digit group into result buffer
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3890
        StringBuilder buf = new StringBuilder(numGroups*digitsPerLong[radix]+1);
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  3891
        if (signum < 0) {
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3892
            buf.append('-');
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  3893
        }
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3894
        buf.append(digitGroup[numGroups-1]);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3895
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3896
        // Append remaining digit groups padded with leading zeros
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  3897
        for (int i=numGroups-2; i >= 0; i--) {
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3898
            // Prepend (any) leading zeros for this digit group
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3899
            int numLeadingZeros = digitsPerLong[radix]-digitGroup[i].length();
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  3900
            if (numLeadingZeros != 0) {
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3901
                buf.append(zeros[numLeadingZeros]);
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  3902
            }
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3903
            buf.append(digitGroup[i]);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3904
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3905
        return buf.toString();
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3906
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3907
18548
0b6ca9785d8c 4641897: Faster string conversion of large integers
bpb
parents: 18538
diff changeset
  3908
    /**
0b6ca9785d8c 4641897: Faster string conversion of large integers
bpb
parents: 18538
diff changeset
  3909
     * Converts the specified BigInteger to a string and appends to
19060
4d949a65ad7f 8014319: Faster division of large integers
bpb
parents: 18588
diff changeset
  3910
     * {@code sb}.  This implements the recursive Schoenhage algorithm
18548
0b6ca9785d8c 4641897: Faster string conversion of large integers
bpb
parents: 18538
diff changeset
  3911
     * for base conversions.
24367
705490680527 8030709: Tidy warnings cleanup for java.lang package; minor cleanup in java.math, javax.script
yan
parents: 23332
diff changeset
  3912
     * <p>
18548
0b6ca9785d8c 4641897: Faster string conversion of large integers
bpb
parents: 18538
diff changeset
  3913
     * See Knuth, Donald,  _The Art of Computer Programming_, Vol. 2,
0b6ca9785d8c 4641897: Faster string conversion of large integers
bpb
parents: 18538
diff changeset
  3914
     * Answers to Exercises (4.4) Question 14.
0b6ca9785d8c 4641897: Faster string conversion of large integers
bpb
parents: 18538
diff changeset
  3915
     *
0b6ca9785d8c 4641897: Faster string conversion of large integers
bpb
parents: 18538
diff changeset
  3916
     * @param u      The number to convert to a string.
0b6ca9785d8c 4641897: Faster string conversion of large integers
bpb
parents: 18538
diff changeset
  3917
     * @param sb     The StringBuilder that will be appended to in place.
0b6ca9785d8c 4641897: Faster string conversion of large integers
bpb
parents: 18538
diff changeset
  3918
     * @param radix  The base to convert to.
0b6ca9785d8c 4641897: Faster string conversion of large integers
bpb
parents: 18538
diff changeset
  3919
     * @param digits The minimum number of digits to pad to.
0b6ca9785d8c 4641897: Faster string conversion of large integers
bpb
parents: 18538
diff changeset
  3920
     */
0b6ca9785d8c 4641897: Faster string conversion of large integers
bpb
parents: 18538
diff changeset
  3921
    private static void toString(BigInteger u, StringBuilder sb, int radix,
0b6ca9785d8c 4641897: Faster string conversion of large integers
bpb
parents: 18538
diff changeset
  3922
                                 int digits) {
23332
c36c4773fe96 8035279: Clean up internal deprecations in BigInteger
bpb
parents: 22042
diff changeset
  3923
        // If we're smaller than a certain threshold, use the smallToString
c36c4773fe96 8035279: Clean up internal deprecations in BigInteger
bpb
parents: 22042
diff changeset
  3924
        // method, padding with leading zeroes when necessary.
18548
0b6ca9785d8c 4641897: Faster string conversion of large integers
bpb
parents: 18538
diff changeset
  3925
        if (u.mag.length <= SCHOENHAGE_BASE_CONVERSION_THRESHOLD) {
0b6ca9785d8c 4641897: Faster string conversion of large integers
bpb
parents: 18538
diff changeset
  3926
            String s = u.smallToString(radix);
0b6ca9785d8c 4641897: Faster string conversion of large integers
bpb
parents: 18538
diff changeset
  3927
0b6ca9785d8c 4641897: Faster string conversion of large integers
bpb
parents: 18538
diff changeset
  3928
            // Pad with internal zeros if necessary.
0b6ca9785d8c 4641897: Faster string conversion of large integers
bpb
parents: 18538
diff changeset
  3929
            // Don't pad if we're at the beginning of the string.
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  3930
            if ((s.length() < digits) && (sb.length() > 0)) {
23332
c36c4773fe96 8035279: Clean up internal deprecations in BigInteger
bpb
parents: 22042
diff changeset
  3931
                for (int i=s.length(); i < digits; i++) {
c36c4773fe96 8035279: Clean up internal deprecations in BigInteger
bpb
parents: 22042
diff changeset
  3932
                    sb.append('0');
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  3933
                }
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  3934
            }
18548
0b6ca9785d8c 4641897: Faster string conversion of large integers
bpb
parents: 18538
diff changeset
  3935
0b6ca9785d8c 4641897: Faster string conversion of large integers
bpb
parents: 18538
diff changeset
  3936
            sb.append(s);
0b6ca9785d8c 4641897: Faster string conversion of large integers
bpb
parents: 18538
diff changeset
  3937
            return;
0b6ca9785d8c 4641897: Faster string conversion of large integers
bpb
parents: 18538
diff changeset
  3938
        }
0b6ca9785d8c 4641897: Faster string conversion of large integers
bpb
parents: 18538
diff changeset
  3939
0b6ca9785d8c 4641897: Faster string conversion of large integers
bpb
parents: 18538
diff changeset
  3940
        int b, n;
0b6ca9785d8c 4641897: Faster string conversion of large integers
bpb
parents: 18538
diff changeset
  3941
        b = u.bitLength();
0b6ca9785d8c 4641897: Faster string conversion of large integers
bpb
parents: 18538
diff changeset
  3942
0b6ca9785d8c 4641897: Faster string conversion of large integers
bpb
parents: 18538
diff changeset
  3943
        // Calculate a value for n in the equation radix^(2^n) = u
0b6ca9785d8c 4641897: Faster string conversion of large integers
bpb
parents: 18538
diff changeset
  3944
        // and subtract 1 from that value.  This is used to find the
0b6ca9785d8c 4641897: Faster string conversion of large integers
bpb
parents: 18538
diff changeset
  3945
        // cache index that contains the best value to divide u.
0b6ca9785d8c 4641897: Faster string conversion of large integers
bpb
parents: 18538
diff changeset
  3946
        n = (int) Math.round(Math.log(b * LOG_TWO / logCache[radix]) / LOG_TWO - 1.0);
0b6ca9785d8c 4641897: Faster string conversion of large integers
bpb
parents: 18538
diff changeset
  3947
        BigInteger v = getRadixConversionCache(radix, n);
0b6ca9785d8c 4641897: Faster string conversion of large integers
bpb
parents: 18538
diff changeset
  3948
        BigInteger[] results;
0b6ca9785d8c 4641897: Faster string conversion of large integers
bpb
parents: 18538
diff changeset
  3949
        results = u.divideAndRemainder(v);
0b6ca9785d8c 4641897: Faster string conversion of large integers
bpb
parents: 18538
diff changeset
  3950
0b6ca9785d8c 4641897: Faster string conversion of large integers
bpb
parents: 18538
diff changeset
  3951
        int expectedDigits = 1 << n;
0b6ca9785d8c 4641897: Faster string conversion of large integers
bpb
parents: 18538
diff changeset
  3952
0b6ca9785d8c 4641897: Faster string conversion of large integers
bpb
parents: 18538
diff changeset
  3953
        // Now recursively build the two halves of each number.
0b6ca9785d8c 4641897: Faster string conversion of large integers
bpb
parents: 18538
diff changeset
  3954
        toString(results[0], sb, radix, digits-expectedDigits);
0b6ca9785d8c 4641897: Faster string conversion of large integers
bpb
parents: 18538
diff changeset
  3955
        toString(results[1], sb, radix, expectedDigits);
0b6ca9785d8c 4641897: Faster string conversion of large integers
bpb
parents: 18538
diff changeset
  3956
    }
0b6ca9785d8c 4641897: Faster string conversion of large integers
bpb
parents: 18538
diff changeset
  3957
0b6ca9785d8c 4641897: Faster string conversion of large integers
bpb
parents: 18538
diff changeset
  3958
    /**
0b6ca9785d8c 4641897: Faster string conversion of large integers
bpb
parents: 18538
diff changeset
  3959
     * Returns the value radix^(2^exponent) from the cache.
0b6ca9785d8c 4641897: Faster string conversion of large integers
bpb
parents: 18538
diff changeset
  3960
     * If this value doesn't already exist in the cache, it is added.
24367
705490680527 8030709: Tidy warnings cleanup for java.lang package; minor cleanup in java.math, javax.script
yan
parents: 23332
diff changeset
  3961
     * <p>
18548
0b6ca9785d8c 4641897: Faster string conversion of large integers
bpb
parents: 18538
diff changeset
  3962
     * This could be changed to a more complicated caching method using
19060
4d949a65ad7f 8014319: Faster division of large integers
bpb
parents: 18588
diff changeset
  3963
     * {@code Future}.
18548
0b6ca9785d8c 4641897: Faster string conversion of large integers
bpb
parents: 18538
diff changeset
  3964
     */
18588
8aa1d5a9d447 8017540: Improve multi-threaded contention behavior of radix conversion cache
bpb
parents: 18548
diff changeset
  3965
    private static BigInteger getRadixConversionCache(int radix, int exponent) {
8aa1d5a9d447 8017540: Improve multi-threaded contention behavior of radix conversion cache
bpb
parents: 18548
diff changeset
  3966
        BigInteger[] cacheLine = powerCache[radix]; // volatile read
8aa1d5a9d447 8017540: Improve multi-threaded contention behavior of radix conversion cache
bpb
parents: 18548
diff changeset
  3967
        if (exponent < cacheLine.length) {
8aa1d5a9d447 8017540: Improve multi-threaded contention behavior of radix conversion cache
bpb
parents: 18548
diff changeset
  3968
            return cacheLine[exponent];
18548
0b6ca9785d8c 4641897: Faster string conversion of large integers
bpb
parents: 18538
diff changeset
  3969
        }
18588
8aa1d5a9d447 8017540: Improve multi-threaded contention behavior of radix conversion cache
bpb
parents: 18548
diff changeset
  3970
8aa1d5a9d447 8017540: Improve multi-threaded contention behavior of radix conversion cache
bpb
parents: 18548
diff changeset
  3971
        int oldLength = cacheLine.length;
8aa1d5a9d447 8017540: Improve multi-threaded contention behavior of radix conversion cache
bpb
parents: 18548
diff changeset
  3972
        cacheLine = Arrays.copyOf(cacheLine, exponent + 1);
8aa1d5a9d447 8017540: Improve multi-threaded contention behavior of radix conversion cache
bpb
parents: 18548
diff changeset
  3973
        for (int i = oldLength; i <= exponent; i++) {
8aa1d5a9d447 8017540: Improve multi-threaded contention behavior of radix conversion cache
bpb
parents: 18548
diff changeset
  3974
            cacheLine[i] = cacheLine[i - 1].pow(2);
8aa1d5a9d447 8017540: Improve multi-threaded contention behavior of radix conversion cache
bpb
parents: 18548
diff changeset
  3975
        }
8aa1d5a9d447 8017540: Improve multi-threaded contention behavior of radix conversion cache
bpb
parents: 18548
diff changeset
  3976
8aa1d5a9d447 8017540: Improve multi-threaded contention behavior of radix conversion cache
bpb
parents: 18548
diff changeset
  3977
        BigInteger[][] pc = powerCache; // volatile read again
8aa1d5a9d447 8017540: Improve multi-threaded contention behavior of radix conversion cache
bpb
parents: 18548
diff changeset
  3978
        if (exponent >= pc[radix].length) {
8aa1d5a9d447 8017540: Improve multi-threaded contention behavior of radix conversion cache
bpb
parents: 18548
diff changeset
  3979
            pc = pc.clone();
8aa1d5a9d447 8017540: Improve multi-threaded contention behavior of radix conversion cache
bpb
parents: 18548
diff changeset
  3980
            pc[radix] = cacheLine;
8aa1d5a9d447 8017540: Improve multi-threaded contention behavior of radix conversion cache
bpb
parents: 18548
diff changeset
  3981
            powerCache = pc; // volatile write, publish
8aa1d5a9d447 8017540: Improve multi-threaded contention behavior of radix conversion cache
bpb
parents: 18548
diff changeset
  3982
        }
8aa1d5a9d447 8017540: Improve multi-threaded contention behavior of radix conversion cache
bpb
parents: 18548
diff changeset
  3983
        return cacheLine[exponent];
18548
0b6ca9785d8c 4641897: Faster string conversion of large integers
bpb
parents: 18538
diff changeset
  3984
    }
18286
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  3985
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3986
    /* zero[i] is a string of i consecutive zeros. */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3987
    private static String zeros[] = new String[64];
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3988
    static {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3989
        zeros[63] =
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3990
            "000000000000000000000000000000000000000000000000000000000000000";
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  3991
        for (int i=0; i < 63; i++)
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3992
            zeros[i] = zeros[63].substring(0, i);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3993
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3994
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3995
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3996
     * Returns the decimal String representation of this BigInteger.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3997
     * The digit-to-character mapping provided by
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3998
     * {@code Character.forDigit} is used, and a minus sign is
90ce3da70b43 Initial load
duke
parents:
diff changeset
  3999
     * prepended if appropriate.  (This representation is compatible
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4000
     * with the {@link #BigInteger(String) (String)} constructor, and
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4001
     * allows for String concatenation with Java's + operator.)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4002
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4003
     * @return decimal String representation of this BigInteger.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4004
     * @see    Character#forDigit
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4005
     * @see    #BigInteger(java.lang.String)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4006
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4007
    public String toString() {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4008
        return toString(10);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4009
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4010
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4011
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4012
     * Returns a byte array containing the two's-complement
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4013
     * representation of this BigInteger.  The byte array will be in
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4014
     * <i>big-endian</i> byte-order: the most significant byte is in
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4015
     * the zeroth element.  The array will contain the minimum number
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4016
     * of bytes required to represent this BigInteger, including at
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4017
     * least one sign bit, which is {@code (ceil((this.bitLength() +
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4018
     * 1)/8))}.  (This representation is compatible with the
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4019
     * {@link #BigInteger(byte[]) (byte[])} constructor.)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4020
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4021
     * @return a byte array containing the two's-complement representation of
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4022
     *         this BigInteger.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4023
     * @see    #BigInteger(byte[])
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4024
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4025
    public byte[] toByteArray() {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4026
        int byteLen = bitLength()/8 + 1;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4027
        byte[] byteArray = new byte[byteLen];
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4028
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  4029
        for (int i=byteLen-1, bytesCopied=4, nextInt=0, intIndex=0; i >= 0; i--) {
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4030
            if (bytesCopied == 4) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4031
                nextInt = getInt(intIndex++);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4032
                bytesCopied = 1;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4033
            } else {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4034
                nextInt >>>= 8;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4035
                bytesCopied++;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4036
            }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4037
            byteArray[i] = (byte)nextInt;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4038
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4039
        return byteArray;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4040
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4041
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4042
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4043
     * Converts this BigInteger to an {@code int}.  This
9266
121fb370f179 7032960: API files in java.awt need to be updated for references to JVM Spec with editions/hyperlinks
jjh
parents: 5506
diff changeset
  4044
     * conversion is analogous to a
121fb370f179 7032960: API files in java.awt need to be updated for references to JVM Spec with editions/hyperlinks
jjh
parents: 5506
diff changeset
  4045
     * <i>narrowing primitive conversion</i> from {@code long} to
38553
0553095041d7 8157724: Improve javadoc tag usage in java.math
darcy
parents: 37880
diff changeset
  4046
     * {@code int} as defined in
9266
121fb370f179 7032960: API files in java.awt need to be updated for references to JVM Spec with editions/hyperlinks
jjh
parents: 5506
diff changeset
  4047
     * <cite>The Java&trade; Language Specification</cite>:
121fb370f179 7032960: API files in java.awt need to be updated for references to JVM Spec with editions/hyperlinks
jjh
parents: 5506
diff changeset
  4048
     * if this BigInteger is too big to fit in an
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4049
     * {@code int}, only the low-order 32 bits are returned.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4050
     * Note that this conversion can lose information about the
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4051
     * overall magnitude of the BigInteger value as well as return a
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4052
     * result with the opposite sign.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4053
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4054
     * @return this BigInteger converted to an {@code int}.
10588
d8173a78bdca 6879143: java.math.BigInteger misses the xxxValueExact methods
darcy
parents: 10431
diff changeset
  4055
     * @see #intValueExact()
38553
0553095041d7 8157724: Improve javadoc tag usage in java.math
darcy
parents: 37880
diff changeset
  4056
     * @jls 5.1.3 Narrowing Primitive Conversion
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4057
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4058
    public int intValue() {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4059
        int result = 0;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4060
        result = getInt(0);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4061
        return result;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4062
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4063
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4064
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4065
     * Converts this BigInteger to a {@code long}.  This
9266
121fb370f179 7032960: API files in java.awt need to be updated for references to JVM Spec with editions/hyperlinks
jjh
parents: 5506
diff changeset
  4066
     * conversion is analogous to a
121fb370f179 7032960: API files in java.awt need to be updated for references to JVM Spec with editions/hyperlinks
jjh
parents: 5506
diff changeset
  4067
     * <i>narrowing primitive conversion</i> from {@code long} to
38553
0553095041d7 8157724: Improve javadoc tag usage in java.math
darcy
parents: 37880
diff changeset
  4068
     * {@code int} as defined in
9266
121fb370f179 7032960: API files in java.awt need to be updated for references to JVM Spec with editions/hyperlinks
jjh
parents: 5506
diff changeset
  4069
     * <cite>The Java&trade; Language Specification</cite>:
121fb370f179 7032960: API files in java.awt need to be updated for references to JVM Spec with editions/hyperlinks
jjh
parents: 5506
diff changeset
  4070
     * if this BigInteger is too big to fit in a
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4071
     * {@code long}, only the low-order 64 bits are returned.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4072
     * Note that this conversion can lose information about the
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4073
     * overall magnitude of the BigInteger value as well as return a
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4074
     * result with the opposite sign.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4075
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4076
     * @return this BigInteger converted to a {@code long}.
10588
d8173a78bdca 6879143: java.math.BigInteger misses the xxxValueExact methods
darcy
parents: 10431
diff changeset
  4077
     * @see #longValueExact()
38553
0553095041d7 8157724: Improve javadoc tag usage in java.math
darcy
parents: 37880
diff changeset
  4078
     * @jls 5.1.3 Narrowing Primitive Conversion
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4079
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4080
    public long longValue() {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4081
        long result = 0;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4082
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  4083
        for (int i=1; i >= 0; i--)
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4084
            result = (result << 32) + (getInt(i) & LONG_MASK);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4085
        return result;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4086
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4087
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4088
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4089
     * Converts this BigInteger to a {@code float}.  This
9266
121fb370f179 7032960: API files in java.awt need to be updated for references to JVM Spec with editions/hyperlinks
jjh
parents: 5506
diff changeset
  4090
     * conversion is similar to the
121fb370f179 7032960: API files in java.awt need to be updated for references to JVM Spec with editions/hyperlinks
jjh
parents: 5506
diff changeset
  4091
     * <i>narrowing primitive conversion</i> from {@code double} to
38553
0553095041d7 8157724: Improve javadoc tag usage in java.math
darcy
parents: 37880
diff changeset
  4092
     * {@code float} as defined in
9266
121fb370f179 7032960: API files in java.awt need to be updated for references to JVM Spec with editions/hyperlinks
jjh
parents: 5506
diff changeset
  4093
     * <cite>The Java&trade; Language Specification</cite>:
121fb370f179 7032960: API files in java.awt need to be updated for references to JVM Spec with editions/hyperlinks
jjh
parents: 5506
diff changeset
  4094
     * if this BigInteger has too great a magnitude
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4095
     * to represent as a {@code float}, it will be converted to
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4096
     * {@link Float#NEGATIVE_INFINITY} or {@link
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4097
     * Float#POSITIVE_INFINITY} as appropriate.  Note that even when
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4098
     * the return value is finite, this conversion can lose
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4099
     * information about the precision of the BigInteger value.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4100
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4101
     * @return this BigInteger converted to a {@code float}.
38553
0553095041d7 8157724: Improve javadoc tag usage in java.math
darcy
parents: 37880
diff changeset
  4102
     * @jls 5.1.3 Narrowing Primitive Conversion
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4103
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4104
    public float floatValue() {
18538
642cc17315fd 7131192: BigInteger.doubleValue() is depressingly slow
bpb
parents: 18286
diff changeset
  4105
        if (signum == 0) {
642cc17315fd 7131192: BigInteger.doubleValue() is depressingly slow
bpb
parents: 18286
diff changeset
  4106
            return 0.0f;
642cc17315fd 7131192: BigInteger.doubleValue() is depressingly slow
bpb
parents: 18286
diff changeset
  4107
        }
642cc17315fd 7131192: BigInteger.doubleValue() is depressingly slow
bpb
parents: 18286
diff changeset
  4108
642cc17315fd 7131192: BigInteger.doubleValue() is depressingly slow
bpb
parents: 18286
diff changeset
  4109
        int exponent = ((mag.length - 1) << 5) + bitLengthForInt(mag[0]) - 1;
642cc17315fd 7131192: BigInteger.doubleValue() is depressingly slow
bpb
parents: 18286
diff changeset
  4110
642cc17315fd 7131192: BigInteger.doubleValue() is depressingly slow
bpb
parents: 18286
diff changeset
  4111
        // exponent == floor(log2(abs(this)))
642cc17315fd 7131192: BigInteger.doubleValue() is depressingly slow
bpb
parents: 18286
diff changeset
  4112
        if (exponent < Long.SIZE - 1) {
642cc17315fd 7131192: BigInteger.doubleValue() is depressingly slow
bpb
parents: 18286
diff changeset
  4113
            return longValue();
642cc17315fd 7131192: BigInteger.doubleValue() is depressingly slow
bpb
parents: 18286
diff changeset
  4114
        } else if (exponent > Float.MAX_EXPONENT) {
642cc17315fd 7131192: BigInteger.doubleValue() is depressingly slow
bpb
parents: 18286
diff changeset
  4115
            return signum > 0 ? Float.POSITIVE_INFINITY : Float.NEGATIVE_INFINITY;
642cc17315fd 7131192: BigInteger.doubleValue() is depressingly slow
bpb
parents: 18286
diff changeset
  4116
        }
642cc17315fd 7131192: BigInteger.doubleValue() is depressingly slow
bpb
parents: 18286
diff changeset
  4117
642cc17315fd 7131192: BigInteger.doubleValue() is depressingly slow
bpb
parents: 18286
diff changeset
  4118
        /*
642cc17315fd 7131192: BigInteger.doubleValue() is depressingly slow
bpb
parents: 18286
diff changeset
  4119
         * We need the top SIGNIFICAND_WIDTH bits, including the "implicit"
642cc17315fd 7131192: BigInteger.doubleValue() is depressingly slow
bpb
parents: 18286
diff changeset
  4120
         * one bit. To make rounding easier, we pick out the top
642cc17315fd 7131192: BigInteger.doubleValue() is depressingly slow
bpb
parents: 18286
diff changeset
  4121
         * SIGNIFICAND_WIDTH + 1 bits, so we have one to help us round up or
642cc17315fd 7131192: BigInteger.doubleValue() is depressingly slow
bpb
parents: 18286
diff changeset
  4122
         * down. twiceSignifFloor will contain the top SIGNIFICAND_WIDTH + 1
642cc17315fd 7131192: BigInteger.doubleValue() is depressingly slow
bpb
parents: 18286
diff changeset
  4123
         * bits, and signifFloor the top SIGNIFICAND_WIDTH.
642cc17315fd 7131192: BigInteger.doubleValue() is depressingly slow
bpb
parents: 18286
diff changeset
  4124
         *
642cc17315fd 7131192: BigInteger.doubleValue() is depressingly slow
bpb
parents: 18286
diff changeset
  4125
         * It helps to consider the real number signif = abs(this) *
642cc17315fd 7131192: BigInteger.doubleValue() is depressingly slow
bpb
parents: 18286
diff changeset
  4126
         * 2^(SIGNIFICAND_WIDTH - 1 - exponent).
642cc17315fd 7131192: BigInteger.doubleValue() is depressingly slow
bpb
parents: 18286
diff changeset
  4127
         */
642cc17315fd 7131192: BigInteger.doubleValue() is depressingly slow
bpb
parents: 18286
diff changeset
  4128
        int shift = exponent - FloatConsts.SIGNIFICAND_WIDTH;
642cc17315fd 7131192: BigInteger.doubleValue() is depressingly slow
bpb
parents: 18286
diff changeset
  4129
642cc17315fd 7131192: BigInteger.doubleValue() is depressingly slow
bpb
parents: 18286
diff changeset
  4130
        int twiceSignifFloor;
642cc17315fd 7131192: BigInteger.doubleValue() is depressingly slow
bpb
parents: 18286
diff changeset
  4131
        // twiceSignifFloor will be == abs().shiftRight(shift).intValue()
642cc17315fd 7131192: BigInteger.doubleValue() is depressingly slow
bpb
parents: 18286
diff changeset
  4132
        // We do the shift into an int directly to improve performance.
642cc17315fd 7131192: BigInteger.doubleValue() is depressingly slow
bpb
parents: 18286
diff changeset
  4133
642cc17315fd 7131192: BigInteger.doubleValue() is depressingly slow
bpb
parents: 18286
diff changeset
  4134
        int nBits = shift & 0x1f;
642cc17315fd 7131192: BigInteger.doubleValue() is depressingly slow
bpb
parents: 18286
diff changeset
  4135
        int nBits2 = 32 - nBits;
642cc17315fd 7131192: BigInteger.doubleValue() is depressingly slow
bpb
parents: 18286
diff changeset
  4136
642cc17315fd 7131192: BigInteger.doubleValue() is depressingly slow
bpb
parents: 18286
diff changeset
  4137
        if (nBits == 0) {
642cc17315fd 7131192: BigInteger.doubleValue() is depressingly slow
bpb
parents: 18286
diff changeset
  4138
            twiceSignifFloor = mag[0];
642cc17315fd 7131192: BigInteger.doubleValue() is depressingly slow
bpb
parents: 18286
diff changeset
  4139
        } else {
642cc17315fd 7131192: BigInteger.doubleValue() is depressingly slow
bpb
parents: 18286
diff changeset
  4140
            twiceSignifFloor = mag[0] >>> nBits;
642cc17315fd 7131192: BigInteger.doubleValue() is depressingly slow
bpb
parents: 18286
diff changeset
  4141
            if (twiceSignifFloor == 0) {
642cc17315fd 7131192: BigInteger.doubleValue() is depressingly slow
bpb
parents: 18286
diff changeset
  4142
                twiceSignifFloor = (mag[0] << nBits2) | (mag[1] >>> nBits);
642cc17315fd 7131192: BigInteger.doubleValue() is depressingly slow
bpb
parents: 18286
diff changeset
  4143
            }
642cc17315fd 7131192: BigInteger.doubleValue() is depressingly slow
bpb
parents: 18286
diff changeset
  4144
        }
642cc17315fd 7131192: BigInteger.doubleValue() is depressingly slow
bpb
parents: 18286
diff changeset
  4145
642cc17315fd 7131192: BigInteger.doubleValue() is depressingly slow
bpb
parents: 18286
diff changeset
  4146
        int signifFloor = twiceSignifFloor >> 1;
642cc17315fd 7131192: BigInteger.doubleValue() is depressingly slow
bpb
parents: 18286
diff changeset
  4147
        signifFloor &= FloatConsts.SIGNIF_BIT_MASK; // remove the implied bit
642cc17315fd 7131192: BigInteger.doubleValue() is depressingly slow
bpb
parents: 18286
diff changeset
  4148
642cc17315fd 7131192: BigInteger.doubleValue() is depressingly slow
bpb
parents: 18286
diff changeset
  4149
        /*
642cc17315fd 7131192: BigInteger.doubleValue() is depressingly slow
bpb
parents: 18286
diff changeset
  4150
         * We round up if either the fractional part of signif is strictly
642cc17315fd 7131192: BigInteger.doubleValue() is depressingly slow
bpb
parents: 18286
diff changeset
  4151
         * greater than 0.5 (which is true if the 0.5 bit is set and any lower
642cc17315fd 7131192: BigInteger.doubleValue() is depressingly slow
bpb
parents: 18286
diff changeset
  4152
         * bit is set), or if the fractional part of signif is >= 0.5 and
642cc17315fd 7131192: BigInteger.doubleValue() is depressingly slow
bpb
parents: 18286
diff changeset
  4153
         * signifFloor is odd (which is true if both the 0.5 bit and the 1 bit
642cc17315fd 7131192: BigInteger.doubleValue() is depressingly slow
bpb
parents: 18286
diff changeset
  4154
         * are set). This is equivalent to the desired HALF_EVEN rounding.
642cc17315fd 7131192: BigInteger.doubleValue() is depressingly slow
bpb
parents: 18286
diff changeset
  4155
         */
642cc17315fd 7131192: BigInteger.doubleValue() is depressingly slow
bpb
parents: 18286
diff changeset
  4156
        boolean increment = (twiceSignifFloor & 1) != 0
642cc17315fd 7131192: BigInteger.doubleValue() is depressingly slow
bpb
parents: 18286
diff changeset
  4157
                && ((signifFloor & 1) != 0 || abs().getLowestSetBit() < shift);
642cc17315fd 7131192: BigInteger.doubleValue() is depressingly slow
bpb
parents: 18286
diff changeset
  4158
        int signifRounded = increment ? signifFloor + 1 : signifFloor;
642cc17315fd 7131192: BigInteger.doubleValue() is depressingly slow
bpb
parents: 18286
diff changeset
  4159
        int bits = ((exponent + FloatConsts.EXP_BIAS))
642cc17315fd 7131192: BigInteger.doubleValue() is depressingly slow
bpb
parents: 18286
diff changeset
  4160
                << (FloatConsts.SIGNIFICAND_WIDTH - 1);
642cc17315fd 7131192: BigInteger.doubleValue() is depressingly slow
bpb
parents: 18286
diff changeset
  4161
        bits += signifRounded;
642cc17315fd 7131192: BigInteger.doubleValue() is depressingly slow
bpb
parents: 18286
diff changeset
  4162
        /*
642cc17315fd 7131192: BigInteger.doubleValue() is depressingly slow
bpb
parents: 18286
diff changeset
  4163
         * If signifRounded == 2^24, we'd need to set all of the significand
642cc17315fd 7131192: BigInteger.doubleValue() is depressingly slow
bpb
parents: 18286
diff changeset
  4164
         * bits to zero and add 1 to the exponent. This is exactly the behavior
642cc17315fd 7131192: BigInteger.doubleValue() is depressingly slow
bpb
parents: 18286
diff changeset
  4165
         * we get from just adding signifRounded to bits directly. If the
642cc17315fd 7131192: BigInteger.doubleValue() is depressingly slow
bpb
parents: 18286
diff changeset
  4166
         * exponent is Float.MAX_EXPONENT, we round up (correctly) to
642cc17315fd 7131192: BigInteger.doubleValue() is depressingly slow
bpb
parents: 18286
diff changeset
  4167
         * Float.POSITIVE_INFINITY.
642cc17315fd 7131192: BigInteger.doubleValue() is depressingly slow
bpb
parents: 18286
diff changeset
  4168
         */
642cc17315fd 7131192: BigInteger.doubleValue() is depressingly slow
bpb
parents: 18286
diff changeset
  4169
        bits |= signum & FloatConsts.SIGN_BIT_MASK;
642cc17315fd 7131192: BigInteger.doubleValue() is depressingly slow
bpb
parents: 18286
diff changeset
  4170
        return Float.intBitsToFloat(bits);
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4171
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4172
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4173
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4174
     * Converts this BigInteger to a {@code double}.  This
9266
121fb370f179 7032960: API files in java.awt need to be updated for references to JVM Spec with editions/hyperlinks
jjh
parents: 5506
diff changeset
  4175
     * conversion is similar to the
121fb370f179 7032960: API files in java.awt need to be updated for references to JVM Spec with editions/hyperlinks
jjh
parents: 5506
diff changeset
  4176
     * <i>narrowing primitive conversion</i> from {@code double} to
38553
0553095041d7 8157724: Improve javadoc tag usage in java.math
darcy
parents: 37880
diff changeset
  4177
     * {@code float} as defined in
9266
121fb370f179 7032960: API files in java.awt need to be updated for references to JVM Spec with editions/hyperlinks
jjh
parents: 5506
diff changeset
  4178
     * <cite>The Java&trade; Language Specification</cite>:
121fb370f179 7032960: API files in java.awt need to be updated for references to JVM Spec with editions/hyperlinks
jjh
parents: 5506
diff changeset
  4179
     * if this BigInteger has too great a magnitude
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4180
     * to represent as a {@code double}, it will be converted to
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4181
     * {@link Double#NEGATIVE_INFINITY} or {@link
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4182
     * Double#POSITIVE_INFINITY} as appropriate.  Note that even when
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4183
     * the return value is finite, this conversion can lose
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4184
     * information about the precision of the BigInteger value.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4185
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4186
     * @return this BigInteger converted to a {@code double}.
38553
0553095041d7 8157724: Improve javadoc tag usage in java.math
darcy
parents: 37880
diff changeset
  4187
     * @jls 5.1.3 Narrowing Primitive Conversion
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4188
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4189
    public double doubleValue() {
18538
642cc17315fd 7131192: BigInteger.doubleValue() is depressingly slow
bpb
parents: 18286
diff changeset
  4190
        if (signum == 0) {
642cc17315fd 7131192: BigInteger.doubleValue() is depressingly slow
bpb
parents: 18286
diff changeset
  4191
            return 0.0;
642cc17315fd 7131192: BigInteger.doubleValue() is depressingly slow
bpb
parents: 18286
diff changeset
  4192
        }
642cc17315fd 7131192: BigInteger.doubleValue() is depressingly slow
bpb
parents: 18286
diff changeset
  4193
642cc17315fd 7131192: BigInteger.doubleValue() is depressingly slow
bpb
parents: 18286
diff changeset
  4194
        int exponent = ((mag.length - 1) << 5) + bitLengthForInt(mag[0]) - 1;
642cc17315fd 7131192: BigInteger.doubleValue() is depressingly slow
bpb
parents: 18286
diff changeset
  4195
642cc17315fd 7131192: BigInteger.doubleValue() is depressingly slow
bpb
parents: 18286
diff changeset
  4196
        // exponent == floor(log2(abs(this))Double)
642cc17315fd 7131192: BigInteger.doubleValue() is depressingly slow
bpb
parents: 18286
diff changeset
  4197
        if (exponent < Long.SIZE - 1) {
642cc17315fd 7131192: BigInteger.doubleValue() is depressingly slow
bpb
parents: 18286
diff changeset
  4198
            return longValue();
642cc17315fd 7131192: BigInteger.doubleValue() is depressingly slow
bpb
parents: 18286
diff changeset
  4199
        } else if (exponent > Double.MAX_EXPONENT) {
642cc17315fd 7131192: BigInteger.doubleValue() is depressingly slow
bpb
parents: 18286
diff changeset
  4200
            return signum > 0 ? Double.POSITIVE_INFINITY : Double.NEGATIVE_INFINITY;
642cc17315fd 7131192: BigInteger.doubleValue() is depressingly slow
bpb
parents: 18286
diff changeset
  4201
        }
642cc17315fd 7131192: BigInteger.doubleValue() is depressingly slow
bpb
parents: 18286
diff changeset
  4202
642cc17315fd 7131192: BigInteger.doubleValue() is depressingly slow
bpb
parents: 18286
diff changeset
  4203
        /*
642cc17315fd 7131192: BigInteger.doubleValue() is depressingly slow
bpb
parents: 18286
diff changeset
  4204
         * We need the top SIGNIFICAND_WIDTH bits, including the "implicit"
642cc17315fd 7131192: BigInteger.doubleValue() is depressingly slow
bpb
parents: 18286
diff changeset
  4205
         * one bit. To make rounding easier, we pick out the top
642cc17315fd 7131192: BigInteger.doubleValue() is depressingly slow
bpb
parents: 18286
diff changeset
  4206
         * SIGNIFICAND_WIDTH + 1 bits, so we have one to help us round up or
642cc17315fd 7131192: BigInteger.doubleValue() is depressingly slow
bpb
parents: 18286
diff changeset
  4207
         * down. twiceSignifFloor will contain the top SIGNIFICAND_WIDTH + 1
642cc17315fd 7131192: BigInteger.doubleValue() is depressingly slow
bpb
parents: 18286
diff changeset
  4208
         * bits, and signifFloor the top SIGNIFICAND_WIDTH.
642cc17315fd 7131192: BigInteger.doubleValue() is depressingly slow
bpb
parents: 18286
diff changeset
  4209
         *
642cc17315fd 7131192: BigInteger.doubleValue() is depressingly slow
bpb
parents: 18286
diff changeset
  4210
         * It helps to consider the real number signif = abs(this) *
642cc17315fd 7131192: BigInteger.doubleValue() is depressingly slow
bpb
parents: 18286
diff changeset
  4211
         * 2^(SIGNIFICAND_WIDTH - 1 - exponent).
642cc17315fd 7131192: BigInteger.doubleValue() is depressingly slow
bpb
parents: 18286
diff changeset
  4212
         */
642cc17315fd 7131192: BigInteger.doubleValue() is depressingly slow
bpb
parents: 18286
diff changeset
  4213
        int shift = exponent - DoubleConsts.SIGNIFICAND_WIDTH;
642cc17315fd 7131192: BigInteger.doubleValue() is depressingly slow
bpb
parents: 18286
diff changeset
  4214
642cc17315fd 7131192: BigInteger.doubleValue() is depressingly slow
bpb
parents: 18286
diff changeset
  4215
        long twiceSignifFloor;
642cc17315fd 7131192: BigInteger.doubleValue() is depressingly slow
bpb
parents: 18286
diff changeset
  4216
        // twiceSignifFloor will be == abs().shiftRight(shift).longValue()
642cc17315fd 7131192: BigInteger.doubleValue() is depressingly slow
bpb
parents: 18286
diff changeset
  4217
        // We do the shift into a long directly to improve performance.
642cc17315fd 7131192: BigInteger.doubleValue() is depressingly slow
bpb
parents: 18286
diff changeset
  4218
642cc17315fd 7131192: BigInteger.doubleValue() is depressingly slow
bpb
parents: 18286
diff changeset
  4219
        int nBits = shift & 0x1f;
642cc17315fd 7131192: BigInteger.doubleValue() is depressingly slow
bpb
parents: 18286
diff changeset
  4220
        int nBits2 = 32 - nBits;
642cc17315fd 7131192: BigInteger.doubleValue() is depressingly slow
bpb
parents: 18286
diff changeset
  4221
642cc17315fd 7131192: BigInteger.doubleValue() is depressingly slow
bpb
parents: 18286
diff changeset
  4222
        int highBits;
642cc17315fd 7131192: BigInteger.doubleValue() is depressingly slow
bpb
parents: 18286
diff changeset
  4223
        int lowBits;
642cc17315fd 7131192: BigInteger.doubleValue() is depressingly slow
bpb
parents: 18286
diff changeset
  4224
        if (nBits == 0) {
642cc17315fd 7131192: BigInteger.doubleValue() is depressingly slow
bpb
parents: 18286
diff changeset
  4225
            highBits = mag[0];
642cc17315fd 7131192: BigInteger.doubleValue() is depressingly slow
bpb
parents: 18286
diff changeset
  4226
            lowBits = mag[1];
642cc17315fd 7131192: BigInteger.doubleValue() is depressingly slow
bpb
parents: 18286
diff changeset
  4227
        } else {
642cc17315fd 7131192: BigInteger.doubleValue() is depressingly slow
bpb
parents: 18286
diff changeset
  4228
            highBits = mag[0] >>> nBits;
642cc17315fd 7131192: BigInteger.doubleValue() is depressingly slow
bpb
parents: 18286
diff changeset
  4229
            lowBits = (mag[0] << nBits2) | (mag[1] >>> nBits);
642cc17315fd 7131192: BigInteger.doubleValue() is depressingly slow
bpb
parents: 18286
diff changeset
  4230
            if (highBits == 0) {
642cc17315fd 7131192: BigInteger.doubleValue() is depressingly slow
bpb
parents: 18286
diff changeset
  4231
                highBits = lowBits;
642cc17315fd 7131192: BigInteger.doubleValue() is depressingly slow
bpb
parents: 18286
diff changeset
  4232
                lowBits = (mag[1] << nBits2) | (mag[2] >>> nBits);
642cc17315fd 7131192: BigInteger.doubleValue() is depressingly slow
bpb
parents: 18286
diff changeset
  4233
            }
642cc17315fd 7131192: BigInteger.doubleValue() is depressingly slow
bpb
parents: 18286
diff changeset
  4234
        }
642cc17315fd 7131192: BigInteger.doubleValue() is depressingly slow
bpb
parents: 18286
diff changeset
  4235
642cc17315fd 7131192: BigInteger.doubleValue() is depressingly slow
bpb
parents: 18286
diff changeset
  4236
        twiceSignifFloor = ((highBits & LONG_MASK) << 32)
642cc17315fd 7131192: BigInteger.doubleValue() is depressingly slow
bpb
parents: 18286
diff changeset
  4237
                | (lowBits & LONG_MASK);
642cc17315fd 7131192: BigInteger.doubleValue() is depressingly slow
bpb
parents: 18286
diff changeset
  4238
642cc17315fd 7131192: BigInteger.doubleValue() is depressingly slow
bpb
parents: 18286
diff changeset
  4239
        long signifFloor = twiceSignifFloor >> 1;
642cc17315fd 7131192: BigInteger.doubleValue() is depressingly slow
bpb
parents: 18286
diff changeset
  4240
        signifFloor &= DoubleConsts.SIGNIF_BIT_MASK; // remove the implied bit
642cc17315fd 7131192: BigInteger.doubleValue() is depressingly slow
bpb
parents: 18286
diff changeset
  4241
642cc17315fd 7131192: BigInteger.doubleValue() is depressingly slow
bpb
parents: 18286
diff changeset
  4242
        /*
642cc17315fd 7131192: BigInteger.doubleValue() is depressingly slow
bpb
parents: 18286
diff changeset
  4243
         * We round up if either the fractional part of signif is strictly
642cc17315fd 7131192: BigInteger.doubleValue() is depressingly slow
bpb
parents: 18286
diff changeset
  4244
         * greater than 0.5 (which is true if the 0.5 bit is set and any lower
642cc17315fd 7131192: BigInteger.doubleValue() is depressingly slow
bpb
parents: 18286
diff changeset
  4245
         * bit is set), or if the fractional part of signif is >= 0.5 and
642cc17315fd 7131192: BigInteger.doubleValue() is depressingly slow
bpb
parents: 18286
diff changeset
  4246
         * signifFloor is odd (which is true if both the 0.5 bit and the 1 bit
642cc17315fd 7131192: BigInteger.doubleValue() is depressingly slow
bpb
parents: 18286
diff changeset
  4247
         * are set). This is equivalent to the desired HALF_EVEN rounding.
642cc17315fd 7131192: BigInteger.doubleValue() is depressingly slow
bpb
parents: 18286
diff changeset
  4248
         */
642cc17315fd 7131192: BigInteger.doubleValue() is depressingly slow
bpb
parents: 18286
diff changeset
  4249
        boolean increment = (twiceSignifFloor & 1) != 0
642cc17315fd 7131192: BigInteger.doubleValue() is depressingly slow
bpb
parents: 18286
diff changeset
  4250
                && ((signifFloor & 1) != 0 || abs().getLowestSetBit() < shift);
642cc17315fd 7131192: BigInteger.doubleValue() is depressingly slow
bpb
parents: 18286
diff changeset
  4251
        long signifRounded = increment ? signifFloor + 1 : signifFloor;
642cc17315fd 7131192: BigInteger.doubleValue() is depressingly slow
bpb
parents: 18286
diff changeset
  4252
        long bits = (long) ((exponent + DoubleConsts.EXP_BIAS))
642cc17315fd 7131192: BigInteger.doubleValue() is depressingly slow
bpb
parents: 18286
diff changeset
  4253
                << (DoubleConsts.SIGNIFICAND_WIDTH - 1);
642cc17315fd 7131192: BigInteger.doubleValue() is depressingly slow
bpb
parents: 18286
diff changeset
  4254
        bits += signifRounded;
642cc17315fd 7131192: BigInteger.doubleValue() is depressingly slow
bpb
parents: 18286
diff changeset
  4255
        /*
642cc17315fd 7131192: BigInteger.doubleValue() is depressingly slow
bpb
parents: 18286
diff changeset
  4256
         * If signifRounded == 2^53, we'd need to set all of the significand
642cc17315fd 7131192: BigInteger.doubleValue() is depressingly slow
bpb
parents: 18286
diff changeset
  4257
         * bits to zero and add 1 to the exponent. This is exactly the behavior
642cc17315fd 7131192: BigInteger.doubleValue() is depressingly slow
bpb
parents: 18286
diff changeset
  4258
         * we get from just adding signifRounded to bits directly. If the
642cc17315fd 7131192: BigInteger.doubleValue() is depressingly slow
bpb
parents: 18286
diff changeset
  4259
         * exponent is Double.MAX_EXPONENT, we round up (correctly) to
642cc17315fd 7131192: BigInteger.doubleValue() is depressingly slow
bpb
parents: 18286
diff changeset
  4260
         * Double.POSITIVE_INFINITY.
642cc17315fd 7131192: BigInteger.doubleValue() is depressingly slow
bpb
parents: 18286
diff changeset
  4261
         */
642cc17315fd 7131192: BigInteger.doubleValue() is depressingly slow
bpb
parents: 18286
diff changeset
  4262
        bits |= signum & DoubleConsts.SIGN_BIT_MASK;
642cc17315fd 7131192: BigInteger.doubleValue() is depressingly slow
bpb
parents: 18286
diff changeset
  4263
        return Double.longBitsToDouble(bits);
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4264
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4265
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4266
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4267
     * Returns a copy of the input array stripped of any leading zero bytes.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4268
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4269
    private static int[] stripLeadingZeroInts(int val[]) {
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  4270
        int vlen = val.length;
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4271
        int keep;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4272
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4273
        // Find first nonzero byte
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  4274
        for (keep = 0; keep < vlen && val[keep] == 0; keep++)
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4275
            ;
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  4276
        return java.util.Arrays.copyOfRange(val, keep, vlen);
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4277
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4278
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4279
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4280
     * Returns the input array stripped of any leading zero bytes.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4281
     * Since the source is trusted the copying may be skipped.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4282
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4283
    private static int[] trustedStripLeadingZeroInts(int val[]) {
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  4284
        int vlen = val.length;
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4285
        int keep;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4286
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4287
        // Find first nonzero byte
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  4288
        for (keep = 0; keep < vlen && val[keep] == 0; keep++)
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4289
            ;
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  4290
        return keep == 0 ? val : java.util.Arrays.copyOfRange(val, keep, vlen);
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4291
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4292
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4293
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4294
     * Returns a copy of the input array stripped of any leading zero bytes.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4295
     */
28309
45f25a2cf942 4026465: Provide more byte array constructors for BigInteger
bpb
parents: 25859
diff changeset
  4296
    private static int[] stripLeadingZeroBytes(byte a[], int off, int len) {
45f25a2cf942 4026465: Provide more byte array constructors for BigInteger
bpb
parents: 25859
diff changeset
  4297
        int indexBound = off + len;
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4298
        int keep;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4299
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4300
        // Find first nonzero byte
28309
45f25a2cf942 4026465: Provide more byte array constructors for BigInteger
bpb
parents: 25859
diff changeset
  4301
        for (keep = off; keep < indexBound && a[keep] == 0; keep++)
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4302
            ;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4303
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4304
        // Allocate new array and copy relevant part of input array
28309
45f25a2cf942 4026465: Provide more byte array constructors for BigInteger
bpb
parents: 25859
diff changeset
  4305
        int intLength = ((indexBound - keep) + 3) >>> 2;
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4306
        int[] result = new int[intLength];
28309
45f25a2cf942 4026465: Provide more byte array constructors for BigInteger
bpb
parents: 25859
diff changeset
  4307
        int b = indexBound - 1;
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4308
        for (int i = intLength-1; i >= 0; i--) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4309
            result[i] = a[b--] & 0xff;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4310
            int bytesRemaining = b - keep + 1;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4311
            int bytesToTransfer = Math.min(3, bytesRemaining);
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  4312
            for (int j=8; j <= (bytesToTransfer << 3); j += 8)
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4313
                result[i] |= ((a[b--] & 0xff) << j);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4314
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4315
        return result;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4316
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4317
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4318
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4319
     * Takes an array a representing a negative 2's-complement number and
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4320
     * returns the minimal (no leading zero bytes) unsigned whose value is -a.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4321
     */
28309
45f25a2cf942 4026465: Provide more byte array constructors for BigInteger
bpb
parents: 25859
diff changeset
  4322
    private static int[] makePositive(byte a[], int off, int len) {
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4323
        int keep, k;
28309
45f25a2cf942 4026465: Provide more byte array constructors for BigInteger
bpb
parents: 25859
diff changeset
  4324
        int indexBound = off + len;
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4325
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4326
        // Find first non-sign (0xff) byte of input
28309
45f25a2cf942 4026465: Provide more byte array constructors for BigInteger
bpb
parents: 25859
diff changeset
  4327
        for (keep=off; keep < indexBound && a[keep] == -1; keep++)
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4328
            ;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4329
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4330
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4331
        /* Allocate output array.  If all non-sign bytes are 0x00, we must
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4332
         * allocate space for one extra output byte. */
28309
45f25a2cf942 4026465: Provide more byte array constructors for BigInteger
bpb
parents: 25859
diff changeset
  4333
        for (k=keep; k < indexBound && a[k] == 0; k++)
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4334
            ;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4335
28309
45f25a2cf942 4026465: Provide more byte array constructors for BigInteger
bpb
parents: 25859
diff changeset
  4336
        int extraByte = (k == indexBound) ? 1 : 0;
45f25a2cf942 4026465: Provide more byte array constructors for BigInteger
bpb
parents: 25859
diff changeset
  4337
        int intLength = ((indexBound - keep + extraByte) + 3) >>> 2;
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4338
        int result[] = new int[intLength];
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4339
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4340
        /* Copy one's complement of input into output, leaving extra
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4341
         * byte (if it exists) == 0x00 */
28309
45f25a2cf942 4026465: Provide more byte array constructors for BigInteger
bpb
parents: 25859
diff changeset
  4342
        int b = indexBound - 1;
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4343
        for (int i = intLength-1; i >= 0; i--) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4344
            result[i] = a[b--] & 0xff;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4345
            int numBytesToTransfer = Math.min(3, b-keep+1);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4346
            if (numBytesToTransfer < 0)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4347
                numBytesToTransfer = 0;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4348
            for (int j=8; j <= 8*numBytesToTransfer; j += 8)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4349
                result[i] |= ((a[b--] & 0xff) << j);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4350
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4351
            // Mask indicates which bits must be complemented
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4352
            int mask = -1 >>> (8*(3-numBytesToTransfer));
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4353
            result[i] = ~result[i] & mask;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4354
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4355
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4356
        // Add one to one's complement to generate two's complement
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  4357
        for (int i=result.length-1; i >= 0; i--) {
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4358
            result[i] = (int)((result[i] & LONG_MASK) + 1);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4359
            if (result[i] != 0)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4360
                break;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4361
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4362
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4363
        return result;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4364
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4365
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4366
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4367
     * Takes an array a representing a negative 2's-complement number and
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4368
     * returns the minimal (no leading zero ints) unsigned whose value is -a.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4369
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4370
    private static int[] makePositive(int a[]) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4371
        int keep, j;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4372
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4373
        // Find first non-sign (0xffffffff) int of input
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  4374
        for (keep=0; keep < a.length && a[keep] == -1; keep++)
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4375
            ;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4376
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4377
        /* Allocate output array.  If all non-sign ints are 0x00, we must
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4378
         * allocate space for one extra output int. */
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  4379
        for (j=keep; j < a.length && a[j] == 0; j++)
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4380
            ;
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  4381
        int extraInt = (j == a.length ? 1 : 0);
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4382
        int result[] = new int[a.length - keep + extraInt];
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4383
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4384
        /* Copy one's complement of input into output, leaving extra
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4385
         * int (if it exists) == 0x00 */
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  4386
        for (int i = keep; i < a.length; i++)
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4387
            result[i - keep + extraInt] = ~a[i];
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4388
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4389
        // Add one to one's complement to generate two's complement
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  4390
        for (int i=result.length-1; ++result[i] == 0; i--)
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4391
            ;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4392
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4393
        return result;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4394
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4395
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4396
    /*
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4397
     * The following two arrays are used for fast String conversions.  Both
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4398
     * are indexed by radix.  The first is the number of digits of the given
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4399
     * radix that can fit in a Java long without "going negative", i.e., the
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4400
     * highest integer n such that radix**n < 2**63.  The second is the
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4401
     * "long radix" that tears each number into "long digits", each of which
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4402
     * consists of the number of digits in the corresponding element in
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4403
     * digitsPerLong (longRadix[i] = i**digitPerLong[i]).  Both arrays have
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4404
     * nonsense values in their 0 and 1 elements, as radixes 0 and 1 are not
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4405
     * used.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4406
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4407
    private static int digitsPerLong[] = {0, 0,
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4408
        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
  4409
        14, 14, 14, 13, 13, 13, 13, 13, 13, 12, 12, 12, 12, 12, 12, 12, 12};
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4410
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4411
    private static BigInteger longRadix[] = {null, null,
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4412
        valueOf(0x4000000000000000L), valueOf(0x383d9170b85ff80bL),
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4413
        valueOf(0x4000000000000000L), valueOf(0x6765c793fa10079dL),
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4414
        valueOf(0x41c21cb8e1000000L), valueOf(0x3642798750226111L),
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4415
        valueOf(0x1000000000000000L), valueOf(0x12bf307ae81ffd59L),
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4416
        valueOf( 0xde0b6b3a7640000L), valueOf(0x4d28cb56c33fa539L),
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4417
        valueOf(0x1eca170c00000000L), valueOf(0x780c7372621bd74dL),
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4418
        valueOf(0x1e39a5057d810000L), valueOf(0x5b27ac993df97701L),
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4419
        valueOf(0x1000000000000000L), valueOf(0x27b95e997e21d9f1L),
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4420
        valueOf(0x5da0e1e53c5c8000L), valueOf( 0xb16a458ef403f19L),
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4421
        valueOf(0x16bcc41e90000000L), valueOf(0x2d04b7fdd9c0ef49L),
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4422
        valueOf(0x5658597bcaa24000L), valueOf( 0x6feb266931a75b7L),
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4423
        valueOf( 0xc29e98000000000L), valueOf(0x14adf4b7320334b9L),
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4424
        valueOf(0x226ed36478bfa000L), valueOf(0x383d9170b85ff80bL),
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4425
        valueOf(0x5a3c23e39c000000L), valueOf( 0x4e900abb53e6b71L),
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4426
        valueOf( 0x7600ec618141000L), valueOf( 0xaee5720ee830681L),
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4427
        valueOf(0x1000000000000000L), valueOf(0x172588ad4f5f0981L),
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4428
        valueOf(0x211e44f7d02c1000L), valueOf(0x2ee56725f06e5c71L),
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4429
        valueOf(0x41c21cb8e1000000L)};
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4430
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4431
    /*
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4432
     * These two arrays are the integer analogue of above.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4433
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4434
    private static int digitsPerInt[] = {0, 0, 30, 19, 15, 13, 11,
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4435
        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
  4436
        6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 5};
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4437
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4438
    private static int intRadix[] = {0, 0,
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4439
        0x40000000, 0x4546b3db, 0x40000000, 0x48c27395, 0x159fd800,
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4440
        0x75db9c97, 0x40000000, 0x17179149, 0x3b9aca00, 0xcc6db61,
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4441
        0x19a10000, 0x309f1021, 0x57f6c100, 0xa2f1b6f,  0x10000000,
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4442
        0x18754571, 0x247dbc80, 0x3547667b, 0x4c4b4000, 0x6b5a6e1d,
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4443
        0x6c20a40,  0x8d2d931,  0xb640000,  0xe8d4a51,  0x1269ae40,
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4444
        0x17179149, 0x1cb91000, 0x23744899, 0x2b73a840, 0x34e63b41,
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4445
        0x40000000, 0x4cfa3cc1, 0x5c13d840, 0x6d91b519, 0x39aa400
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4446
    };
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4447
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4448
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4449
     * These routines provide access to the two's complement representation
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4450
     * of BigIntegers.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4451
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4452
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4453
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4454
     * Returns the length of the two's complement representation in ints,
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4455
     * including space for at least one sign bit.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4456
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4457
    private int intLength() {
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  4458
        return (bitLength() >>> 5) + 1;
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4459
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4460
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4461
    /* Returns sign bit */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4462
    private int signBit() {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4463
        return signum < 0 ? 1 : 0;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4464
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4465
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4466
    /* Returns an int of sign bits */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4467
    private int signInt() {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4468
        return signum < 0 ? -1 : 0;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4469
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4470
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4471
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4472
     * Returns the specified int of the little-endian two's complement
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4473
     * representation (int 0 is the least significant).  The int number can
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4474
     * be arbitrarily high (values are logically preceded by infinitely many
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4475
     * sign ints).
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4476
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4477
    private int getInt(int n) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4478
        if (n < 0)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4479
            return 0;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4480
        if (n >= mag.length)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4481
            return signInt();
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4482
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4483
        int magInt = mag[mag.length-n-1];
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4484
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4485
        return (signum >= 0 ? magInt :
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4486
                (n <= firstNonzeroIntNum() ? -magInt : ~magInt));
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4487
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4488
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4489
    /**
23332
c36c4773fe96 8035279: Clean up internal deprecations in BigInteger
bpb
parents: 22042
diff changeset
  4490
    * Returns the index of the int that contains the first nonzero int in the
c36c4773fe96 8035279: Clean up internal deprecations in BigInteger
bpb
parents: 22042
diff changeset
  4491
    * little-endian binary representation of the magnitude (int 0 is the
c36c4773fe96 8035279: Clean up internal deprecations in BigInteger
bpb
parents: 22042
diff changeset
  4492
    * least significant). If the magnitude is zero, return value is undefined.
c36c4773fe96 8035279: Clean up internal deprecations in BigInteger
bpb
parents: 22042
diff changeset
  4493
    *
c36c4773fe96 8035279: Clean up internal deprecations in BigInteger
bpb
parents: 22042
diff changeset
  4494
    * <p>Note: never used for a BigInteger with a magnitude of zero.
c36c4773fe96 8035279: Clean up internal deprecations in BigInteger
bpb
parents: 22042
diff changeset
  4495
    * @see #getInt.
c36c4773fe96 8035279: Clean up internal deprecations in BigInteger
bpb
parents: 22042
diff changeset
  4496
    */
18286
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  4497
    private int firstNonzeroIntNum() {
23332
c36c4773fe96 8035279: Clean up internal deprecations in BigInteger
bpb
parents: 22042
diff changeset
  4498
        int fn = firstNonzeroIntNumPlusTwo - 2;
18286
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  4499
        if (fn == -2) { // firstNonzeroIntNum not initialized yet
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  4500
            // Search for the first nonzero int
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  4501
            int i;
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  4502
            int mlen = mag.length;
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  4503
            for (i = mlen - 1; i >= 0 && mag[i] == 0; i--)
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  4504
                ;
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  4505
            fn = mlen - i - 1;
23332
c36c4773fe96 8035279: Clean up internal deprecations in BigInteger
bpb
parents: 22042
diff changeset
  4506
            firstNonzeroIntNumPlusTwo = fn + 2; // offset by two to initialize
18286
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  4507
        }
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  4508
        return fn;
b38489d5aadf 4837946: Faster multiplication and exponentiation of large integers
bpb
parents: 10588
diff changeset
  4509
    }
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4510
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4511
    /** use serialVersionUID from JDK 1.1. for interoperability */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4512
    private static final long serialVersionUID = -8287574255936472291L;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4513
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4514
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4515
     * Serializable fields for BigInteger.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4516
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4517
     * @serialField signum  int
23332
c36c4773fe96 8035279: Clean up internal deprecations in BigInteger
bpb
parents: 22042
diff changeset
  4518
     *              signum of this BigInteger
c36c4773fe96 8035279: Clean up internal deprecations in BigInteger
bpb
parents: 22042
diff changeset
  4519
     * @serialField magnitude byte[]
c36c4773fe96 8035279: Clean up internal deprecations in BigInteger
bpb
parents: 22042
diff changeset
  4520
     *              magnitude array of this BigInteger
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4521
     * @serialField bitCount  int
23332
c36c4773fe96 8035279: Clean up internal deprecations in BigInteger
bpb
parents: 22042
diff changeset
  4522
     *              appears in the serialized form for backward compatibility
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4523
     * @serialField bitLength int
23332
c36c4773fe96 8035279: Clean up internal deprecations in BigInteger
bpb
parents: 22042
diff changeset
  4524
     *              appears in the serialized form for backward compatibility
c36c4773fe96 8035279: Clean up internal deprecations in BigInteger
bpb
parents: 22042
diff changeset
  4525
     * @serialField firstNonzeroByteNum int
c36c4773fe96 8035279: Clean up internal deprecations in BigInteger
bpb
parents: 22042
diff changeset
  4526
     *              appears in the serialized form for backward compatibility
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4527
     * @serialField lowestSetBit int
23332
c36c4773fe96 8035279: Clean up internal deprecations in BigInteger
bpb
parents: 22042
diff changeset
  4528
     *              appears in the serialized form for backward compatibility
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4529
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4530
    private static final ObjectStreamField[] serialPersistentFields = {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4531
        new ObjectStreamField("signum", Integer.TYPE),
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4532
        new ObjectStreamField("magnitude", byte[].class),
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4533
        new ObjectStreamField("bitCount", Integer.TYPE),
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4534
        new ObjectStreamField("bitLength", Integer.TYPE),
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4535
        new ObjectStreamField("firstNonzeroByteNum", Integer.TYPE),
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4536
        new ObjectStreamField("lowestSetBit", Integer.TYPE)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4537
        };
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4538
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4539
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4540
     * Reconstitute the {@code BigInteger} instance from a stream (that is,
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4541
     * deserialize it). The magnitude is read in as an array of bytes
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4542
     * for historical reasons, but it is converted to an array of ints
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4543
     * and the byte array is discarded.
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  4544
     * Note:
23332
c36c4773fe96 8035279: Clean up internal deprecations in BigInteger
bpb
parents: 22042
diff changeset
  4545
     * The current convention is to initialize the cache fields, bitCountPlusOne,
c36c4773fe96 8035279: Clean up internal deprecations in BigInteger
bpb
parents: 22042
diff changeset
  4546
     * bitLengthPlusOne and lowestSetBitPlusTwo, to 0 rather than some other
c36c4773fe96 8035279: Clean up internal deprecations in BigInteger
bpb
parents: 22042
diff changeset
  4547
     * marker value. Therefore, no explicit action to set these fields needs to
c36c4773fe96 8035279: Clean up internal deprecations in BigInteger
bpb
parents: 22042
diff changeset
  4548
     * be taken in readObject because those fields already have a 0 value by
c36c4773fe96 8035279: Clean up internal deprecations in BigInteger
bpb
parents: 22042
diff changeset
  4549
     * default since defaultReadObject is not being used.
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4550
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4551
    private void readObject(java.io.ObjectInputStream s)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4552
        throws java.io.IOException, ClassNotFoundException {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4553
        // prepare to read the alternate persistent fields
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4554
        ObjectInputStream.GetField fields = s.readFields();
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4555
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4556
        // Read the alternate persistent fields that we care about
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  4557
        int sign = fields.get("signum", -2);
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4558
        byte[] magnitude = (byte[])fields.get("magnitude", null);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4559
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4560
        // Validate signum
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  4561
        if (sign < -1 || sign > 1) {
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4562
            String message = "BigInteger: Invalid signum value";
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4563
            if (fields.defaulted("signum"))
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4564
                message = "BigInteger: Signum not present in stream";
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4565
            throw new java.io.StreamCorruptedException(message);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4566
        }
28309
45f25a2cf942 4026465: Provide more byte array constructors for BigInteger
bpb
parents: 25859
diff changeset
  4567
        int[] mag = stripLeadingZeroBytes(magnitude, 0, magnitude.length);
21420
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
  4568
        if ((mag.length == 0) != (sign == 0)) {
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4569
            String message = "BigInteger: signum-magnitude mismatch";
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4570
            if (fields.defaulted("magnitude"))
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4571
                message = "BigInteger: Magnitude not present in stream";
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4572
            throw new java.io.StreamCorruptedException(message);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4573
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4574
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  4575
        // Commit final fields via Unsafe
10431
448fc54a8e23 6838776: Defer initialization of static fields in java.math.BigInteger
darcy
parents: 10425
diff changeset
  4576
        UnsafeHolder.putSign(this, sign);
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4577
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4578
        // Calculate mag field from magnitude and discard magnitude
21420
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
  4579
        UnsafeHolder.putMag(this, mag);
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
  4580
        if (mag.length >= MAX_MAG_LENGTH) {
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
  4581
            try {
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
  4582
                checkRange();
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
  4583
            } catch (ArithmeticException e) {
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
  4584
                throw new java.io.StreamCorruptedException("BigInteger: Out of the supported range");
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
  4585
            }
a56f40ab71ce 6910473: java.math.BigInteger.bitLength() may return negative "int" on large numbers
bpb
parents: 20756
diff changeset
  4586
        }
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  4587
    }
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  4588
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  4589
    // Support for resetting final fields while deserializing
10431
448fc54a8e23 6838776: Defer initialization of static fields in java.math.BigInteger
darcy
parents: 10425
diff changeset
  4590
    private static class UnsafeHolder {
46873
7ac2f551b0d6 8182487: Add Unsafe.objectFieldOffset(Class, String)
redestad
parents: 38553
diff changeset
  4591
        private static final jdk.internal.misc.Unsafe unsafe
7ac2f551b0d6 8182487: Add Unsafe.objectFieldOffset(Class, String)
redestad
parents: 38553
diff changeset
  4592
                = jdk.internal.misc.Unsafe.getUnsafe();
7ac2f551b0d6 8182487: Add Unsafe.objectFieldOffset(Class, String)
redestad
parents: 38553
diff changeset
  4593
        private static final long signumOffset
7ac2f551b0d6 8182487: Add Unsafe.objectFieldOffset(Class, String)
redestad
parents: 38553
diff changeset
  4594
                = unsafe.objectFieldOffset(BigInteger.class, "signum");
7ac2f551b0d6 8182487: Add Unsafe.objectFieldOffset(Class, String)
redestad
parents: 38553
diff changeset
  4595
        private static final long magOffset
7ac2f551b0d6 8182487: Add Unsafe.objectFieldOffset(Class, String)
redestad
parents: 38553
diff changeset
  4596
                = unsafe.objectFieldOffset(BigInteger.class, "mag");
10431
448fc54a8e23 6838776: Defer initialization of static fields in java.math.BigInteger
darcy
parents: 10425
diff changeset
  4597
448fc54a8e23 6838776: Defer initialization of static fields in java.math.BigInteger
darcy
parents: 10425
diff changeset
  4598
        static void putSign(BigInteger bi, int sign) {
29220
b07abc731618 8074022: Serialization should issue a freeze action after reconstituting a graph that contains objects with final fields
chegar
parents: 28309
diff changeset
  4599
            unsafe.putInt(bi, signumOffset, sign);
10431
448fc54a8e23 6838776: Defer initialization of static fields in java.math.BigInteger
darcy
parents: 10425
diff changeset
  4600
        }
448fc54a8e23 6838776: Defer initialization of static fields in java.math.BigInteger
darcy
parents: 10425
diff changeset
  4601
448fc54a8e23 6838776: Defer initialization of static fields in java.math.BigInteger
darcy
parents: 10425
diff changeset
  4602
        static void putMag(BigInteger bi, int[] magnitude) {
52220
9c260a6b6471 8207146: Rename jdk.internal.misc.Unsafe::xxxObject to xxxReference
mchung
parents: 52088
diff changeset
  4603
            unsafe.putReference(bi, magOffset, magnitude);
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  4604
        }
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4605
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4606
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4607
    /**
23332
c36c4773fe96 8035279: Clean up internal deprecations in BigInteger
bpb
parents: 22042
diff changeset
  4608
     * Save the {@code BigInteger} instance to a stream.  The magnitude of a
c36c4773fe96 8035279: Clean up internal deprecations in BigInteger
bpb
parents: 22042
diff changeset
  4609
     * {@code BigInteger} is serialized as a byte array for historical reasons.
c36c4773fe96 8035279: Clean up internal deprecations in BigInteger
bpb
parents: 22042
diff changeset
  4610
     * To maintain compatibility with older implementations, the integers
c36c4773fe96 8035279: Clean up internal deprecations in BigInteger
bpb
parents: 22042
diff changeset
  4611
     * -1, -1, -2, and -2 are written as the values of the obsolete fields
c36c4773fe96 8035279: Clean up internal deprecations in BigInteger
bpb
parents: 22042
diff changeset
  4612
     * {@code bitCount}, {@code bitLength}, {@code lowestSetBit}, and
c36c4773fe96 8035279: Clean up internal deprecations in BigInteger
bpb
parents: 22042
diff changeset
  4613
     * {@code firstNonzeroByteNum}, respectively.  These values are compatible
c36c4773fe96 8035279: Clean up internal deprecations in BigInteger
bpb
parents: 22042
diff changeset
  4614
     * with older implementations, but will be ignored by current
c36c4773fe96 8035279: Clean up internal deprecations in BigInteger
bpb
parents: 22042
diff changeset
  4615
     * implementations.
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4616
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4617
    private void writeObject(ObjectOutputStream s) throws IOException {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4618
        // set the values of the Serializable fields
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4619
        ObjectOutputStream.PutField fields = s.putFields();
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4620
        fields.put("signum", signum);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4621
        fields.put("magnitude", magSerializedForm());
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  4622
        // The values written for cached fields are compatible with older
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  4623
        // versions, but are ignored in readObject so don't otherwise matter.
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4624
        fields.put("bitCount", -1);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4625
        fields.put("bitLength", -1);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4626
        fields.put("lowestSetBit", -2);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4627
        fields.put("firstNonzeroByteNum", -2);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4628
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4629
        // save them
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4630
        s.writeFields();
23332
c36c4773fe96 8035279: Clean up internal deprecations in BigInteger
bpb
parents: 22042
diff changeset
  4631
    }
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4632
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4633
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4634
     * Returns the mag array as an array of bytes.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4635
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4636
    private byte[] magSerializedForm() {
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  4637
        int len = mag.length;
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  4638
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  4639
        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
  4640
        int byteLen = (bitLen + 7) >>> 3;
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4641
        byte[] result = new byte[byteLen];
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4642
2922
dd6d609861f0 6622432: RFE: Performance improvements to java.math.BigDecimal
xlu
parents: 2
diff changeset
  4643
        for (int i = byteLen - 1, bytesCopied = 4, intIndex = len - 1, nextInt = 0;
19061
d48848ef5670 8020641: Clean up some code style in recent BigInteger contributions
bpb
parents: 19060
diff changeset
  4644
             i >= 0; i--) {
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4645
            if (bytesCopied == 4) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4646
                nextInt = mag[intIndex--];
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4647
                bytesCopied = 1;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4648
            } else {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4649
                nextInt >>>= 8;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4650
                bytesCopied++;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4651
            }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4652
            result[i] = (byte)nextInt;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4653
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4654
        return result;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4655
    }
10588
d8173a78bdca 6879143: java.math.BigInteger misses the xxxValueExact methods
darcy
parents: 10431
diff changeset
  4656
d8173a78bdca 6879143: java.math.BigInteger misses the xxxValueExact methods
darcy
parents: 10431
diff changeset
  4657
    /**
d8173a78bdca 6879143: java.math.BigInteger misses the xxxValueExact methods
darcy
parents: 10431
diff changeset
  4658
     * Converts this {@code BigInteger} to a {@code long}, checking
d8173a78bdca 6879143: java.math.BigInteger misses the xxxValueExact methods
darcy
parents: 10431
diff changeset
  4659
     * for lost information.  If the value of this {@code BigInteger}
d8173a78bdca 6879143: java.math.BigInteger misses the xxxValueExact methods
darcy
parents: 10431
diff changeset
  4660
     * is out of the range of the {@code long} type, then an
d8173a78bdca 6879143: java.math.BigInteger misses the xxxValueExact methods
darcy
parents: 10431
diff changeset
  4661
     * {@code ArithmeticException} is thrown.
d8173a78bdca 6879143: java.math.BigInteger misses the xxxValueExact methods
darcy
parents: 10431
diff changeset
  4662
     *
d8173a78bdca 6879143: java.math.BigInteger misses the xxxValueExact methods
darcy
parents: 10431
diff changeset
  4663
     * @return this {@code BigInteger} converted to a {@code long}.
d8173a78bdca 6879143: java.math.BigInteger misses the xxxValueExact methods
darcy
parents: 10431
diff changeset
  4664
     * @throws ArithmeticException if the value of {@code this} will
d8173a78bdca 6879143: java.math.BigInteger misses the xxxValueExact methods
darcy
parents: 10431
diff changeset
  4665
     * not exactly fit in a {@code long}.
d8173a78bdca 6879143: java.math.BigInteger misses the xxxValueExact methods
darcy
parents: 10431
diff changeset
  4666
     * @see BigInteger#longValue
d8173a78bdca 6879143: java.math.BigInteger misses the xxxValueExact methods
darcy
parents: 10431
diff changeset
  4667
     * @since  1.8
d8173a78bdca 6879143: java.math.BigInteger misses the xxxValueExact methods
darcy
parents: 10431
diff changeset
  4668
     */
d8173a78bdca 6879143: java.math.BigInteger misses the xxxValueExact methods
darcy
parents: 10431
diff changeset
  4669
    public long longValueExact() {
d8173a78bdca 6879143: java.math.BigInteger misses the xxxValueExact methods
darcy
parents: 10431
diff changeset
  4670
        if (mag.length <= 2 && bitLength() <= 63)
d8173a78bdca 6879143: java.math.BigInteger misses the xxxValueExact methods
darcy
parents: 10431
diff changeset
  4671
            return longValue();
d8173a78bdca 6879143: java.math.BigInteger misses the xxxValueExact methods
darcy
parents: 10431
diff changeset
  4672
        else
d8173a78bdca 6879143: java.math.BigInteger misses the xxxValueExact methods
darcy
parents: 10431
diff changeset
  4673
            throw new ArithmeticException("BigInteger out of long range");
d8173a78bdca 6879143: java.math.BigInteger misses the xxxValueExact methods
darcy
parents: 10431
diff changeset
  4674
    }
d8173a78bdca 6879143: java.math.BigInteger misses the xxxValueExact methods
darcy
parents: 10431
diff changeset
  4675
d8173a78bdca 6879143: java.math.BigInteger misses the xxxValueExact methods
darcy
parents: 10431
diff changeset
  4676
    /**
d8173a78bdca 6879143: java.math.BigInteger misses the xxxValueExact methods
darcy
parents: 10431
diff changeset
  4677
     * Converts this {@code BigInteger} to an {@code int}, checking
d8173a78bdca 6879143: java.math.BigInteger misses the xxxValueExact methods
darcy
parents: 10431
diff changeset
  4678
     * for lost information.  If the value of this {@code BigInteger}
d8173a78bdca 6879143: java.math.BigInteger misses the xxxValueExact methods
darcy
parents: 10431
diff changeset
  4679
     * is out of the range of the {@code int} type, then an
d8173a78bdca 6879143: java.math.BigInteger misses the xxxValueExact methods
darcy
parents: 10431
diff changeset
  4680
     * {@code ArithmeticException} is thrown.
d8173a78bdca 6879143: java.math.BigInteger misses the xxxValueExact methods
darcy
parents: 10431
diff changeset
  4681
     *
d8173a78bdca 6879143: java.math.BigInteger misses the xxxValueExact methods
darcy
parents: 10431
diff changeset
  4682
     * @return this {@code BigInteger} converted to an {@code int}.
d8173a78bdca 6879143: java.math.BigInteger misses the xxxValueExact methods
darcy
parents: 10431
diff changeset
  4683
     * @throws ArithmeticException if the value of {@code this} will
37880
60ec48925dc6 8156661: Handful of typos in javadoc
igerasim
parents: 36671
diff changeset
  4684
     * not exactly fit in an {@code int}.
10588
d8173a78bdca 6879143: java.math.BigInteger misses the xxxValueExact methods
darcy
parents: 10431
diff changeset
  4685
     * @see BigInteger#intValue
d8173a78bdca 6879143: java.math.BigInteger misses the xxxValueExact methods
darcy
parents: 10431
diff changeset
  4686
     * @since  1.8
d8173a78bdca 6879143: java.math.BigInteger misses the xxxValueExact methods
darcy
parents: 10431
diff changeset
  4687
     */
d8173a78bdca 6879143: java.math.BigInteger misses the xxxValueExact methods
darcy
parents: 10431
diff changeset
  4688
    public int intValueExact() {
d8173a78bdca 6879143: java.math.BigInteger misses the xxxValueExact methods
darcy
parents: 10431
diff changeset
  4689
        if (mag.length <= 1 && bitLength() <= 31)
d8173a78bdca 6879143: java.math.BigInteger misses the xxxValueExact methods
darcy
parents: 10431
diff changeset
  4690
            return intValue();
d8173a78bdca 6879143: java.math.BigInteger misses the xxxValueExact methods
darcy
parents: 10431
diff changeset
  4691
        else
d8173a78bdca 6879143: java.math.BigInteger misses the xxxValueExact methods
darcy
parents: 10431
diff changeset
  4692
            throw new ArithmeticException("BigInteger out of int range");
d8173a78bdca 6879143: java.math.BigInteger misses the xxxValueExact methods
darcy
parents: 10431
diff changeset
  4693
    }
d8173a78bdca 6879143: java.math.BigInteger misses the xxxValueExact methods
darcy
parents: 10431
diff changeset
  4694
d8173a78bdca 6879143: java.math.BigInteger misses the xxxValueExact methods
darcy
parents: 10431
diff changeset
  4695
    /**
d8173a78bdca 6879143: java.math.BigInteger misses the xxxValueExact methods
darcy
parents: 10431
diff changeset
  4696
     * Converts this {@code BigInteger} to a {@code short}, checking
d8173a78bdca 6879143: java.math.BigInteger misses the xxxValueExact methods
darcy
parents: 10431
diff changeset
  4697
     * for lost information.  If the value of this {@code BigInteger}
d8173a78bdca 6879143: java.math.BigInteger misses the xxxValueExact methods
darcy
parents: 10431
diff changeset
  4698
     * is out of the range of the {@code short} type, then an
d8173a78bdca 6879143: java.math.BigInteger misses the xxxValueExact methods
darcy
parents: 10431
diff changeset
  4699
     * {@code ArithmeticException} is thrown.
d8173a78bdca 6879143: java.math.BigInteger misses the xxxValueExact methods
darcy
parents: 10431
diff changeset
  4700
     *
d8173a78bdca 6879143: java.math.BigInteger misses the xxxValueExact methods
darcy
parents: 10431
diff changeset
  4701
     * @return this {@code BigInteger} converted to a {@code short}.
d8173a78bdca 6879143: java.math.BigInteger misses the xxxValueExact methods
darcy
parents: 10431
diff changeset
  4702
     * @throws ArithmeticException if the value of {@code this} will
d8173a78bdca 6879143: java.math.BigInteger misses the xxxValueExact methods
darcy
parents: 10431
diff changeset
  4703
     * not exactly fit in a {@code short}.
d8173a78bdca 6879143: java.math.BigInteger misses the xxxValueExact methods
darcy
parents: 10431
diff changeset
  4704
     * @see BigInteger#shortValue
d8173a78bdca 6879143: java.math.BigInteger misses the xxxValueExact methods
darcy
parents: 10431
diff changeset
  4705
     * @since  1.8
d8173a78bdca 6879143: java.math.BigInteger misses the xxxValueExact methods
darcy
parents: 10431
diff changeset
  4706
     */
d8173a78bdca 6879143: java.math.BigInteger misses the xxxValueExact methods
darcy
parents: 10431
diff changeset
  4707
    public short shortValueExact() {
d8173a78bdca 6879143: java.math.BigInteger misses the xxxValueExact methods
darcy
parents: 10431
diff changeset
  4708
        if (mag.length <= 1 && bitLength() <= 31) {
d8173a78bdca 6879143: java.math.BigInteger misses the xxxValueExact methods
darcy
parents: 10431
diff changeset
  4709
            int value = intValue();
d8173a78bdca 6879143: java.math.BigInteger misses the xxxValueExact methods
darcy
parents: 10431
diff changeset
  4710
            if (value >= Short.MIN_VALUE && value <= Short.MAX_VALUE)
d8173a78bdca 6879143: java.math.BigInteger misses the xxxValueExact methods
darcy
parents: 10431
diff changeset
  4711
                return shortValue();
d8173a78bdca 6879143: java.math.BigInteger misses the xxxValueExact methods
darcy
parents: 10431
diff changeset
  4712
        }
d8173a78bdca 6879143: java.math.BigInteger misses the xxxValueExact methods
darcy
parents: 10431
diff changeset
  4713
        throw new ArithmeticException("BigInteger out of short range");
d8173a78bdca 6879143: java.math.BigInteger misses the xxxValueExact methods
darcy
parents: 10431
diff changeset
  4714
    }
d8173a78bdca 6879143: java.math.BigInteger misses the xxxValueExact methods
darcy
parents: 10431
diff changeset
  4715
d8173a78bdca 6879143: java.math.BigInteger misses the xxxValueExact methods
darcy
parents: 10431
diff changeset
  4716
    /**
d8173a78bdca 6879143: java.math.BigInteger misses the xxxValueExact methods
darcy
parents: 10431
diff changeset
  4717
     * Converts this {@code BigInteger} to a {@code byte}, checking
d8173a78bdca 6879143: java.math.BigInteger misses the xxxValueExact methods
darcy
parents: 10431
diff changeset
  4718
     * for lost information.  If the value of this {@code BigInteger}
d8173a78bdca 6879143: java.math.BigInteger misses the xxxValueExact methods
darcy
parents: 10431
diff changeset
  4719
     * is out of the range of the {@code byte} type, then an
d8173a78bdca 6879143: java.math.BigInteger misses the xxxValueExact methods
darcy
parents: 10431
diff changeset
  4720
     * {@code ArithmeticException} is thrown.
d8173a78bdca 6879143: java.math.BigInteger misses the xxxValueExact methods
darcy
parents: 10431
diff changeset
  4721
     *
d8173a78bdca 6879143: java.math.BigInteger misses the xxxValueExact methods
darcy
parents: 10431
diff changeset
  4722
     * @return this {@code BigInteger} converted to a {@code byte}.
d8173a78bdca 6879143: java.math.BigInteger misses the xxxValueExact methods
darcy
parents: 10431
diff changeset
  4723
     * @throws ArithmeticException if the value of {@code this} will
d8173a78bdca 6879143: java.math.BigInteger misses the xxxValueExact methods
darcy
parents: 10431
diff changeset
  4724
     * not exactly fit in a {@code byte}.
d8173a78bdca 6879143: java.math.BigInteger misses the xxxValueExact methods
darcy
parents: 10431
diff changeset
  4725
     * @see BigInteger#byteValue
d8173a78bdca 6879143: java.math.BigInteger misses the xxxValueExact methods
darcy
parents: 10431
diff changeset
  4726
     * @since  1.8
d8173a78bdca 6879143: java.math.BigInteger misses the xxxValueExact methods
darcy
parents: 10431
diff changeset
  4727
     */
d8173a78bdca 6879143: java.math.BigInteger misses the xxxValueExact methods
darcy
parents: 10431
diff changeset
  4728
    public byte byteValueExact() {
d8173a78bdca 6879143: java.math.BigInteger misses the xxxValueExact methods
darcy
parents: 10431
diff changeset
  4729
        if (mag.length <= 1 && bitLength() <= 31) {
d8173a78bdca 6879143: java.math.BigInteger misses the xxxValueExact methods
darcy
parents: 10431
diff changeset
  4730
            int value = intValue();
d8173a78bdca 6879143: java.math.BigInteger misses the xxxValueExact methods
darcy
parents: 10431
diff changeset
  4731
            if (value >= Byte.MIN_VALUE && value <= Byte.MAX_VALUE)
d8173a78bdca 6879143: java.math.BigInteger misses the xxxValueExact methods
darcy
parents: 10431
diff changeset
  4732
                return byteValue();
d8173a78bdca 6879143: java.math.BigInteger misses the xxxValueExact methods
darcy
parents: 10431
diff changeset
  4733
        }
d8173a78bdca 6879143: java.math.BigInteger misses the xxxValueExact methods
darcy
parents: 10431
diff changeset
  4734
        throw new ArithmeticException("BigInteger out of byte range");
d8173a78bdca 6879143: java.math.BigInteger misses the xxxValueExact methods
darcy
parents: 10431
diff changeset
  4735
    }
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  4736
}