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