1 /*
2  * Hunt - A refined core library for D programming language.
3  *
4  * Copyright (C) 2018-2019 HuntLabs
5  *
6  * Website: https://www.huntlabs.net/
7  *
8  * Licensed under the Apache-2.0 License.
9  *
10  */
11 
12 module hunt.math.BigInteger;
13 
14 import hunt.Double;
15 import hunt.Float;
16 import hunt.Integer;
17 import hunt.Long;
18 import hunt.Number;
19 
20 import hunt.Char;
21 import hunt.text.CharacterData;
22 import hunt.Exceptions;
23 import hunt.text;
24 
25 import std.algorithm;
26 import std.conv;
27 import std.math;
28 import std.random;
29 import std.string;
30 
31 /**
32  * Immutable arbitrary-precision integers.  All operations behave as if
33  * BigIntegers were represented in two's-complement notation (like Java's
34  * primitive integer types).  BigInteger provides analogues to all of Java's
35  * primitive integer operators, and all relevant methods from java.lang.std.math.
36  * Additionally, BigInteger provides operations for modular arithmetic, GCD
37  * calculation, primality testing, prime generation, bit manipulation,
38  * and a few other miscellaneous operations.
39  *
40  * <p>Semantics of arithmetic operations exactly mimic those of Java's integer
41  * arithmetic operators, as defined in <i>The Java Language Specification</i>.
42  * For example, division by zero throws an {@code ArithmeticException}, and
43  * division of a negative by a positive yields a negative (or zero) remainder.
44  * All of the details in the Spec concerning overflow are ignored, as
45  * BigIntegers are made as large as necessary to accommodate the results of an
46  * operation.
47  *
48  * <p>Semantics of shift operations extend those of Java's shift operators
49  * to allow for negative shift distances.  A right-shift with a negative
50  * shift distance results in a left shift, and vice-versa.  The unsigned
51  * right shift operator ({@code >>>}) is omitted, as this operation makes
52  * little sense in combination with the "infinite word size" abstraction
53  * provided by this class.
54  *
55  * <p>Semantics of bitwise logical operations exactly mimic those of Java's
56  * bitwise integer operators.  The binary operators ({@code and},
57  * {@code or}, {@code xor}) implicitly perform sign extension on the shorter
58  * of the two operands prior to performing the operation.
59  *
60  * <p>Comparison operations perform signed integer comparisons, analogous to
61  * those performed by Java's relational and equality operators.
62  *
63  * <p>Modular arithmetic operations are provided to compute residues, perform
64  * exponentiation, and compute multiplicative inverses.  These methods always
65  * return a non-negative result, between {@code 0} and {@code (modulus - 1)},
66  * inclusive.
67  *
68  * <p>Bit operations operate on a single bit of the two's-complement
69  * representation of their operand.  If necessary, the operand is sign-
70  * extended so that it contains the designated bit.  None of the single-bit
71  * operations can produce a BigInteger with a different sign from the
72  * BigInteger being operated on, as they affect only a single bit, and the
73  * "infinite word size" abstraction provided by this class ensures that there
74  * are infinitely many "virtual sign bits" preceding each BigInteger.
75  *
76  * <p>For the sake of brevity and clarity, pseudo-code is used throughout the
77  * descriptions of BigInteger methods.  The pseudo-code expression
78  * {@code (i + j)} is shorthand for "a BigInteger whose value is
79  * that of the BigInteger {@code i} plus that of the BigInteger {@code j}."
80  * The pseudo-code expression {@code (i == j)} is shorthand for
81  * "{@code true} if and only if the BigInteger {@code i} represents the same
82  * value as the BigInteger {@code j}."  Other pseudo-code expressions are
83  * interpreted similarly.
84  *
85  * <p>All methods and constructors in this class throw
86  * {@code NullPointerException} when passed
87  * a null object reference for any input parameter.
88  *
89  * BigInteger must support values in the range
90  * -2<sup>{@code int.max}</sup> (exclusive) to
91  * +2<sup>{@code int.max}</sup> (exclusive)
92  * and may support values outside of that range.
93  *
94  * The range of probable prime values is limited and may be less than
95  * the full supported positive range of {@code BigInteger}.
96  * The range must be at least 1 to 2<sup>500000000</sup>.
97  *
98  * @implNote
99  * BigInteger constructors and operations throw {@code ArithmeticException} when
100  * the result is out of the supported range of
101  * -2<sup>{@code int.max}</sup> (exclusive) to
102  * +2<sup>{@code int.max}</sup> (exclusive).
103  *
104  * @see     BigDecimal
105  * @jls     4.2.2 Integer Operations
106  * @author  Josh Bloch
107  * @author  Michael McCloskey
108  * @author  Alan Eliasen
109  * @author  Timothy Buktu
110  */
111 
112 class BigInteger : Number {
113     /**
114      * The signum of this BigInteger: -1 for negative, 0 for zero, or
115      * 1 for positive.  Note that the BigInteger zero <em>must</em> have
116      * a signum of 0.  This is necessary to ensures that there is exactly one
117      * representation for each BigInteger value.
118      */
119     private int _signum;
120 
121     /**
122      * The magnitude of this BigInteger, in <i>big-endian</i> order: the
123      * zeroth element of this array is the most-significant int of the
124      * magnitude.  The magnitude must be "minimal" in that the most-significant
125      * int ({@code mag[0]}) must be non-zero.  This is necessary to
126      * ensure that there is exactly one representation for each BigInteger
127      * value.  Note that this implies that the BigInteger zero has a
128      * zero-length mag array.
129      */
130     private int[] mag;
131 
132     // The following fields are stable variables. A stable variable's value
133     // changes at most once from the default zero value to a non-zero stable
134     // value. A stable value is calculated lazily on demand.
135 
136     /**
137      * One plus the bitCount of this BigInteger. This is a stable variable.
138      *
139      * @see #bitCount
140      */
141     private int bitCountPlusOne;
142 
143     /**
144      * One plus the bitLength of this BigInteger. This is a stable variable.
145      * (either value is acceptable).
146      *
147      * @see #bitLength()
148      */
149     private int bitLengthPlusOne;
150 
151     /**
152      * Two plus the lowest set bit of this BigInteger. This is a stable variable.
153      *
154      * @see #getLowestSetBit
155      */
156     private int lowestSetBitPlusTwo;
157 
158     /**
159      * Two plus the index of the lowest-order int in the magnitude of this
160      * BigInteger that contains a nonzero int. This is a stable variable. The
161      * least significant int has int-number 0, the next int in order of
162      * increasing significance has int-number 1, and so forth.
163      *
164      * <p>Note: never used for a BigInteger with a magnitude of zero.
165      *
166      * @see #firstNonzeroIntNum()
167      */
168     private int firstNonzeroIntNumPlusTwo;
169 
170     /**
171      * This mask is used to obtain the value of an int as if it were unsigned.
172      */
173     enum long LONG_MASK = 0xffffffffL;
174 
175     /**
176      * This constant limits {@code mag.length} of BigIntegers to the supported
177      * range.
178      */
179     private enum int MAX_MAG_LENGTH = int.max / int.sizeof + 1; // (1 << 26)
180 
181     /**
182      * Bit lengths larger than this constant can cause overflow in searchLen
183      * calculation and in BitSieve.singleSearch method.
184      */
185     private enum int PRIME_SEARCH_BIT_LENGTH_LIMIT = 500000000;
186 
187     /**
188      * The threshold value for using Karatsuba multiplication.  If the number
189      * of ints in both mag arrays are greater than this number, then
190      * Karatsuba multiplication will be used.   This value is found
191      * experimentally to work well.
192      */
193     private enum int KARATSUBA_THRESHOLD = 80;
194 
195     /**
196      * The threshold value for using 3-way Toom-Cook multiplication.
197      * If the number of ints in each mag array is greater than the
198      * Karatsuba threshold, and the number of ints in at least one of
199      * the mag arrays is greater than this threshold, then Toom-Cook
200      * multiplication will be used.
201      */
202     private enum int TOOM_COOK_THRESHOLD = 240;
203 
204     /**
205      * The threshold value for using Karatsuba squaring.  If the number
206      * of ints in the number are larger than this value,
207      * Karatsuba squaring will be used.   This value is found
208      * experimentally to work well.
209      */
210     private enum int KARATSUBA_SQUARE_THRESHOLD = 128;
211 
212     /**
213      * The threshold value for using Toom-Cook squaring.  If the number
214      * of ints in the number are larger than this value,
215      * Toom-Cook squaring will be used.   This value is found
216      * experimentally to work well.
217      */
218     private enum int TOOM_COOK_SQUARE_THRESHOLD = 216;
219 
220     /**
221      * The threshold value for using Burnikel-Ziegler division.  If the number
222      * of ints in the divisor are larger than this value, Burnikel-Ziegler
223      * division may be used.  This value is found experimentally to work well.
224      */
225     enum int BURNIKEL_ZIEGLER_THRESHOLD = 80;
226 
227     /**
228      * The offset value for using Burnikel-Ziegler division.  If the number
229      * of ints in the divisor exceeds the Burnikel-Ziegler threshold, and the
230      * number of ints in the dividend is greater than the number of ints in the
231      * divisor plus this value, Burnikel-Ziegler division will be used.  This
232      * value is found experimentally to work well.
233      */
234     enum int BURNIKEL_ZIEGLER_OFFSET = 40;
235 
236     /**
237      * The threshold value for using Schoenhage recursive base conversion. If
238      * the number of ints in the number are larger than this value,
239      * the Schoenhage algorithm will be used.  In practice, it appears that the
240      * Schoenhage routine is faster for any threshold down to 2, and is
241      * relatively flat for thresholds between 2-25, so this choice may be
242      * varied within this range for very small effect.
243      */
244     private enum int SCHOENHAGE_BASE_CONVERSION_THRESHOLD = 20;
245 
246     /**
247      * The threshold value for using squaring code to perform multiplication
248      * of a {@code BigInteger} instance by itself.  If the number of ints in
249      * the number are larger than this value, {@code multiply(this)} will
250      * return {@code square()}.
251      */
252     private enum int MULTIPLY_SQUARE_THRESHOLD = 20;
253 
254     /**
255      * The threshold for using an intrinsic version of
256      * implMontgomeryXXX to perform Montgomery multiplication.  If the
257      * number of ints in the number is more than this value we do not
258      * use the intrinsic.
259      */
260     private enum int MONTGOMERY_INTRINSIC_THRESHOLD = 512;
261 
262 
263     // Constructors
264 
265     /**
266      * Translates a byte sub-array containing the two's-complement binary
267      * representation of a BigInteger into a BigInteger.  The sub-array is
268      * specified via an offset into the array and a length.  The sub-array is
269      * assumed to be in <i>big-endian</i> byte-order: the most significant
270      * byte is the element at index {@code off}.  The {@code val} array is
271      * assumed to be unchanged for the duration of the constructor call.
272      *
273      * An {@code IndexOutOfBoundsException} is thrown if the length of the array
274      * {@code val} is non-zero and either {@code off} is negative, {@code len}
275      * is negative, or {@code off+len} is greater than the length of
276      * {@code val}.
277      *
278      * @param  val byte array containing a sub-array which is the big-endian
279      *         two's-complement binary representation of a BigInteger.
280      * @param  off the start offset of the binary representation.
281      * @param  len the number of bytes to use.
282      * @throws NumberFormatException {@code val} is zero bytes long.
283      * @throws IndexOutOfBoundsException if the provided array offset and
284      *         length would cause an index into the byte array to be
285      *         negative or greater than or equal to the array length.
286      */
287     this(byte[] val, int off, int len) {
288         if (val.length == 0) {
289             throw new NumberFormatException("Zero length BigInteger");
290         } else if ((off < 0) || (off >= cast(int)val.length) || (len < 0) ||
291                    (len > val.length - off)) { // 0 <= off < val.length
292             throw new IndexOutOfBoundsException();
293         }
294 
295         if (val[off] < 0) {
296             mag = makePositive(val, off, len);
297             _signum = -1;
298         } else {
299             mag = stripLeadingZeroBytes(val, off, len);
300             _signum = (mag.length == 0 ? 0 : 1);
301         }
302         if (mag.length >= MAX_MAG_LENGTH) {
303             checkRange();
304         }
305     }
306 
307     /**
308      * Translates a byte array containing the two's-complement binary
309      * representation of a BigInteger into a BigInteger.  The input array is
310      * assumed to be in <i>big-endian</i> byte-order: the most significant
311      * byte is in the zeroth element.  The {@code val} array is assumed to be
312      * unchanged for the duration of the constructor call.
313      *
314      * @param  val big-endian two's-complement binary representation of a
315      *         BigInteger.
316      * @throws NumberFormatException {@code val} is zero bytes long.
317      */
318     this(byte[] val) {
319         this(val, 0, cast(int)val.length);
320     }
321 
322     /**
323      * This private constructor translates an int array containing the
324      * two's-complement binary representation of a BigInteger into a
325      * BigInteger. The input array is assumed to be in <i>big-endian</i>
326      * int-order: the most significant int is in the zeroth element.  The
327      * {@code val} array is assumed to be unchanged for the duration of
328      * the constructor call.
329      */
330     private this(int[] val) {
331         if (val.length == 0)
332             throw new NumberFormatException("Zero length BigInteger");
333 
334         if (val[0] < 0) {
335             mag = makePositive(val);
336             _signum = -1;
337         } else {
338             mag = trustedStripLeadingZeroInts(val);
339             _signum = (mag.length == 0 ? 0 : 1);
340         }
341         if (mag.length >= MAX_MAG_LENGTH) {
342             checkRange();
343         }
344     }
345 
346     /**
347      * Translates the sign-magnitude representation of a BigInteger into a
348      * BigInteger.  The sign is represented as an integer signum value: -1 for
349      * negative, 0 for zero, or 1 for positive.  The magnitude is a sub-array of
350      * a byte array in <i>big-endian</i> byte-order: the most significant byte
351      * is the element at index {@code off}.  A zero value of the length
352      * {@code len} is permissible, and will result in a BigInteger value of 0,
353      * whether signum is -1, 0 or 1.  The {@code magnitude} array is assumed to
354      * be unchanged for the duration of the constructor call.
355      *
356      * An {@code IndexOutOfBoundsException} is thrown if the length of the array
357      * {@code magnitude} is non-zero and either {@code off} is negative,
358      * {@code len} is negative, or {@code off+len} is greater than the length of
359      * {@code magnitude}.
360      *
361      * @param  signum signum of the number (-1 for negative, 0 for zero, 1
362      *         for positive).
363      * @param  magnitude big-endian binary representation of the magnitude of
364      *         the number.
365      * @param  off the start offset of the binary representation.
366      * @param  len the number of bytes to use.
367      * @throws NumberFormatException {@code signum} is not one of the three
368      *         legal values (-1, 0, and 1), or {@code signum} is 0 and
369      *         {@code magnitude} contains one or more non-zero bytes.
370      * @throws IndexOutOfBoundsException if the provided array offset and
371      *         length would cause an index into the byte array to be
372      *         negative or greater than or equal to the array length.
373      */
374     this(int signum, byte[] magnitude, int off, int len) {
375         if (signum < -1 || signum > 1) {
376             throw(new NumberFormatException("Invalid signum value"));
377         } else if ((off < 0) || (len < 0) ||
378             (len > 0 &&
379                 ((off >= magnitude.length) ||
380                  (len > magnitude.length - off)))) { // 0 <= off < magnitude.length
381             throw new IndexOutOfBoundsException();
382         }
383 
384         // stripLeadingZeroBytes() returns a zero length array if len == 0
385         this.mag = stripLeadingZeroBytes(magnitude, off, len);
386 
387         if (this.mag.length == 0) {
388             this._signum = 0;
389         } else {
390             if (signum == 0)
391                 throw(new NumberFormatException("signum-magnitude mismatch"));
392             this._signum = signum;
393         }
394         if (mag.length >= MAX_MAG_LENGTH) {
395             checkRange();
396         }
397     }
398 
399     /**
400      * Translates the sign-magnitude representation of a BigInteger into a
401      * BigInteger.  The sign is represented as an integer signum value: -1 for
402      * negative, 0 for zero, or 1 for positive.  The magnitude is a byte array
403      * in <i>big-endian</i> byte-order: the most significant byte is the
404      * zeroth element.  A zero-length magnitude array is permissible, and will
405      * result in a BigInteger value of 0, whether signum is -1, 0 or 1.  The
406      * {@code magnitude} array is assumed to be unchanged for the duration of
407      * the constructor call.
408      *
409      * @param  signum signum of the number (-1 for negative, 0 for zero, 1
410      *         for positive).
411      * @param  magnitude big-endian binary representation of the magnitude of
412      *         the number.
413      * @throws NumberFormatException {@code signum} is not one of the three
414      *         legal values (-1, 0, and 1), or {@code signum} is 0 and
415      *         {@code magnitude} contains one or more non-zero bytes.
416      */
417     this(int signum, byte[] magnitude) {
418          this(signum, magnitude, 0, cast(int)magnitude.length);
419     }
420 
421     /**
422      * A constructor for internal use that translates the sign-magnitude
423      * representation of a BigInteger into a BigInteger. It checks the
424      * arguments and copies the magnitude so this constructor would be
425      * safe for external use.  The {@code magnitude} array is assumed to be
426      * unchanged for the duration of the constructor call.
427      */
428     private this(int signum, int[] magnitude) {
429         this.mag = stripLeadingZeroInts(magnitude);
430 
431         if (signum < -1 || signum > 1)
432             throw(new NumberFormatException("Invalid signum value"));
433 
434         if (this.mag.length == 0) {
435             this._signum = 0;
436         } else {
437             if (signum == 0)
438                 throw(new NumberFormatException("signum-magnitude mismatch"));
439             this._signum = signum;
440         }
441         if (mag.length >= MAX_MAG_LENGTH) {
442             checkRange();
443         }
444     }
445 
446     /**
447      * Translates the string representation of a BigInteger in the
448      * specified radix into a BigInteger.  The string representation
449      * consists of an optional minus or plus sign followed by a
450      * sequence of one or more digits in the specified radix.  The
451      * character-to-digit mapping is provided by {@code
452      * CharacterHelper.digit}.  The string may not contain any extraneous
453      * characters (whitespace, for example).
454      *
455      * @param val string representation of BigInteger.
456      * @param radix radix to be used in interpreting {@code val}.
457      * @throws NumberFormatException {@code val} is not a valid representation
458      *         of a BigInteger in the specified radix, or {@code radix} is
459      *         outside the range from {@link Character#MIN_RADIX} to
460      *         {@link Character#MAX_RADIX}, inclusive.
461      * @see    Character#digit
462      */
463     this(string val, int radix) {
464         int cursor = 0, numDigits;
465         int len = cast(int)val.length;
466 
467         if (radix < Char.MIN_RADIX || radix > Char.MAX_RADIX)
468             throw new NumberFormatException("Radix out of range");
469         if (len == 0)
470             throw new NumberFormatException("Zero length BigInteger");
471 
472         // Check for at most one leading sign
473         int sign = 1;
474         ptrdiff_t index1 = val.lastIndexOf('-');
475         ptrdiff_t index2 = val.lastIndexOf('+');
476         if (index1 >= 0) {
477             if (index1 != 0 || index2 >= 0) {
478                 throw new NumberFormatException("Illegal embedded sign character");
479             }
480             sign = -1;
481             cursor = 1;
482         } else if (index2 >= 0) {
483             if (index2 != 0) {
484                 throw new NumberFormatException("Illegal embedded sign character");
485             }
486             cursor = 1;
487         }
488         if (cursor == len)
489             throw new NumberFormatException("Zero length BigInteger");
490 
491         // Skip leading zeros and compute number of digits in magnitude
492         while (cursor < len &&
493                CharacterHelper.digit(val[cursor], radix) == 0) {
494             cursor++;
495         }
496 
497         if (cursor == len) {
498             _signum = 0;
499             mag = ZERO.mag;
500             return;
501         }
502 
503         numDigits = len - cursor;
504         _signum = sign;
505 
506         // Pre-allocate array of expected size. May be too large but can
507         // never be too small. Typically exact.
508         long numBits = ((numDigits * bitsPerDigit[radix]) >>> 10) + 1;
509         if (numBits + 31 >= (1L << 32)) {
510             reportOverflow();
511         }
512         int numWords = cast(int) (numBits + 31) >>> 5;
513         int[] magnitude = new int[numWords];
514 
515         // Process first (potentially short) digit group
516         int firstGroupLen = numDigits % digitsPerInt[radix];
517         if (firstGroupLen == 0)
518             firstGroupLen = digitsPerInt[radix];
519         string group = val.substring(cursor, cursor += firstGroupLen);
520         magnitude[numWords - 1] = to!int(group, radix);
521         if (magnitude[numWords - 1] < 0)
522             throw new NumberFormatException("Illegal digit");
523 
524         // Process remaining digit groups
525         int superRadix = intRadix[radix];
526         int groupVal = 0;
527         while (cursor < len) {
528             group = val.substring(cursor, cursor += digitsPerInt[radix]);
529             groupVal = to!int(group, radix);
530             if (groupVal < 0)
531                 throw new NumberFormatException("Illegal digit");
532             destructiveMulAdd(magnitude, superRadix, groupVal);
533         }
534         // Required for cases where the array was overallocated.
535         mag = trustedStripLeadingZeroInts(magnitude);
536         if (mag.length >= MAX_MAG_LENGTH) {
537             checkRange();
538         }
539     }
540 
541     /*
542      * Constructs a new BigInteger using a char array with radix=10.
543      * Sign is precalculated outside and not allowed in the val. The {@code val}
544      * array is assumed to be unchanged for the duration of the constructor
545      * call.
546      */
547     this(char[] val, int sign, int len) {
548         int cursor = 0, numDigits;
549 
550         // Skip leading zeros and compute number of digits in magnitude
551         while (cursor < len && CharacterHelper.digit(val[cursor], 10) == 0) {
552             cursor++;
553         }
554         if (cursor == len) {
555             _signum = 0;
556             mag = ZERO.mag;
557             return;
558         }
559 
560         numDigits = len - cursor;
561         _signum = sign;
562         // Pre-allocate array of expected size
563         int numWords;
564         if (len < 10) {
565             numWords = 1;
566         } else {
567             long numBits = ((numDigits * bitsPerDigit[10]) >>> 10) + 1;
568             if (numBits + 31 >= (1L << 32)) {
569                 reportOverflow();
570             }
571             numWords = cast(int) (numBits + 31) >>> 5;
572         }
573         int[] magnitude = new int[numWords];
574 
575         // Process first (potentially short) digit group
576         int firstGroupLen = numDigits % digitsPerInt[10];
577         if (firstGroupLen == 0)
578             firstGroupLen = digitsPerInt[10];
579         magnitude[numWords - 1] = parseInt(val, cursor,  cursor += firstGroupLen);
580 
581         // Process remaining digit groups
582         while (cursor < len) {
583             int groupVal = parseInt(val, cursor, cursor += digitsPerInt[10]);
584             destructiveMulAdd(magnitude, intRadix[10], groupVal);
585         }
586         mag = trustedStripLeadingZeroInts(magnitude);
587         if (mag.length >= MAX_MAG_LENGTH) {
588             checkRange();
589         }
590     }
591 
592     // Create an integer with the digits between the two indexes
593     // Assumes start < end. The result may be negative, but it
594     // is to be treated as an unsigned value.
595     private int parseInt(char[] source, int start, int end) {
596         int result = CharacterHelper.digit(source[start++], 10);
597         if (result == -1)
598             throw new NumberFormatException(cast(string)(source));
599 
600         for (int index = start; index < end; index++) {
601             int nextVal = CharacterHelper.digit(source[index], 10);
602             if (nextVal == -1)
603                 throw new NumberFormatException(cast(string)(source));
604             result = 10*result + nextVal;
605         }
606 
607         return result;
608     }
609 
610     // bitsPerDigit in the given radix times 1024
611     // Rounded up to avoid underallocation.
612     private enum long[] bitsPerDigit = [ 0, 0,
613         1024, 1624, 2048, 2378, 2648, 2875, 3072, 3247, 3402, 3543, 3672,
614         3790, 3899, 4001, 4096, 4186, 4271, 4350, 4426, 4498, 4567, 4633,
615         4696, 4756, 4814, 4870, 4923, 4975, 5025, 5074, 5120, 5166, 5210,
616                                            5253, 5295];
617 
618     // Multiply x array times word y in place, and add word z
619     private static void destructiveMulAdd(int[] x, int y, int z) {
620         // Perform the multiplication word by word
621         long ylong = y & LONG_MASK;
622         long zlong = z & LONG_MASK;
623         int len = cast(int)x.length;
624 
625         long product = 0;
626         long carry = 0;
627         for (int i = len-1; i >= 0; i--) {
628             product = ylong * (x[i] & LONG_MASK) + carry;
629             x[i] = cast(int)product;
630             carry = product >>> 32;
631         }
632 
633         // Perform the addition
634         long sum = (x[len-1] & LONG_MASK) + zlong;
635         x[len-1] = cast(int)sum;
636         carry = sum >>> 32;
637         for (int i = len-2; i >= 0; i--) {
638             sum = (x[i] & LONG_MASK) + carry;
639             x[i] = cast(int)sum;
640             carry = sum >>> 32;
641         }
642     }
643 
644     /**
645      * Translates the decimal string representation of a BigInteger into a
646      * BigInteger.  The string representation consists of an optional minus
647      * sign followed by a sequence of one or more decimal digits.  The
648      * character-to-digit mapping is provided by {@code CharacterHelper.digit}.
649      * The string may not contain any extraneous characters (whitespace, for
650      * example).
651      *
652      * @param val decimal string representation of BigInteger.
653      * @throws NumberFormatException {@code val} is not a valid representation
654      *         of a BigInteger.
655      * @see    Character#digit
656      */
657     this(string val) {
658         this(val, 10);
659     }
660 
661     /**
662      * Constructs a randomly generated BigInteger, uniformly distributed over
663      * the range 0 to (2<sup>{@code numBits}</sup> - 1), inclusive.
664      * The uniformity of the distribution assumes that a fair source of random
665      * bits is provided in {@code rnd}.  Note that this constructor always
666      * constructs a non-negative BigInteger.
667      *
668      * @param  numBits maximum bitLength of the new BigInteger.
669      * @param  rnd source of randomness to be used in computing the new
670      *         BigInteger.
671      * @throws IllegalArgumentException {@code numBits} is negative.
672      * @see #bitLength()
673      */
674     this(int numBits, Random* rnd) {
675         this(1, randomBits(numBits, rnd));
676     }
677 
678     private static byte[] randomBits(int numBits, Random* rnd) {
679         if (numBits < 0)
680             throw new IllegalArgumentException("numBits must be non-negative");
681         int numBytes = cast(int)((cast(long)numBits+7)/8); // avoid overflow
682         byte[] buffer = new byte[numBytes];
683 
684         // Generate random bytes and mask out any excess bits
685         if (numBytes > 0) {
686             for(int i=0; i<numBytes; i++) {
687                 buffer[i] = uniform(byte.min, byte.max, rnd);
688             }
689             int excessBits = 8*numBytes - numBits;
690             buffer[0] &= (1 << (8-excessBits)) - 1;
691         }
692         return buffer;
693     }
694 
695     /**
696      * Constructs a randomly generated positive BigInteger that is probably
697      * prime, with the specified bitLength.
698      *
699      * @apiNote It is recommended that the {@link #probablePrime probablePrime}
700      * method be used in preference to this constructor unless there
701      * is a compelling need to specify a certainty.
702      *
703      * @param  bitLength bitLength of the returned BigInteger.
704      * @param  certainty a measure of the uncertainty that the caller is
705      *         willing to tolerate.  The probability that the new BigInteger
706      *         represents a prime number will exceed
707      *         (1 - 1/2<sup>{@code certainty}</sup>).  The execution time of
708      *         this constructor is proportional to the value of this parameter.
709      * @param  rnd source of random bits used to select candidates to be
710      *         tested for primality.
711      * @throws ArithmeticException {@code bitLength < 2} or {@code bitLength} is too large.
712      * @see    #bitLength()
713      */
714     this(int bitLength, int certainty, Random* rnd) {
715         BigInteger prime;
716 
717         if (bitLength < 2)
718             throw new ArithmeticException("bitLength < 2");
719         prime = (bitLength < SMALL_PRIME_THRESHOLD
720                                 ? smallPrime(bitLength, certainty, rnd)
721                                 : largePrime(bitLength, certainty, rnd));
722         _signum = 1;
723         mag = prime.mag;
724     }
725 
726     // Minimum size in bits that the requested prime number has
727     // before we use the large prime number generating algorithms.
728     // The cutoff of 95 was chosen empirically for best performance.
729     private enum int SMALL_PRIME_THRESHOLD = 95;
730 
731     // Certainty required to meet the spec of probablePrime
732     private enum int DEFAULT_PRIME_CERTAINTY = 100;
733 
734     /**
735      * Returns a positive BigInteger that is probably prime, with the
736      * specified bitLength. The probability that a BigInteger returned
737      * by this method is composite does not exceed 2<sup>-100</sup>.
738      *
739      * @param  bitLength bitLength of the returned BigInteger.
740      * @param  rnd source of random bits used to select candidates to be
741      *         tested for primality.
742      * @return a BigInteger of {@code bitLength} bits that is probably prime
743      * @throws ArithmeticException {@code bitLength < 2} or {@code bitLength} is too large.
744      * @see    #bitLength()
745      */
746     // static BigInteger probablePrime(int bitLength, Random* rnd) {
747     //     if (bitLength < 2)
748     //         throw new ArithmeticException("bitLength < 2");
749 
750     //     return (bitLength < SMALL_PRIME_THRESHOLD ?
751     //             smallPrime(bitLength, DEFAULT_PRIME_CERTAINTY, rnd) :
752     //             largePrime(bitLength, DEFAULT_PRIME_CERTAINTY, rnd));
753     // }
754 
755     /**
756      * Find a random number of the specified bitLength that is probably prime.
757      * This method is used for smaller primes, its performance degrades on
758      * larger bitlengths.
759      *
760      * This method assumes bitLength > 1.
761      */
762     private static BigInteger smallPrime(int bitLength, int certainty, Random* rnd) {
763         int magLen = (bitLength + 31) >>> 5;
764         int[] temp = new int[magLen];
765         int highBit = 1 << ((bitLength+31) & 0x1f);  // High bit of high int
766         int highMask = (highBit << 1) - 1;  // Bits to keep in high int
767 
768         while (true) {
769             // Construct a candidate
770             for (int i=0; i < magLen; i++)
771                 temp[i] = uniform(int.min, int.max, rnd);
772             temp[0] = (temp[0] & highMask) | highBit;  // Ensure exact length
773             if (bitLength > 2)
774                 temp[magLen-1] |= 1;  // Make odd if bitlen > 2
775 
776             BigInteger p = new BigInteger(temp, 1);
777 
778             // Do cheap "pre-test" if applicable
779             if (bitLength > 6) {
780                 long r = p.remainder(SMALL_PRIME_PRODUCT).longValue();
781                 if ((r%3==0)  || (r%5==0)  || (r%7==0)  || (r%11==0) ||
782                     (r%13==0) || (r%17==0) || (r%19==0) || (r%23==0) ||
783                     (r%29==0) || (r%31==0) || (r%37==0) || (r%41==0))
784                     continue; // Candidate is composite; try another
785             }
786 
787             // All candidates of bitLength 2 and 3 are prime by this point
788             if (bitLength < 4)
789                 return p;
790 
791             // Do expensive test if we survive pre-test (or it's inapplicable)
792             if (p.primeToCertainty(certainty, rnd))
793                 return p;
794         }
795     }
796 
797     private __gshared BigInteger SMALL_PRIME_PRODUCT;
798 
799     shared static this() {
800         SMALL_PRIME_PRODUCT = valueOf(3L*5*7*11*13*17*19*23*29*31*37*41);
801     }
802 
803     /**
804      * Find a random number of the specified bitLength that is probably prime.
805      * This method is more appropriate for larger bitlengths since it uses
806      * a sieve to eliminate most composites before using a more expensive
807      * test.
808      */
809     private static BigInteger largePrime(int bitLength, int certainty, Random* rnd) {
810         BigInteger p;
811         p = new BigInteger(bitLength, rnd).setBit(bitLength-1);
812         p.mag[$-1] &= 0xfffffffe;
813 
814         // Use a sieve length likely to contain the next prime number
815         int searchLen = getPrimeSearchLen(bitLength);
816         BitSieve searchSieve = new BitSieve(p, searchLen);
817         BigInteger candidate = searchSieve.retrieve(p, certainty, rnd);
818 
819         while ((candidate is null) || (candidate.bitLength() != bitLength)) {
820             p = p.add(BigInteger.valueOf(2*searchLen));
821             if (p.bitLength() != bitLength)
822                 p = new BigInteger(bitLength, rnd).setBit(bitLength-1);
823             p.mag[$-1] &= 0xfffffffe;
824             searchSieve = new BitSieve(p, searchLen);
825             candidate = searchSieve.retrieve(p, certainty, rnd);
826         }
827         return candidate;
828     }
829 
830    /**
831     * Returns the first integer greater than this {@code BigInteger} that
832     * is probably prime.  The probability that the number returned by this
833     * method is composite does not exceed 2<sup>-100</sup>. This method will
834     * never skip over a prime when searching: if it returns {@code p}, there
835     * is no prime {@code q} such that {@code this < q < p}.
836     *
837     * @return the first integer greater than this {@code BigInteger} that
838     *         is probably prime.
839     * @throws ArithmeticException {@code this < 0} or {@code this} is too large.
840     */
841     BigInteger nextProbablePrime() {
842         if (this._signum < 0)
843             throw new ArithmeticException("start < 0: " ~ this.toString());
844 
845         // Handle trivial cases
846         if ((this._signum == 0) || this.equals(ONE))
847             return TWO;
848 
849         BigInteger result = this.add(ONE);
850 
851         // Fastpath for small numbers
852         if (result.bitLength() < SMALL_PRIME_THRESHOLD) {
853 
854             // Ensure an odd number
855             if (!result.testBit(0))
856                 result = result.add(ONE);
857 
858             while (true) {
859                 // Do cheap "pre-test" if applicable
860                 if (result.bitLength() > 6) {
861                     long r = result.remainder(SMALL_PRIME_PRODUCT).longValue();
862                     if ((r%3==0)  || (r%5==0)  || (r%7==0)  || (r%11==0) ||
863                         (r%13==0) || (r%17==0) || (r%19==0) || (r%23==0) ||
864                         (r%29==0) || (r%31==0) || (r%37==0) || (r%41==0)) {
865                         result = result.add(TWO);
866                         continue; // Candidate is composite; try another
867                     }
868                 }
869 
870                 // All candidates of bitLength 2 and 3 are prime by this point
871                 if (result.bitLength() < 4)
872                     return result;
873 
874                 // The expensive test
875                 if (result.primeToCertainty(DEFAULT_PRIME_CERTAINTY, null))
876                     return result;
877 
878                 result = result.add(TWO);
879             }
880         }
881 
882         // Start at previous even number
883         if (result.testBit(0))
884             result = result.subtract(ONE);
885 
886         // Looking for the next large prime
887         int searchLen = getPrimeSearchLen(result.bitLength());
888 
889         while (true) {
890            BitSieve searchSieve = new BitSieve(result, searchLen);
891            BigInteger candidate = searchSieve.retrieve(result,
892                                                  DEFAULT_PRIME_CERTAINTY, null);
893            if (candidate !is null)
894                return candidate;
895            result = result.add(BigInteger.valueOf(2 * searchLen));
896         }
897     }
898 
899     private static int getPrimeSearchLen(int bitLength) {
900         if (bitLength > PRIME_SEARCH_BIT_LENGTH_LIMIT + 1) {
901             throw new ArithmeticException("Prime search implementation restriction on bitLength");
902         }
903         return bitLength / 20 * 64;
904     }
905 
906     /**
907      * Returns {@code true} if this BigInteger is probably prime,
908      * {@code false} if it's definitely composite.
909      *
910      * This method assumes bitLength > 2.
911      *
912      * @param  certainty a measure of the uncertainty that the caller is
913      *         willing to tolerate: if the call returns {@code true}
914      *         the probability that this BigInteger is prime exceeds
915      *         {@code (1 - 1/2<sup>certainty</sup>)}.  The execution time of
916      *         this method is proportional to the value of this parameter.
917      * @return {@code true} if this BigInteger is probably prime,
918      *         {@code false} if it's definitely composite.
919      */
920     bool primeToCertainty(int certainty, Random* random) {
921         int rounds = 0;
922         int n = (std.algorithm.min(certainty, int.max-1)+1)/2;
923 
924         // The relationship between the certainty and the number of rounds
925         // we perform is given in the draft standard ANSI X9.80, "PRIME
926         // NUMBER GENERATION, PRIMALITY TESTING, AND PRIMALITY CERTIFICATES".
927         int sizeInBits = this.bitLength();
928         if (sizeInBits < 100) {
929             rounds = 50;
930             rounds = n < rounds ? n : rounds;
931             return passesMillerRabin(rounds, random);
932         }
933 
934         if (sizeInBits < 256) {
935             rounds = 27;
936         } else if (sizeInBits < 512) {
937             rounds = 15;
938         } else if (sizeInBits < 768) {
939             rounds = 8;
940         } else if (sizeInBits < 1024) {
941             rounds = 4;
942         } else {
943             rounds = 2;
944         }
945         rounds = n < rounds ? n : rounds;
946 
947         return passesMillerRabin(rounds, random) && passesLucasLehmer();
948     }
949 
950     /**
951      * Returns true iff this BigInteger is a Lucas-Lehmer probable prime.
952      *
953      * The following assumptions are made:
954      * This BigInteger is a positive, odd number.
955      */
956     private bool passesLucasLehmer() {
957         BigInteger thisPlusOne = this.add(ONE);
958 
959         // Step 1
960         int d = 5;
961         while (jacobiSymbol(d, this) != -1) {
962             // 5, -7, 9, -11, ...
963             d = (d < 0) ? std.math.abs(d)+2 : -(d+2);
964         }
965 
966         // Step 2
967         BigInteger u = lucasLehmerSequence(d, thisPlusOne, this);
968 
969         // Step 3
970         return u.mod(this).equals(ZERO);
971     }
972 
973     /**
974      * Computes Jacobi(p,n).
975      * Assumes n positive, odd, n>=3.
976      */
977     private static int jacobiSymbol(int p, BigInteger n) {
978         if (p == 0)
979             return 0;
980 
981         // Algorithm and comments adapted from Colin Plumb's C library.
982         int j = 1;
983         int u = n.mag[$-1];
984 
985         // Make p positive
986         if (p < 0) {
987             p = -p;
988             int n8 = u & 7;
989             if ((n8 == 3) || (n8 == 7))
990                 j = -j; // 3 (011) or 7 (111) mod 8
991         }
992 
993         // Get rid of factors of 2 in p
994         while ((p & 3) == 0)
995             p >>= 2;
996         if ((p & 1) == 0) {
997             p >>= 1;
998             if (((u ^ (u>>1)) & 2) != 0)
999                 j = -j; // 3 (011) or 5 (101) mod 8
1000         }
1001         if (p == 1)
1002             return j;
1003         // Then, apply quadratic reciprocity
1004         if ((p & u & 2) != 0)   // p = u = 3 (mod 4)?
1005             j = -j;
1006         // And reduce u mod p
1007         u = n.mod(BigInteger.valueOf(p)).intValue();
1008 
1009         // Now compute Jacobi(u,p), u < p
1010         while (u != 0) {
1011             while ((u & 3) == 0)
1012                 u >>= 2;
1013             if ((u & 1) == 0) {
1014                 u >>= 1;
1015                 if (((p ^ (p>>1)) & 2) != 0)
1016                     j = -j;     // 3 (011) or 5 (101) mod 8
1017             }
1018             if (u == 1)
1019                 return j;
1020             // Now both u and p are odd, so use quadratic reciprocity
1021             assert (u < p);
1022             int t = u; u = p; p = t;
1023             if ((u & p & 2) != 0) // u = p = 3 (mod 4)?
1024                 j = -j;
1025             // Now u >= p, so it can be reduced
1026             u %= p;
1027         }
1028         return 0;
1029     }
1030 
1031     private static BigInteger lucasLehmerSequence(int z, BigInteger k, BigInteger n) {
1032         BigInteger d = BigInteger.valueOf(z);
1033         BigInteger u = ONE; BigInteger u2;
1034         BigInteger v = ONE; BigInteger v2;
1035 
1036         for (int i=k.bitLength()-2; i >= 0; i--) {
1037             u2 = u.multiply(v).mod(n);
1038 
1039             v2 = v.square().add(d.multiply(u.square())).mod(n);
1040             if (v2.testBit(0))
1041                 v2 = v2.subtract(n);
1042 
1043             v2 = v2.shiftRight(1);
1044 
1045             u = u2; v = v2;
1046             if (k.testBit(i)) {
1047                 u2 = u.add(v).mod(n);
1048                 if (u2.testBit(0))
1049                     u2 = u2.subtract(n);
1050 
1051                 u2 = u2.shiftRight(1);
1052                 v2 = v.add(d.multiply(u)).mod(n);
1053                 if (v2.testBit(0))
1054                     v2 = v2.subtract(n);
1055                 v2 = v2.shiftRight(1);
1056 
1057                 u = u2; v = v2;
1058             }
1059         }
1060         return u;
1061     }
1062 
1063     /**
1064      * Returns true iff this BigInteger passes the specified number of
1065      * Miller-Rabin tests. This test is taken from the DSA spec (NIST FIPS
1066      * 186-2).
1067      *
1068      * The following assumptions are made:
1069      * This BigInteger is a positive, odd number greater than 2.
1070      * iterations<=50.
1071      */
1072     private bool passesMillerRabin(int iterations, Random* rnd) {
1073         // Find a and m such that m is odd and this == 1 + 2**a * m
1074         BigInteger thisMinusOne = this.subtract(ONE);
1075         BigInteger m = thisMinusOne;
1076         int a = m.getLowestSetBit();
1077         m = m.shiftRight(a);
1078 
1079         // Do the tests
1080         // if (rnd is null) {
1081         //     rnd = ThreadLocalRandom.current();
1082         // }
1083         for (int i=0; i < iterations; i++) {
1084             // Generate a uniform random on (1, this)
1085             BigInteger b;
1086             do {
1087                 b = new BigInteger(this.bitLength(), rnd);
1088             } while (b.compareTo(ONE) <= 0 || b.compareTo(this) >= 0);
1089 
1090             int j = 0;
1091             BigInteger z = b.modPow(m, this);
1092             while (!((j == 0 && z.equals(ONE)) || z.equals(thisMinusOne))) {
1093                 if (j > 0 && z.equals(ONE) || ++j == a)
1094                     return false;
1095                 z = z.modPow(TWO, this);
1096             }
1097         }
1098         return true;
1099     }
1100 
1101     /**
1102      * This internal constructor differs from its cousin
1103      * with the arguments reversed in two ways: it assumes that its
1104      * arguments are correct, and it doesn't copy the magnitude array.
1105      */
1106     this(int[] magnitude, int signum) {
1107         this._signum = (magnitude.length == 0 ? 0 : signum);
1108         this.mag = magnitude;
1109         if (mag.length >= MAX_MAG_LENGTH) {
1110             checkRange();
1111         }
1112     }
1113 
1114     /**
1115      * This private constructor is for internal use and assumes that its
1116      * arguments are correct.  The {@code magnitude} array is assumed to be
1117      * unchanged for the duration of the constructor call.
1118      */
1119     private this(byte[] magnitude, int signum) {
1120         this._signum = (magnitude.length == 0 ? 0 : signum);
1121         this.mag = stripLeadingZeroBytes(magnitude, 0, cast(int)magnitude.length);
1122         if (mag.length >= MAX_MAG_LENGTH) {
1123             checkRange();
1124         }
1125     }
1126 
1127     /**
1128      * Throws an {@code ArithmeticException} if the {@code BigInteger} would be
1129      * out of the supported range.
1130      *
1131      * @throws ArithmeticException if {@code this} exceeds the supported range.
1132      */
1133     private void checkRange() {
1134         if (mag.length > MAX_MAG_LENGTH || mag.length == MAX_MAG_LENGTH && mag[0] < 0) {
1135             reportOverflow();
1136         }
1137     }
1138 
1139     private static void reportOverflow() {
1140         throw new ArithmeticException("BigInteger would overflow supported range");
1141     }
1142 
1143     //Static Factory Methods
1144 
1145     /**
1146      * Returns a BigInteger whose value is equal to that of the
1147      * specified {@code long}.
1148      *
1149      * @apiNote This static factory method is provided in preference
1150      * to a ({@code long}) constructor because it allows for reuse of
1151      * frequently used BigIntegers.
1152      *
1153      * @param  val value of the BigInteger to return.
1154      * @return a BigInteger with the specified value.
1155      */
1156     static BigInteger valueOf(long val) {
1157         // If -MAX_CONSTANT < val < MAX_CONSTANT, return stashed constant
1158         if (val == 0)
1159             return ZERO;
1160         if (val > 0 && val <= MAX_CONSTANT)
1161             return posConst[cast(int) val];
1162         else if (val < 0 && val >= -MAX_CONSTANT)
1163             return negConst[cast(int) -val];
1164 
1165         return new BigInteger(val);
1166     }
1167 
1168     /**
1169      * Constructs a BigInteger with the specified value, which may not be zero.
1170      */
1171     private this(long val) {
1172         if (val < 0) {
1173             val = -val;
1174             _signum = -1;
1175         } else {
1176             _signum = 1;
1177         }
1178 
1179         int highWord = cast(int)(val >>> 32);
1180         if (highWord == 0) {
1181             mag = new int[1];
1182             mag[0] = cast(int)val;
1183         } else {
1184             mag = new int[2];
1185             mag[0] = highWord;
1186             mag[1] = cast(int)val;
1187         }
1188     }
1189 
1190     /**
1191      * Returns a BigInteger with the given two's complement representation.
1192      * Assumes that the input array will not be modified (the returned
1193      * BigInteger will reference the input array if feasible).
1194      */
1195     private static BigInteger valueOf(int[] val) {
1196         return (val[0] > 0 ? new BigInteger(val, 1) : new BigInteger(val));
1197     }
1198 
1199     // Constants
1200 
1201     /**
1202      * Initialize static constant array when class is loaded.
1203      */
1204     private enum int MAX_CONSTANT = 16;
1205     private __gshared BigInteger[] posConst;
1206     private __gshared BigInteger[] negConst;
1207 
1208     /**
1209      * The cache of powers of each radix.  This allows us to not have to
1210      * recalculate powers of radix^(2^n) more than once.  This speeds
1211      * Schoenhage recursive base conversion significantly.
1212      */
1213     private __gshared BigInteger[][] powerCache;
1214 
1215     /** The cache of logarithms of radices for base conversion. */
1216     private __gshared double[] logCache;
1217 
1218     /** The natural log of 2.  This is used in computing cache indices. */
1219     private __gshared immutable double LOG_TWO;
1220 
1221     shared static this() {
1222         LOG_TWO = std.math.log(2.0);
1223         posConst = new BigInteger[MAX_CONSTANT+1];
1224         negConst = new BigInteger[MAX_CONSTANT+1];
1225 
1226         for (int i = 1; i <= MAX_CONSTANT; i++) {
1227             int[] magnitude = [i];
1228             posConst[i] = new BigInteger(magnitude,  1);
1229             negConst[i] = new BigInteger(magnitude, -1);
1230         }
1231 
1232         /*
1233          * Initialize the cache of radix^(2^x) values used for base conversion
1234          * with just the very first value.  Additional values will be created
1235          * on demand.
1236          */
1237         powerCache = new BigInteger[][Char.MAX_RADIX+1];
1238         logCache = new double[Char.MAX_RADIX+1];
1239 
1240         for (int i=Char.MIN_RADIX; i <= Char.MAX_RADIX; i++) {
1241             powerCache[i] = [BigInteger.valueOf(i)];
1242             logCache[i] = std.math.log(i);
1243         }
1244     }
1245 
1246     /**
1247      * The BigInteger constant zero.
1248      *
1249      */
1250     __gshared static BigInteger ZERO;
1251 
1252     /**
1253      * The BigInteger constant one.
1254      *
1255      */
1256     __gshared static BigInteger ONE;
1257 
1258     /**
1259      * The BigInteger constant two.
1260      *
1261      */
1262     __gshared static BigInteger TWO;
1263 
1264     /**
1265      * The BigInteger constant -1.  (Not exported.)
1266      */
1267     private __gshared static BigInteger NEGATIVE_ONE;
1268 
1269     /**
1270      * The BigInteger constant ten.
1271      *
1272      */
1273     __gshared static BigInteger TEN;
1274 
1275     shared static this() {
1276         ZERO = new BigInteger(cast(byte[])[], 0);
1277         ONE = valueOf(1);
1278         TWO = valueOf(2);
1279         NEGATIVE_ONE = valueOf(-1);
1280         TEN = valueOf(10);
1281     }
1282 
1283     // Arithmetic Operations
1284 
1285     /**
1286      * Returns a BigInteger whose value is {@code (this + val)}.
1287      *
1288      * @param  val value to be added to this BigInteger.
1289      * @return {@code this + val}
1290      */
1291     BigInteger add(BigInteger val) {
1292         if (val._signum == 0)
1293             return this;
1294         if (_signum == 0)
1295             return val;
1296         if (val._signum == signum)
1297             return new BigInteger(add(mag, val.mag), signum);
1298 
1299         int cmp = compareMagnitude(val);
1300         if (cmp == 0)
1301             return ZERO;
1302         int[] resultMag = (cmp > 0 ? subtract(mag, val.mag)
1303                            : subtract(val.mag, mag));
1304         resultMag = trustedStripLeadingZeroInts(resultMag);
1305 
1306         return new BigInteger(resultMag, cmp == signum ? 1 : -1);
1307     }
1308 
1309     /**
1310      * Package private methods used by BigDecimal code to add a BigInteger
1311      * with a long. Assumes val is not equal to INFLATED.
1312      */
1313     BigInteger add(long val) {
1314         if (val == 0)
1315             return this;
1316         if (_signum == 0)
1317             return valueOf(val);
1318         if (Long.signum(val) == signum)
1319             return new BigInteger(add(mag, std.math.abs(val)), signum);
1320         int cmp = compareMagnitude(val);
1321         if (cmp == 0)
1322             return ZERO;
1323         int[] resultMag = (cmp > 0 ? subtract(mag, std.math.abs(val)) : subtract(std.math.abs(val), mag));
1324         resultMag = trustedStripLeadingZeroInts(resultMag);
1325         return new BigInteger(resultMag, cmp == signum ? 1 : -1);
1326     }
1327 
1328     /**
1329      * Adds the contents of the int array x and long value val. This
1330      * method allocates a new int array to hold the answer and returns
1331      * a reference to that array.  Assumes x.length &gt; 0 and val is
1332      * non-negative
1333      */
1334     private static int[] add(int[] x, long val) {
1335         int[] y;
1336         long sum = 0;
1337         int xIndex = cast(int)x.length;
1338         int[] result;
1339         int highWord = cast(int)(val >>> 32);
1340         if (highWord == 0) {
1341             result = new int[xIndex];
1342             sum = (x[--xIndex] & LONG_MASK) + val;
1343             result[xIndex] = cast(int)sum;
1344         } else {
1345             if (xIndex == 1) {
1346                 result = new int[2];
1347                 sum = val  + (x[0] & LONG_MASK);
1348                 result[1] = cast(int)sum;
1349                 result[0] = cast(int)(sum >>> 32);
1350                 return result;
1351             } else {
1352                 result = new int[xIndex];
1353                 sum = (x[--xIndex] & LONG_MASK) + (val & LONG_MASK);
1354                 result[xIndex] = cast(int)sum;
1355                 sum = (x[--xIndex] & LONG_MASK) + (highWord & LONG_MASK) + (sum >>> 32);
1356                 result[xIndex] = cast(int)sum;
1357             }
1358         }
1359         // Copy remainder of longer number while carry propagation is required
1360         bool carry = (sum >>> 32 != 0);
1361         while (xIndex > 0 && carry)
1362             carry = ((result[--xIndex] = x[xIndex] + 1) == 0);
1363         // Copy remainder of longer number
1364         while (xIndex > 0)
1365             result[--xIndex] = x[xIndex];
1366         // Grow result if necessary
1367         if (carry) {
1368             size_t len = cast(int)result.length;
1369             int[] bigger = new int[len + 1];
1370             // System.arraycopy(result, 0, bigger, 1, result.length);
1371             bigger[1 .. len+1] = result[0..$];
1372             bigger[0] = 0x01;
1373             return bigger;
1374         }
1375         return result;
1376     }
1377 
1378     /**
1379      * Adds the contents of the int arrays x and y. This method allocates
1380      * a new int array to hold the answer and returns a reference to that
1381      * array.
1382      */
1383     private static int[] add(int[] x, int[] y) {
1384         // If x is shorter, swap the two arrays
1385         if (x.length < y.length) {
1386             int[] tmp = x;
1387             x = y;
1388             y = tmp;
1389         }
1390 
1391         int xIndex = cast(int)x.length;
1392         int yIndex = cast(int)y.length;
1393         int[] result = new int[xIndex];
1394         long sum = 0;
1395         if (yIndex == 1) {
1396             sum = (x[--xIndex] & LONG_MASK) + (y[0] & LONG_MASK) ;
1397             result[xIndex] = cast(int)sum;
1398         } else {
1399             // Add common parts of both numbers
1400             while (yIndex > 0) {
1401                 sum = (x[--xIndex] & LONG_MASK) +
1402                       (y[--yIndex] & LONG_MASK) + (sum >>> 32);
1403                 result[xIndex] = cast(int)sum;
1404             }
1405         }
1406         // Copy remainder of longer number while carry propagation is required
1407         bool carry = (sum >>> 32 != 0);
1408         while (xIndex > 0 && carry)
1409             carry = ((result[--xIndex] = x[xIndex] + 1) == 0);
1410 
1411         // Copy remainder of longer number
1412         while (xIndex > 0)
1413             result[--xIndex] = x[xIndex];
1414 
1415         // Grow result if necessary
1416         if (carry) {
1417             size_t len = cast(int)result.length;
1418             int[] bigger = new int[len + 1];
1419             // System.arraycopy(result, 0, bigger, 1, result.length);
1420             bigger[1 .. 1+len] = result[0 .. $];
1421             bigger[0] = 0x01;
1422             return bigger;
1423         }
1424         return result;
1425     }
1426 
1427     private static int[] subtract(long val, int[] little) {
1428         int highWord = cast(int)(val >>> 32);
1429         if (highWord == 0) {
1430             int[] result = new int[1];
1431             result[0] = cast(int)(val - (little[0] & LONG_MASK));
1432             return result;
1433         } else {
1434             int[] result = new int[2];
1435             if (little.length == 1) {
1436                 long difference = (cast(int)val & LONG_MASK) - (little[0] & LONG_MASK);
1437                 result[1] = cast(int)difference;
1438                 // Subtract remainder of longer number while borrow propagates
1439                 bool borrow = (difference >> 32 != 0);
1440                 if (borrow) {
1441                     result[0] = highWord - 1;
1442                 } else {        // Copy remainder of longer number
1443                     result[0] = highWord;
1444                 }
1445                 return result;
1446             } else { // little.length == 2
1447                 long difference = (cast(int)val & LONG_MASK) - (little[1] & LONG_MASK);
1448                 result[1] = cast(int)difference;
1449                 difference = (highWord & LONG_MASK) - (little[0] & LONG_MASK) + (difference >> 32);
1450                 result[0] = cast(int)difference;
1451                 return result;
1452             }
1453         }
1454     }
1455 
1456     /**
1457      * Subtracts the contents of the second argument (val) from the
1458      * first (big).  The first int array (big) must represent a larger number
1459      * than the second.  This method allocates the space necessary to hold the
1460      * answer.
1461      * assumes val &gt;= 0
1462      */
1463     private static int[] subtract(int[] big, long val) {
1464         int highWord = cast(int)(val >>> 32);
1465         int bigIndex = cast(int)big.length;
1466         int[] result = new int[bigIndex];
1467         long difference = 0;
1468 
1469         if (highWord == 0) {
1470             difference = (big[--bigIndex] & LONG_MASK) - val;
1471             result[bigIndex] = cast(int)difference;
1472         } else {
1473             difference = (big[--bigIndex] & LONG_MASK) - (val & LONG_MASK);
1474             result[bigIndex] = cast(int)difference;
1475             difference = (big[--bigIndex] & LONG_MASK) - (highWord & LONG_MASK) + (difference >> 32);
1476             result[bigIndex] = cast(int)difference;
1477         }
1478 
1479         // Subtract remainder of longer number while borrow propagates
1480         bool borrow = (difference >> 32 != 0);
1481         while (bigIndex > 0 && borrow)
1482             borrow = ((result[--bigIndex] = big[bigIndex] - 1) == -1);
1483 
1484         // Copy remainder of longer number
1485         while (bigIndex > 0)
1486             result[--bigIndex] = big[bigIndex];
1487 
1488         return result;
1489     }
1490 
1491     /**
1492      * Returns a BigInteger whose value is {@code (this - val)}.
1493      *
1494      * @param  val value to be subtracted from this BigInteger.
1495      * @return {@code this - val}
1496      */
1497     BigInteger subtract(BigInteger val) {
1498         if (val._signum == 0)
1499             return this;
1500         if (_signum == 0)
1501             return val.negate();
1502         if (val.signum != signum)
1503             return new BigInteger(add(mag, val.mag), signum);
1504 
1505         int cmp = compareMagnitude(val);
1506         if (cmp == 0)
1507             return ZERO;
1508         int[] resultMag = (cmp > 0 ? subtract(mag, val.mag)
1509                            : subtract(val.mag, mag));
1510         resultMag = trustedStripLeadingZeroInts(resultMag);
1511         return new BigInteger(resultMag, cmp == signum ? 1 : -1);
1512     }
1513 
1514     /**
1515      * Subtracts the contents of the second int arrays (little) from the
1516      * first (big).  The first int array (big) must represent a larger number
1517      * than the second.  This method allocates the space necessary to hold the
1518      * answer.
1519      */
1520     private static int[] subtract(int[] big, int[] little) {
1521         int bigIndex = cast(int)big.length;
1522         int[] result = new int[bigIndex];
1523         int littleIndex = cast(int)little.length;
1524         long difference = 0;
1525 
1526         // Subtract common parts of both numbers
1527         while (littleIndex > 0) {
1528             difference = (big[--bigIndex] & LONG_MASK) -
1529                          (little[--littleIndex] & LONG_MASK) +
1530                          (difference >> 32);
1531             result[bigIndex] = cast(int)difference;
1532         }
1533 
1534         // Subtract remainder of longer number while borrow propagates
1535         bool borrow = (difference >> 32 != 0);
1536         while (bigIndex > 0 && borrow)
1537             borrow = ((result[--bigIndex] = big[bigIndex] - 1) == -1);
1538 
1539         // Copy remainder of longer number
1540         while (bigIndex > 0)
1541             result[--bigIndex] = big[bigIndex];
1542 
1543         return result;
1544     }
1545 
1546     /**
1547      * Returns a BigInteger whose value is {@code (this * val)}.
1548      *
1549      * @implNote An implementation may offer better algorithmic
1550      * performance when {@code val == this}.
1551      *
1552      * @param  val value to be multiplied by this BigInteger.
1553      * @return {@code this * val}
1554      */
1555     BigInteger multiply(BigInteger val) {
1556         if (val._signum == 0 || _signum == 0)
1557             return ZERO;
1558 
1559         int xlen = cast(int)mag.length;
1560 
1561         if (val == this && xlen > MULTIPLY_SQUARE_THRESHOLD) {
1562             return square();
1563         }
1564 
1565         int ylen = cast(int)val.mag.length;
1566 
1567         if ((xlen < KARATSUBA_THRESHOLD) || (ylen < KARATSUBA_THRESHOLD)) {
1568             int resultSign = _signum == val.signum ? 1 : -1;
1569             if (val.mag.length == 1) {
1570                 return multiplyByInt(mag,val.mag[0], resultSign);
1571             }
1572             if (mag.length == 1) {
1573                 return multiplyByInt(val.mag,mag[0], resultSign);
1574             }
1575             int[] result = multiplyToLen(mag, xlen,
1576                                          val.mag, ylen, null);
1577             result = trustedStripLeadingZeroInts(result);
1578             return new BigInteger(result, resultSign);
1579         } else {
1580             if ((xlen < TOOM_COOK_THRESHOLD) && (ylen < TOOM_COOK_THRESHOLD)) {
1581                 return multiplyKaratsuba(this, val);
1582             } else {
1583                 return multiplyToomCook3(this, val);
1584             }
1585         }
1586     }
1587 
1588     private static BigInteger multiplyByInt(int[] x, int y, int sign) {
1589         if (Integer.bitCount(y) == 1) {
1590             return new BigInteger(shiftLeft(x, Integer.numberOfTrailingZeros(y)), sign);
1591         }
1592         int xlen = cast(int)x.length;
1593         int[] rmag =  new int[xlen + 1];
1594         long carry = 0;
1595         long yl = y & LONG_MASK;
1596         int rstart = cast(int)rmag.length - 1;
1597         for (int i = xlen - 1; i >= 0; i--) {
1598             long product = (x[i] & LONG_MASK) * yl + carry;
1599             rmag[rstart--] = cast(int)product;
1600             carry = product >>> 32;
1601         }
1602         if (carry == 0L) {
1603             rmag = rmag[1 .. $]; // java.util.Arrays.copyOfRange(rmag, 1, rmag.length);
1604         } else {
1605             rmag[rstart] = cast(int)carry;
1606         }
1607         return new BigInteger(rmag, sign);
1608     }
1609 
1610     /**
1611      * Package private methods used by BigDecimal code to multiply a BigInteger
1612      * with a long. Assumes v is not equal to INFLATED.
1613      */
1614     BigInteger multiply(long v) {
1615         if (v == 0 || _signum == 0)
1616           return ZERO;
1617         if (v == long.min)
1618             return multiply(BigInteger.valueOf(v));
1619         int rsign = (v > 0 ? signum : -signum);
1620         if (v < 0)
1621             v = -v;
1622         long dh = v >>> 32;      // higher order bits
1623         long dl = v & LONG_MASK; // lower order bits
1624 
1625         int xlen = cast(int)mag.length;
1626         int[] value = mag;
1627         int[] rmag = (dh == 0L) ? (new int[xlen + 1]) : (new int[xlen + 2]);
1628         long carry = 0;
1629         int rstart = cast(int)rmag.length - 1;
1630         for (int i = xlen - 1; i >= 0; i--) {
1631             long product = (value[i] & LONG_MASK) * dl + carry;
1632             rmag[rstart--] = cast(int)product;
1633             carry = product >>> 32;
1634         }
1635         rmag[rstart] = cast(int)carry;
1636         if (dh != 0L) {
1637             carry = 0;
1638             rstart = cast(int)rmag.length - 2;
1639             for (int i = xlen - 1; i >= 0; i--) {
1640                 long product = (value[i] & LONG_MASK) * dh +
1641                     (rmag[rstart] & LONG_MASK) + carry;
1642                 rmag[rstart--] = cast(int)product;
1643                 carry = product >>> 32;
1644             }
1645             rmag[0] = cast(int)carry;
1646         }
1647         if (carry == 0L)
1648             rmag = rmag[1 .. $]; //java.util.Arrays.copyOfRange(rmag, 1, rmag.length);
1649         return new BigInteger(rmag, rsign);
1650     }
1651 
1652     /**
1653      * Multiplies int arrays x and y to the specified lengths and places
1654      * the result into z. There will be no leading zeros in the resultant array.
1655      */
1656     private static int[] multiplyToLen(int[] x, int xlen, int[] y, int ylen, int[] z) {
1657         multiplyToLenCheck(x, xlen);
1658         multiplyToLenCheck(y, ylen);
1659         return implMultiplyToLen(x, xlen, y, ylen, z);
1660     }
1661 
1662     
1663     private static int[] implMultiplyToLen(int[] x, int xlen, int[] y, int ylen, int[] z) {
1664         int xstart = xlen - 1;
1665         int ystart = ylen - 1;
1666 
1667         if (z is null || z.length < (xlen+ ylen))
1668             z = new int[xlen+ylen];
1669 
1670         long carry = 0;
1671         for (int j=ystart, k=ystart+1+xstart; j >= 0; j--, k--) {
1672             long product = (y[j] & LONG_MASK) *
1673                            (x[xstart] & LONG_MASK) + carry;
1674             z[k] = cast(int)product;
1675             carry = product >>> 32;
1676         }
1677         z[xstart] = cast(int)carry;
1678 
1679         for (int i = xstart-1; i >= 0; i--) {
1680             carry = 0;
1681             for (int j=ystart, k=ystart+1+i; j >= 0; j--, k--) {
1682                 long product = (y[j] & LONG_MASK) *
1683                                (x[i] & LONG_MASK) +
1684                                (z[k] & LONG_MASK) + carry;
1685                 z[k] = cast(int)product;
1686                 carry = product >>> 32;
1687             }
1688             z[i] = cast(int)carry;
1689         }
1690         return z;
1691     }
1692 
1693     private static void multiplyToLenCheck(int[] array, int length) {
1694         if (length <= 0) {
1695             return;  // not an error because multiplyToLen won't execute if len <= 0
1696         }
1697 
1698         assert(array !is null);
1699 
1700         if (length > array.length) {
1701             throw new ArrayIndexOutOfBoundsException(length - 1);
1702         }
1703     }
1704 
1705     /**
1706      * Multiplies two BigIntegers using the Karatsuba multiplication
1707      * algorithm.  This is a recursive divide-and-conquer algorithm which is
1708      * more efficient for large numbers than what is commonly called the
1709      * "grade-school" algorithm used in multiplyToLen.  If the numbers to be
1710      * multiplied have length n, the "grade-school" algorithm has an
1711      * asymptotic complexity of O(n^2).  In contrast, the Karatsuba algorithm
1712      * has complexity of O(n^(log2(3))), or O(n^1.585).  It achieves this
1713      * increased performance by doing 3 multiplies instead of 4 when
1714      * evaluating the product.  As it has some overhead, should be used when
1715      * both numbers are larger than a certain threshold (found
1716      * experimentally).
1717      *
1718      * See:  http://en.wikipedia.org/wiki/Karatsuba_algorithm
1719      */
1720     private static BigInteger multiplyKaratsuba(BigInteger x, BigInteger y) {
1721         int xlen = cast(int)x.mag.length;
1722         int ylen = cast(int)y.mag.length;
1723 
1724         // The number of ints in each half of the number.
1725         int half = (std.algorithm.max(xlen, ylen)+1) / 2;
1726 
1727         // xl and yl are the lower halves of x and y respectively,
1728         // xh and yh are the upper halves.
1729         BigInteger xl = x.getLower(half);
1730         BigInteger xh = x.getUpper(half);
1731         BigInteger yl = y.getLower(half);
1732         BigInteger yh = y.getUpper(half);
1733 
1734         BigInteger p1 = xh.multiply(yh);  // p1 = xh*yh
1735         BigInteger p2 = xl.multiply(yl);  // p2 = xl*yl
1736 
1737         // p3=(xh+xl)*(yh+yl)
1738         BigInteger p3 = xh.add(xl).multiply(yh.add(yl));
1739 
1740         // result = p1 * 2^(32*2*half) + (p3 - p1 - p2) * 2^(32*half) + p2
1741         BigInteger result = p1.shiftLeft(32*half).add(p3.subtract(p1).subtract(p2)).shiftLeft(32*half).add(p2);
1742 
1743         if (x.signum != y.signum) {
1744             return result.negate();
1745         } else {
1746             return result;
1747         }
1748     }
1749 
1750     /**
1751      * Multiplies two BigIntegers using a 3-way Toom-Cook multiplication
1752      * algorithm.  This is a recursive divide-and-conquer algorithm which is
1753      * more efficient for large numbers than what is commonly called the
1754      * "grade-school" algorithm used in multiplyToLen.  If the numbers to be
1755      * multiplied have length n, the "grade-school" algorithm has an
1756      * asymptotic complexity of O(n^2).  In contrast, 3-way Toom-Cook has a
1757      * complexity of about O(n^1.465).  It achieves this increased asymptotic
1758      * performance by breaking each number into three parts and by doing 5
1759      * multiplies instead of 9 when evaluating the product.  Due to overhead
1760      * (additions, shifts, and one division) in the Toom-Cook algorithm, it
1761      * should only be used when both numbers are larger than a certain
1762      * threshold (found experimentally).  This threshold is generally larger
1763      * than that for Karatsuba multiplication, so this algorithm is generally
1764      * only used when numbers become significantly larger.
1765      *
1766      * The algorithm used is the "optimal" 3-way Toom-Cook algorithm outlined
1767      * by Marco Bodrato.
1768      *
1769      *  See: http://bodrato.it/toom-cook/
1770      *       http://bodrato.it/papers/#WAIFI2007
1771      *
1772      * "Towards Optimal Toom-Cook Multiplication for Univariate and
1773      * Multivariate Polynomials in Characteristic 2 and 0." by Marco BODRATO;
1774      * In C.Carlet and B.Sunar, Eds., "WAIFI'07 proceedings", p. 116-133,
1775      * LNCS #4547. Springer, Madrid, Spain, June 21-22, 2007.
1776      *
1777      */
1778     private static BigInteger multiplyToomCook3(BigInteger a, BigInteger b) {
1779         int alen = cast(int)a.mag.length;
1780         int blen = cast(int)b.mag.length;
1781 
1782         int largest = std.algorithm.max(alen, blen);
1783 
1784         // k is the size (in ints) of the lower-order slices.
1785         int k = (largest+2)/3;   // Equal to ceil(largest/3)
1786 
1787         // r is the size (in ints) of the highest-order slice.
1788         int r = largest - 2*k;
1789 
1790         // Obtain slices of the numbers. a2 and b2 are the most significant
1791         // bits of the numbers a and b, and a0 and b0 the least significant.
1792         BigInteger a0, a1, a2, b0, b1, b2;
1793         a2 = a.getToomSlice(k, r, 0, largest);
1794         a1 = a.getToomSlice(k, r, 1, largest);
1795         a0 = a.getToomSlice(k, r, 2, largest);
1796         b2 = b.getToomSlice(k, r, 0, largest);
1797         b1 = b.getToomSlice(k, r, 1, largest);
1798         b0 = b.getToomSlice(k, r, 2, largest);
1799 
1800         BigInteger v0, v1, v2, vm1, vinf, t1, t2, tm1, da1, db1;
1801 
1802         v0 = a0.multiply(b0);
1803         da1 = a2.add(a0);
1804         db1 = b2.add(b0);
1805         vm1 = da1.subtract(a1).multiply(db1.subtract(b1));
1806         da1 = da1.add(a1);
1807         db1 = db1.add(b1);
1808         v1 = da1.multiply(db1);
1809         v2 = da1.add(a2).shiftLeft(1).subtract(a0).multiply(
1810              db1.add(b2).shiftLeft(1).subtract(b0));
1811         vinf = a2.multiply(b2);
1812 
1813         // The algorithm requires two divisions by 2 and one by 3.
1814         // All divisions are known to be exact, that is, they do not produce
1815         // remainders, and all results are positive.  The divisions by 2 are
1816         // implemented as right shifts which are relatively efficient, leaving
1817         // only an exact division by 3, which is done by a specialized
1818         // linear-time algorithm.
1819         t2 = v2.subtract(vm1).exactDivideBy3();
1820         tm1 = v1.subtract(vm1).shiftRight(1);
1821         t1 = v1.subtract(v0);
1822         t2 = t2.subtract(t1).shiftRight(1);
1823         t1 = t1.subtract(tm1).subtract(vinf);
1824         t2 = t2.subtract(vinf.shiftLeft(1));
1825         tm1 = tm1.subtract(t2);
1826 
1827         // Number of bits to shift left.
1828         int ss = k*32;
1829 
1830         BigInteger result = vinf.shiftLeft(ss).add(t2).shiftLeft(ss).add(t1).shiftLeft(ss).add(tm1).shiftLeft(ss).add(v0);
1831 
1832         if (a.signum != b.signum) {
1833             return result.negate();
1834         } else {
1835             return result;
1836         }
1837     }
1838 
1839 
1840     /**
1841      * Returns a slice of a BigInteger for use in Toom-Cook multiplication.
1842      *
1843      * @param lowerSize The size of the lower-order bit slices.
1844      * @param upperSize The size of the higher-order bit slices.
1845      * @param slice The index of which slice is requested, which must be a
1846      * number from 0 to size-1. Slice 0 is the highest-order bits, and slice
1847      * size-1 are the lowest-order bits. Slice 0 may be of different size than
1848      * the other slices.
1849      * @param fullsize The size of the larger integer array, used to align
1850      * slices to the appropriate position when multiplying different-sized
1851      * numbers.
1852      */
1853     private BigInteger getToomSlice(int lowerSize, int upperSize, int slice,
1854                                     int fullsize) {
1855         int start, end, sliceSize, len, offset;
1856 
1857         len = cast(int)mag.length;
1858         offset = fullsize - len;
1859 
1860         if (slice == 0) {
1861             start = 0 - offset;
1862             end = upperSize - 1 - offset;
1863         } else {
1864             start = upperSize + (slice-1)*lowerSize - offset;
1865             end = start + lowerSize - 1;
1866         }
1867 
1868         if (start < 0) {
1869             start = 0;
1870         }
1871         if (end < 0) {
1872            return ZERO;
1873         }
1874 
1875         sliceSize = (end-start) + 1;
1876 
1877         if (sliceSize <= 0) {
1878             return ZERO;
1879         }
1880 
1881         // While performing Toom-Cook, all slices are positive and
1882         // the sign is adjusted when the final number is composed.
1883         if (start == 0 && sliceSize >= len) {
1884             return this.abs();
1885         }
1886 
1887         int[] intSlice = mag[start .. start + sliceSize];
1888         // int[] intSlice = new int[sliceSize];
1889         //System.arraycopy(mag, start, intSlice, 0, sliceSize);
1890 
1891         return new BigInteger(trustedStripLeadingZeroInts(intSlice), 1);
1892     }
1893 
1894     /**
1895      * Does an exact division (that is, the remainder is known to be zero)
1896      * of the specified number by 3.  This is used in Toom-Cook
1897      * multiplication.  This is an efficient algorithm that runs in linear
1898      * time.  If the argument is not exactly divisible by 3, results are
1899      * undefined.  Note that this is expected to be called with positive
1900      * arguments only.
1901      */
1902     private BigInteger exactDivideBy3() {
1903         int len = cast(int)mag.length;
1904         int[] result = new int[len];
1905         long x, w, q, borrow;
1906         borrow = 0L;
1907         for (int i=len-1; i >= 0; i--) {
1908             x = (mag[i] & LONG_MASK);
1909             w = x - borrow;
1910             if (borrow > x) {      // Did we make the number go negative?
1911                 borrow = 1L;
1912             } else {
1913                 borrow = 0L;
1914             }
1915 
1916             // 0xAAAAAAAB is the modular inverse of 3 (mod 2^32).  Thus,
1917             // the effect of this is to divide by 3 (mod 2^32).
1918             // This is much faster than division on most architectures.
1919             q = (w * 0xAAAAAAABL) & LONG_MASK;
1920             result[i] = cast(int) q;
1921 
1922             // Now check the borrow. The second check can of course be
1923             // eliminated if the first fails.
1924             if (q >= 0x55555556L) {
1925                 borrow++;
1926                 if (q >= 0xAAAAAAABL)
1927                     borrow++;
1928             }
1929         }
1930         result = trustedStripLeadingZeroInts(result);
1931         return new BigInteger(result, signum);
1932     }
1933 
1934     /**
1935      * Returns a new BigInteger representing n lower ints of the number.
1936      * This is used by Karatsuba multiplication and Karatsuba squaring.
1937      */
1938     private BigInteger getLower(int n) {
1939         int len = cast(int)mag.length;
1940 
1941         if (len <= n) {
1942             return abs();
1943         }
1944 
1945         int[] lowerInts = mag[len-n .. len];
1946         // int[] lowerInts = new int[n];
1947         // System.arraycopy(mag, len-n, lowerInts, 0, n);
1948 
1949         return new BigInteger(trustedStripLeadingZeroInts(lowerInts), 1);
1950     }
1951 
1952     /**
1953      * Returns a new BigInteger representing mag.length-n upper
1954      * ints of the number.  This is used by Karatsuba multiplication and
1955      * Karatsuba squaring.
1956      */
1957     private BigInteger getUpper(int n) {
1958         int len = cast(int)mag.length;
1959 
1960         if (len <= n) {
1961             return ZERO;
1962         }
1963 
1964         int upperLen = len - n;
1965         int[] upperInts = mag[0 .. upperLen];
1966         // int[] upperInts = new int[upperLen];
1967         // System.arraycopy(mag, 0, upperInts, 0, upperLen);
1968 
1969         return new BigInteger(trustedStripLeadingZeroInts(upperInts), 1);
1970     }
1971 
1972     // Squaring
1973 
1974     /**
1975      * Returns a BigInteger whose value is {@code (this<sup>2</sup>)}.
1976      *
1977      * @return {@code this<sup>2</sup>}
1978      */
1979     private BigInteger square() {
1980         if (_signum == 0) {
1981             return ZERO;
1982         }
1983         int len = cast(int)mag.length;
1984 
1985         if (len < KARATSUBA_SQUARE_THRESHOLD) {
1986             int[] z = squareToLen(mag, len, null);
1987             return new BigInteger(trustedStripLeadingZeroInts(z), 1);
1988         } else {
1989             if (len < TOOM_COOK_SQUARE_THRESHOLD) {
1990                 return squareKaratsuba();
1991             } else {
1992                 return squareToomCook3();
1993             }
1994         }
1995     }
1996 
1997     /**
1998      * Squares the contents of the int array x. The result is placed into the
1999      * int array z.  The contents of x are not changed.
2000      */
2001     private static int[] squareToLen(int[] x, int len, int[] z) {
2002          int zlen = len << 1;
2003          if (z is null || z.length < zlen)
2004              z = new int[zlen];
2005 
2006          // Execute checks before calling intrinsified method.
2007          implSquareToLenChecks(x, len, z, zlen);
2008          return implSquareToLen(x, len, z, zlen);
2009      }
2010 
2011      /**
2012       * Parameters validation.
2013       */
2014      private static void implSquareToLenChecks(int[] x, int len, int[] z, int zlen) {
2015          if (len < 1) {
2016              throw new IllegalArgumentException("invalid input length: " ~ len.to!string().to!string());
2017          }
2018          if (len > x.length) {
2019              throw new IllegalArgumentException("input length out of bound: " ~
2020                                         len.to!string() ~ " > " ~ x.length.to!string());
2021          }
2022          if (len * 2 > z.length) {
2023              throw new IllegalArgumentException("input length out of bound: " ~
2024                                         (len * 2).to!string() ~ " > " ~ z.length.to!string());
2025          }
2026          if (zlen < 1) {
2027              throw new IllegalArgumentException("invalid input length: " ~ zlen.to!string());
2028          }
2029          if (zlen > z.length) {
2030              throw new IllegalArgumentException("input length out of bound: " ~
2031                                         len.to!string() ~ " > " ~ z.length.to!string());
2032          }
2033      }
2034 
2035      /**
2036       * Java Runtime may use intrinsic for this method.
2037       */
2038      
2039      private static final int[] implSquareToLen(int[] x, int len, int[] z, int zlen) {
2040         /*
2041          * The algorithm used here is adapted from Colin Plumb's C library.
2042          * Technique: Consider the partial products in the multiplication
2043          * of "abcde" by itself:
2044          *
2045          *               a  b  c  d  e
2046          *            *  a  b  c  d  e
2047          *          ==================
2048          *              ae be ce de ee
2049          *           ad bd cd dd de
2050          *        ac bc cc cd ce
2051          *     ab bb bc bd be
2052          *  aa ab ac ad ae
2053          *
2054          * Note that everything above the main diagonal:
2055          *              ae be ce de = (abcd) * e
2056          *           ad bd cd       = (abc) * d
2057          *        ac bc             = (ab) * c
2058          *     ab                   = (a) * b
2059          *
2060          * is a copy of everything below the main diagonal:
2061          *                       de
2062          *                 cd ce
2063          *           bc bd be
2064          *     ab ac ad ae
2065          *
2066          * Thus, the sum is 2 * (off the diagonal) + diagonal.
2067          *
2068          * This is accumulated beginning with the diagonal (which
2069          * consist of the squares of the digits of the input), which is then
2070          * divided by two, the off-diagonal added, and multiplied by two
2071          * again.  The low bit is simply a copy of the low bit of the
2072          * input, so it doesn't need special care.
2073          */
2074 
2075         // Store the squares, right shifted one bit (i.e., divided by 2)
2076         int lastProductLowWord = 0;
2077         for (int j=0, i=0; j < len; j++) {
2078             long piece = (x[j] & LONG_MASK);
2079             long product = piece * piece;
2080             z[i++] = (lastProductLowWord << 31) | cast(int)(product >>> 33);
2081             z[i++] = cast(int)(product >>> 1);
2082             lastProductLowWord = cast(int)product;
2083         }
2084 
2085         // Add in off-diagonal sums
2086         for (int i=len, offset=1; i > 0; i--, offset+=2) {
2087             int t = x[i-1];
2088             t = mulAdd(z, x, offset, i-1, t);
2089             addOne(z, offset-1, i, t);
2090         }
2091 
2092         // Shift back up and set low bit
2093         primitiveLeftShift(z, zlen, 1);
2094         z[zlen-1] |= x[len-1] & 1;
2095 
2096         return z;
2097     }
2098 
2099     /**
2100      * Squares a BigInteger using the Karatsuba squaring algorithm.  It should
2101      * be used when both numbers are larger than a certain threshold (found
2102      * experimentally).  It is a recursive divide-and-conquer algorithm that
2103      * has better asymptotic performance than the algorithm used in
2104      * squareToLen.
2105      */
2106     private BigInteger squareKaratsuba() {
2107         int half = cast(int)(mag.length+1) / 2;
2108 
2109         BigInteger xl = getLower(half);
2110         BigInteger xh = getUpper(half);
2111 
2112         BigInteger xhs = xh.square();  // xhs = xh^2
2113         BigInteger xls = xl.square();  // xls = xl^2
2114 
2115         // xh^2 << 64  +  (((xl+xh)^2 - (xh^2 + xl^2)) << 32) + xl^2
2116         return xhs.shiftLeft(half*32).add(xl.add(xh).square().subtract(xhs.add(xls))).shiftLeft(half*32).add(xls);
2117     }
2118 
2119     /**
2120      * Squares a BigInteger using the 3-way Toom-Cook squaring algorithm.  It
2121      * should be used when both numbers are larger than a certain threshold
2122      * (found experimentally).  It is a recursive divide-and-conquer algorithm
2123      * that has better asymptotic performance than the algorithm used in
2124      * squareToLen or squareKaratsuba.
2125      */
2126     private BigInteger squareToomCook3() {
2127         int len = cast(int)mag.length;
2128 
2129         // k is the size (in ints) of the lower-order slices.
2130         int k = (len+2)/3;   // Equal to ceil(largest/3)
2131 
2132         // r is the size (in ints) of the highest-order slice.
2133         int r = len - 2*k;
2134 
2135         // Obtain slices of the numbers. a2 is the most significant
2136         // bits of the number, and a0 the least significant.
2137         BigInteger a0, a1, a2;
2138         a2 = getToomSlice(k, r, 0, len);
2139         a1 = getToomSlice(k, r, 1, len);
2140         a0 = getToomSlice(k, r, 2, len);
2141         BigInteger v0, v1, v2, vm1, vinf, t1, t2, tm1, da1;
2142 
2143         v0 = a0.square();
2144         da1 = a2.add(a0);
2145         vm1 = da1.subtract(a1).square();
2146         da1 = da1.add(a1);
2147         v1 = da1.square();
2148         vinf = a2.square();
2149         v2 = da1.add(a2).shiftLeft(1).subtract(a0).square();
2150 
2151         // The algorithm requires two divisions by 2 and one by 3.
2152         // All divisions are known to be exact, that is, they do not produce
2153         // remainders, and all results are positive.  The divisions by 2 are
2154         // implemented as right shifts which are relatively efficient, leaving
2155         // only a division by 3.
2156         // The division by 3 is done by an optimized algorithm for this case.
2157         t2 = v2.subtract(vm1).exactDivideBy3();
2158         tm1 = v1.subtract(vm1).shiftRight(1);
2159         t1 = v1.subtract(v0);
2160         t2 = t2.subtract(t1).shiftRight(1);
2161         t1 = t1.subtract(tm1).subtract(vinf);
2162         t2 = t2.subtract(vinf.shiftLeft(1));
2163         tm1 = tm1.subtract(t2);
2164 
2165         // Number of bits to shift left.
2166         int ss = k*32;
2167 
2168         return vinf.shiftLeft(ss).add(t2).shiftLeft(ss).add(t1).shiftLeft(ss).add(tm1).shiftLeft(ss).add(v0);
2169     }
2170 
2171     // Division
2172 
2173     /**
2174      * Returns a BigInteger whose value is {@code (this / val)}.
2175      *
2176      * @param  val value by which this BigInteger is to be divided.
2177      * @return {@code this / val}
2178      * @throws ArithmeticException if {@code val} is zero.
2179      */
2180     BigInteger divide(BigInteger val) {
2181         // if (val.mag.length < BURNIKEL_ZIEGLER_THRESHOLD ||
2182         //         mag.length - val.mag.length < BURNIKEL_ZIEGLER_OFFSET) {
2183         //     return divideKnuth(val);
2184         // } else {
2185         //     return divideBurnikelZiegler(val);
2186         // }
2187         return null;
2188     }
2189 
2190     /**
2191      * Returns a BigInteger whose value is {@code (this / val)} using an O(n^2) algorithm from Knuth.
2192      *
2193      * @param  val value by which this BigInteger is to be divided.
2194      * @return {@code this / val}
2195      * @throws ArithmeticException if {@code val} is zero.
2196      * @see MutableBigInteger#divideKnuth(MutableBigInteger, MutableBigInteger, bool)
2197      */
2198     // private BigInteger divideKnuth(BigInteger val) {
2199     //     MutableBigInteger q = new MutableBigInteger(),
2200     //                       a = new MutableBigInteger(this.mag),
2201     //                       b = new MutableBigInteger(val.mag);
2202 
2203     //     a.divideKnuth(b, q, false);
2204     //     return q.toBigInteger(this._signum * val.signum);
2205     // }
2206 
2207     /**
2208      * Returns an array of two BigIntegers containing {@code (this / val)}
2209      * followed by {@code (this % val)}.
2210      *
2211      * @param  val value by which this BigInteger is to be divided, and the
2212      *         remainder computed.
2213      * @return an array of two BigIntegers: the quotient {@code (this / val)}
2214      *         is the initial element, and the remainder {@code (this % val)}
2215      *         is the final element.
2216      * @throws ArithmeticException if {@code val} is zero.
2217      */
2218     BigInteger[] divideAndRemainder(BigInteger val) {
2219         if (val.mag.length < BURNIKEL_ZIEGLER_THRESHOLD ||
2220                 mag.length - val.mag.length < BURNIKEL_ZIEGLER_OFFSET) {
2221             return divideAndRemainderKnuth(val);
2222         } else {
2223             return divideAndRemainderBurnikelZiegler(val);
2224         }
2225     }
2226 
2227     /** Long division */
2228     private BigInteger[] divideAndRemainderKnuth(BigInteger val) {
2229         BigInteger[] result = new BigInteger[2];
2230         MutableBigInteger q = new MutableBigInteger(),
2231                           a = new MutableBigInteger(this.mag),
2232                           b = new MutableBigInteger(val.mag);
2233         MutableBigInteger r = a.divideKnuth(b, q);
2234         result[0] = q.toBigInteger(this._signum == val.signum ? 1 : -1);
2235         result[1] = r.toBigInteger(this._signum);
2236         return result;
2237     }
2238 
2239     /**
2240      * Returns a BigInteger whose value is {@code (this % val)}.
2241      *
2242      * @param  val value by which this BigInteger is to be divided, and the
2243      *         remainder computed.
2244      * @return {@code this % val}
2245      * @throws ArithmeticException if {@code val} is zero.
2246      */
2247     BigInteger remainder(BigInteger val) {
2248         if (val.mag.length < BURNIKEL_ZIEGLER_THRESHOLD ||
2249                 mag.length - val.mag.length < BURNIKEL_ZIEGLER_OFFSET) {
2250             return remainderKnuth(val);
2251         } else {
2252             return remainderBurnikelZiegler(val);
2253         }
2254     }
2255 
2256     /** Long division */
2257     private BigInteger remainderKnuth(BigInteger val) {
2258         MutableBigInteger q = new MutableBigInteger(),
2259                           a = new MutableBigInteger(this.mag),
2260                           b = new MutableBigInteger(val.mag);
2261 
2262         return a.divideKnuth(b, q).toBigInteger(this._signum);
2263     }
2264 
2265     /**
2266      * Calculates {@code this / val} using the Burnikel-Ziegler algorithm.
2267      * @param  val the divisor
2268      * @return {@code this / val}
2269      */
2270     private BigInteger divideBurnikelZiegler(BigInteger val) {
2271         return divideAndRemainderBurnikelZiegler(val)[0];
2272     }
2273 
2274     /**
2275      * Calculates {@code this % val} using the Burnikel-Ziegler algorithm.
2276      * @param val the divisor
2277      * @return {@code this % val}
2278      */
2279     private BigInteger remainderBurnikelZiegler(BigInteger val) {
2280         return divideAndRemainderBurnikelZiegler(val)[1];
2281     }
2282 
2283     /**
2284      * Computes {@code this / val} and {@code this % val} using the
2285      * Burnikel-Ziegler algorithm.
2286      * @param val the divisor
2287      * @return an array containing the quotient and remainder
2288      */
2289     private BigInteger[] divideAndRemainderBurnikelZiegler(BigInteger val) {
2290         MutableBigInteger q = new MutableBigInteger();
2291         MutableBigInteger r = new MutableBigInteger(this).divideAndRemainderBurnikelZiegler(new MutableBigInteger(val), q);
2292         BigInteger qBigInt = q.isZero() ? ZERO : q.toBigInteger(signum*val.signum);
2293         BigInteger rBigInt = r.isZero() ? ZERO : r.toBigInteger(signum);
2294         return [qBigInt, rBigInt];
2295     }
2296 
2297     /**
2298      * Returns a BigInteger whose value is <code>(this<sup>exponent</sup>)</code>.
2299      * Note that {@code exponent} is an integer rather than a BigInteger.
2300      *
2301      * @param  exponent exponent to which this BigInteger is to be raised.
2302      * @return <code>this<sup>exponent</sup></code>
2303      * @throws ArithmeticException {@code exponent} is negative.  (This would
2304      *         cause the operation to yield a non-integer value.)
2305      */
2306     BigInteger pow(int exponent) {
2307         if (exponent < 0) {
2308             throw new ArithmeticException("Negative exponent");
2309         }
2310         if (_signum == 0) {
2311             return (exponent == 0 ? ONE : this);
2312         }
2313 
2314         BigInteger partToSquare = this.abs();
2315 
2316         // Factor out powers of two from the base, as the exponentiation of
2317         // these can be done by left shifts only.
2318         // The remaining part can then be exponentiated faster.  The
2319         // powers of two will be multiplied back at the end.
2320         int powersOfTwo = partToSquare.getLowestSetBit();
2321         long bitsToShift = cast(long)powersOfTwo * exponent;
2322         if (bitsToShift > int.max) {
2323             reportOverflow();
2324         }
2325 
2326         int remainingBits;
2327 
2328         // Factor the powers of two out quickly by shifting right, if needed.
2329         if (powersOfTwo > 0) {
2330             partToSquare = partToSquare.shiftRight(powersOfTwo);
2331             remainingBits = partToSquare.bitLength();
2332             if (remainingBits == 1) {  // Nothing left but +/- 1?
2333                 if (signum < 0 && (exponent&1) == 1) {
2334                     return NEGATIVE_ONE.shiftLeft(powersOfTwo*exponent);
2335                 } else {
2336                     return ONE.shiftLeft(powersOfTwo*exponent);
2337                 }
2338             }
2339         } else {
2340             remainingBits = partToSquare.bitLength();
2341             if (remainingBits == 1) { // Nothing left but +/- 1?
2342                 if (signum < 0  && (exponent&1) == 1) {
2343                     return NEGATIVE_ONE;
2344                 } else {
2345                     return ONE;
2346                 }
2347             }
2348         }
2349 
2350         // This is a quick way to approximate the size of the result,
2351         // similar to doing log2[n] * exponent.  This will give an upper bound
2352         // of how big the result can be, and which algorithm to use.
2353         long scaleFactor = cast(long)remainingBits * exponent;
2354 
2355         // Use slightly different algorithms for small and large operands.
2356         // See if the result will safely fit into a long. (Largest 2^63-1)
2357         if (partToSquare.mag.length == 1 && scaleFactor <= 62) {
2358             // Small number algorithm.  Everything fits into a long.
2359             int newSign = (signum <0  && (exponent&1) == 1 ? -1 : 1);
2360             long result = 1;
2361             long baseToPow2 = partToSquare.mag[0] & LONG_MASK;
2362 
2363             int workingExponent = exponent;
2364 
2365             // Perform exponentiation using repeated squaring trick
2366             while (workingExponent != 0) {
2367                 if ((workingExponent & 1) == 1) {
2368                     result = result * baseToPow2;
2369                 }
2370 
2371                 if ((workingExponent >>>= 1) != 0) {
2372                     baseToPow2 = baseToPow2 * baseToPow2;
2373                 }
2374             }
2375 
2376             // Multiply back the powers of two (quickly, by shifting left)
2377             if (powersOfTwo > 0) {
2378                 if (bitsToShift + scaleFactor <= 62) { // Fits in long?
2379                     return valueOf((result << bitsToShift) * newSign);
2380                 } else {
2381                     return valueOf(result*newSign).shiftLeft(cast(int) bitsToShift);
2382                 }
2383             }
2384             else {
2385                 return valueOf(result*newSign);
2386             }
2387         } else {
2388             // Large number algorithm.  This is basically identical to
2389             // the algorithm above, but calls multiply() and square()
2390             // which may use more efficient algorithms for large numbers.
2391             BigInteger answer = ONE;
2392 
2393             int workingExponent = exponent;
2394             // Perform exponentiation using repeated squaring trick
2395             while (workingExponent != 0) {
2396                 if ((workingExponent & 1) == 1) {
2397                     answer = answer.multiply(partToSquare);
2398                 }
2399 
2400                 if ((workingExponent >>>= 1) != 0) {
2401                     partToSquare = partToSquare.square();
2402                 }
2403             }
2404             // Multiply back the (exponentiated) powers of two (quickly,
2405             // by shifting left)
2406             if (powersOfTwo > 0) {
2407                 answer = answer.shiftLeft(powersOfTwo*exponent);
2408             }
2409 
2410             if (signum < 0 && (exponent&1) == 1) {
2411                 return answer.negate();
2412             } else {
2413                 return answer;
2414             }
2415         }
2416     }
2417 
2418     /**
2419      * Returns the integer square root of this BigInteger.  The integer square
2420      * root of the corresponding mathematical integer {@code n} is the largest
2421      * mathematical integer {@code s} such that {@code s*s <= n}.  It is equal
2422      * to the value of {@code floor(sqrt(n))}, where {@code sqrt(n)} denotes the
2423      * real square root of {@code n} treated as a real.  Note that the integer
2424      * square root will be less than the real square root if the latter is not
2425      * representable as an integral value.
2426      *
2427      * @return the integer square root of {@code this}
2428      * @throws ArithmeticException if {@code this} is negative.  (The square
2429      *         root of a negative integer {@code val} is
2430      *         {@code (i * sqrt(-val))} where <i>i</i> is the
2431      *         <i>imaginary unit</i> and is equal to
2432      *         {@code sqrt(-1)}.)
2433      */
2434     BigInteger sqrt() {
2435         if (this._signum < 0) {
2436             throw new ArithmeticException("Negative BigInteger");
2437         }
2438 
2439         return new MutableBigInteger(this.mag).sqrt().toBigInteger();
2440     }
2441 
2442     /**
2443      * Returns an array of two BigIntegers containing the integer square root
2444      * {@code s} of {@code this} and its remainder {@code this - s*s},
2445      * respectively.
2446      *
2447      * @return an array of two BigIntegers with the integer square root at
2448      *         offset 0 and the remainder at offset 1
2449      * @throws ArithmeticException if {@code this} is negative.  (The square
2450      *         root of a negative integer {@code val} is
2451      *         {@code (i * sqrt(-val))} where <i>i</i> is the
2452      *         <i>imaginary unit</i> and is equal to
2453      *         {@code sqrt(-1)}.)
2454      * @see #sqrt()
2455      */
2456     BigInteger[] sqrtAndRemainder() {
2457         BigInteger s = sqrt();
2458         BigInteger r = this.subtract(s.square());
2459         assert(r.compareTo(BigInteger.ZERO) >= 0);
2460         return [s, r];
2461     }
2462 
2463     /**
2464      * Returns a BigInteger whose value is the greatest common divisor of
2465      * {@code abs(this)} and {@code abs(val)}.  Returns 0 if
2466      * {@code this == 0 && val == 0}.
2467      *
2468      * @param  val value with which the GCD is to be computed.
2469      * @return {@code GCD(abs(this), abs(val))}
2470      */
2471     BigInteger gcd(BigInteger val) {
2472         if (val._signum == 0)
2473             return this.abs();
2474         else if (this._signum == 0)
2475             return val.abs();
2476 
2477         MutableBigInteger a = new MutableBigInteger(this);
2478         MutableBigInteger b = new MutableBigInteger(val);
2479 
2480         MutableBigInteger result = a.hybridGCD(b);
2481 
2482         return result.toBigInteger(1);
2483     }
2484 
2485     /**
2486      * Package private method to return bit length for an integer.
2487      */
2488     static int bitLengthForInt(int n) {
2489         return 32 - Integer.numberOfLeadingZeros(n);
2490     }
2491 
2492     /**
2493      * Left shift int array a up to len by n bits. Returns the array that
2494      * results from the shift since space may have to be reallocated.
2495      */
2496     private static int[] leftShift(int[] a, int len, int n) {
2497         int nInts = n >>> 5;
2498         int nBits = n&0x1F;
2499         int bitsInHighWord = bitLengthForInt(a[0]);
2500 
2501         // If shift can be done without recopy, do so
2502         if (n <= (32-bitsInHighWord)) {
2503             primitiveLeftShift(a, len, nBits);
2504             return a;
2505         } else { // Array must be resized
2506             if (nBits <= (32-bitsInHighWord)) {
2507                 int[] result = new int[nInts+len];
2508                 // System.arraycopy(a, 0, result, 0, len);
2509                 result[0..len] = a[0..len];
2510                 primitiveLeftShift(result, cast(int)result.length, nBits);
2511                 return result;
2512             } else {
2513                 int[] result = new int[nInts+len+1];
2514                 // System.arraycopy(a, 0, result, 0, len);
2515                 result[0..len] = a[0..len];
2516                 primitiveRightShift(result, cast(int)result.length, 32 - nBits);
2517                 return result;
2518             }
2519         }
2520     }
2521 
2522     // shifts a up to len right n bits assumes no leading zeros, 0<n<32
2523     static void primitiveRightShift(int[] a, int len, int n) {
2524         int n2 = 32 - n;
2525         for (int i=len-1, c=a[i]; i > 0; i--) {
2526             int b = c;
2527             c = a[i-1];
2528             a[i] = (c << n2) | (b >>> n);
2529         }
2530         a[0] >>>= n;
2531     }
2532 
2533     // shifts a up to len left n bits assumes no leading zeros, 0<=n<32
2534     static void primitiveLeftShift(int[] a, int len, int n) {
2535         if (len == 0 || n == 0)
2536             return;
2537 
2538         int n2 = 32 - n;
2539         for (int i=0, c=a[i], m=i+len-1; i < m; i++) {
2540             int b = c;
2541             c = a[i+1];
2542             a[i] = (b << n) | (c >>> n2);
2543         }
2544         a[len-1] <<= n;
2545     }
2546 
2547     /**
2548      * Calculate bitlength of contents of the first len elements an int array,
2549      * assuming there are no leading zero ints.
2550      */
2551     private static int bitLength(int[] val, int len) {
2552         if (len == 0)
2553             return 0;
2554         return ((len - 1) << 5) + bitLengthForInt(val[0]);
2555     }
2556 
2557     /**
2558      * Returns a BigInteger whose value is the absolute value of this
2559      * BigInteger.
2560      *
2561      * @return {@code abs(this)}
2562      */
2563     BigInteger abs() {
2564         return (signum >= 0 ? this : this.negate());
2565     }
2566 
2567     /**
2568      * Returns a BigInteger whose value is {@code (-this)}.
2569      *
2570      * @return {@code -this}
2571      */
2572     BigInteger negate() {
2573         return new BigInteger(this.mag, -this._signum);
2574     }
2575 
2576     /**
2577      * Returns the signum function of this BigInteger.
2578      *
2579      * @return -1, 0 or 1 as the value of this BigInteger is negative, zero or
2580      *         positive.
2581      */
2582     int signum() {
2583         return this._signum;
2584     }
2585 
2586     // Modular Arithmetic Operations
2587 
2588     /**
2589      * Returns a BigInteger whose value is {@code (this mod m}).  This method
2590      * differs from {@code remainder} in that it always returns a
2591      * <i>non-negative</i> BigInteger.
2592      *
2593      * @param  m the modulus.
2594      * @return {@code this mod m}
2595      * @throws ArithmeticException {@code m} &le; 0
2596      * @see    #remainder
2597      */
2598     BigInteger mod(BigInteger m) {
2599         if (m.signum <= 0)
2600             throw new ArithmeticException("BigInteger: modulus not positive");
2601 
2602         BigInteger result = this.remainder(m);
2603         return (result.signum >= 0 ? result : result.add(m));
2604     }
2605 
2606     /**
2607      * Returns a BigInteger whose value is
2608      * <code>(this<sup>exponent</sup> mod m)</code>.  (Unlike {@code pow}, this
2609      * method permits negative exponents.)
2610      *
2611      * @param  exponent the exponent.
2612      * @param  m the modulus.
2613      * @return <code>this<sup>exponent</sup> mod m</code>
2614      * @throws ArithmeticException {@code m} &le; 0 or the exponent is
2615      *         negative and this BigInteger is not <i>relatively
2616      *         prime</i> to {@code m}.
2617      * @see    #modInverse
2618      */
2619     BigInteger modPow(BigInteger exponent, BigInteger m) {
2620         if (m.signum <= 0)
2621             throw new ArithmeticException("BigInteger: modulus not positive");
2622 
2623         // Trivial cases
2624         if (exponent._signum == 0)
2625             return (m.equals(ONE) ? ZERO : ONE);
2626 
2627         if (this.equals(ONE))
2628             return (m.equals(ONE) ? ZERO : ONE);
2629 
2630         if (this.equals(ZERO) && exponent.signum >= 0)
2631             return ZERO;
2632 
2633         if (this.equals(negConst[1]) && (!exponent.testBit(0)))
2634             return (m.equals(ONE) ? ZERO : ONE);
2635 
2636         bool invertResult;
2637         invertResult = (exponent.signum < 0);
2638         if (invertResult)
2639             exponent = exponent.negate();
2640 
2641         BigInteger base = (this._signum < 0 || this.compareTo(m) >= 0
2642                            ? this.mod(m) : this);
2643         BigInteger result;
2644         if (m.testBit(0)) { // odd modulus
2645             result = base.oddModPow(exponent, m);
2646         } else {
2647             /*
2648              * Even modulus.  Tear it into an "odd part" (m1) and power of two
2649              * (m2), exponentiate mod m1, manually exponentiate mod m2, and
2650              * use Chinese Remainder Theorem to combine results.
2651              */
2652 
2653             // Tear m apart into odd part (m1) and power of 2 (m2)
2654             int p = m.getLowestSetBit();   // Max pow of 2 that divides m
2655 
2656             BigInteger m1 = m.shiftRight(p);  // m/2**p
2657             BigInteger m2 = ONE.shiftLeft(p); // 2**p
2658 
2659             // Calculate new base from m1
2660             BigInteger base2 = (this._signum < 0 || this.compareTo(m1) >= 0
2661                                 ? this.mod(m1) : this);
2662 
2663             // Caculate (base ** exponent) mod m1.
2664             BigInteger a1 = (m1.equals(ONE) ? ZERO :
2665                              base2.oddModPow(exponent, m1));
2666 
2667             // Calculate (this ** exponent) mod m2
2668             BigInteger a2 = base.modPow2(exponent, p);
2669 
2670             // Combine results using Chinese Remainder Theorem
2671             BigInteger y1 = m2.modInverse(m1);
2672             BigInteger y2 = m1.modInverse(m2);
2673 
2674             if (m.mag.length < MAX_MAG_LENGTH / 2) {
2675                 result = a1.multiply(m2).multiply(y1).add(a2.multiply(m1).multiply(y2)).mod(m);
2676             } else {
2677                 MutableBigInteger t1 = new MutableBigInteger();
2678                 new MutableBigInteger(a1.multiply(m2)).multiply(new MutableBigInteger(y1), t1);
2679                 MutableBigInteger t2 = new MutableBigInteger();
2680                 new MutableBigInteger(a2.multiply(m1)).multiply(new MutableBigInteger(y2), t2);
2681                 t1.add(t2);
2682                 MutableBigInteger q = new MutableBigInteger();
2683                 result = t1.divide(new MutableBigInteger(m), q).toBigInteger();
2684             }
2685         }
2686 
2687         return (invertResult ? result.modInverse(m) : result);
2688     }
2689 
2690     // Montgomery multiplication.  These are wrappers for
2691     // implMontgomeryXX routines which are expected to be replaced by
2692     // virtual machine intrinsics.  We don't use the intrinsics for
2693     // very large operands: MONTGOMERY_INTRINSIC_THRESHOLD should be
2694     // larger than any reasonable crypto key.
2695     private static int[] montgomeryMultiply(int[] a, int[] b, int[] n, int len, long inv,
2696                                             int[] product) {
2697         implMontgomeryMultiplyChecks(a, b, n, len, product);
2698         if (len > MONTGOMERY_INTRINSIC_THRESHOLD) {
2699             // Very long argument: do not use an intrinsic
2700             product = multiplyToLen(a, len, b, len, product);
2701             return montReduce(product, n, len, cast(int)inv);
2702         } else {
2703             return implMontgomeryMultiply(a, b, n, len, inv, materialize(product, len));
2704         }
2705     }
2706     private static int[] montgomerySquare(int[] a, int[] n, int len, long inv,
2707                                           int[] product) {
2708         implMontgomeryMultiplyChecks(a, a, n, len, product);
2709         if (len > MONTGOMERY_INTRINSIC_THRESHOLD) {
2710             // Very long argument: do not use an intrinsic
2711             product = squareToLen(a, len, product);
2712             return montReduce(product, n, len, cast(int)inv);
2713         } else {
2714             return implMontgomerySquare(a, n, len, inv, materialize(product, len));
2715         }
2716     }
2717 
2718     // Range-check everything.
2719     private static void implMontgomeryMultiplyChecks
2720         (int[] a, int[] b, int[] n, int len, int[] product) {
2721         if (len % 2 != 0) {
2722             throw new IllegalArgumentException("input array length must be even: " ~ len.to!string());
2723         }
2724 
2725         if (len < 1) {
2726             throw new IllegalArgumentException("invalid input length: " ~ len.to!string());
2727         }
2728 
2729         if (len > a.length ||
2730             len > b.length ||
2731             len > n.length ||
2732             (product !is null && len > product.length)) {
2733             throw new IllegalArgumentException("input array length out of bound: " ~ len.to!string());
2734         }
2735     }
2736 
2737     // Make sure that the int array z (which is expected to contain
2738     // the result of a Montgomery multiplication) is present and
2739     // sufficiently large.
2740     private static int[] materialize(int[] z, int len) {
2741          if (z is null || z.length < len)
2742              z = new int[len];
2743          return z;
2744     }
2745 
2746     // These methods are intended to be replaced by virtual machine
2747     // intrinsics.
2748     
2749     private static int[] implMontgomeryMultiply(int[] a, int[] b, int[] n, int len,
2750                                          long inv, int[] product) {
2751         product = multiplyToLen(a, len, b, len, product);
2752         return montReduce(product, n, len, cast(int)inv);
2753     }
2754     
2755     private static int[] implMontgomerySquare(int[] a, int[] n, int len,
2756                                        long inv, int[] product) {
2757         product = squareToLen(a, len, product);
2758         return montReduce(product, n, len, cast(int)inv);
2759     }
2760 
2761     enum int[] bnExpModThreshTable = [7, 25, 81, 241, 673, 1793,
2762                                                 int.max]; // Sentinel
2763 
2764     /**
2765      * Returns a BigInteger whose value is x to the power of y mod z.
2766      * Assumes: z is odd && x < z.
2767      */
2768     private BigInteger oddModPow(BigInteger y, BigInteger z) {
2769     /*
2770      * The algorithm is adapted from Colin Plumb's C library.
2771      *
2772      * The window algorithm:
2773      * The idea is to keep a running product of b1 = n^(high-order bits of exp)
2774      * and then keep appending exponent bits to it.  The following patterns
2775      * apply to a 3-bit window (k = 3):
2776      * To append   0: square
2777      * To append   1: square, multiply by n^1
2778      * To append  10: square, multiply by n^1, square
2779      * To append  11: square, square, multiply by n^3
2780      * To append 100: square, multiply by n^1, square, square
2781      * To append 101: square, square, square, multiply by n^5
2782      * To append 110: square, square, multiply by n^3, square
2783      * To append 111: square, square, square, multiply by n^7
2784      *
2785      * Since each pattern involves only one multiply, the longer the pattern
2786      * the better, except that a 0 (no multiplies) can be appended directly.
2787      * We precompute a table of odd powers of n, up to 2^k, and can then
2788      * multiply k bits of exponent at a time.  Actually, assuming random
2789      * exponents, there is on average one zero bit between needs to
2790      * multiply (1/2 of the time there's none, 1/4 of the time there's 1,
2791      * 1/8 of the time, there's 2, 1/32 of the time, there's 3, etc.), so
2792      * you have to do one multiply per k+1 bits of exponent.
2793      *
2794      * The loop walks down the exponent, squaring the result buffer as
2795      * it goes.  There is a wbits+1 bit lookahead buffer, buf, that is
2796      * filled with the upcoming exponent bits.  (What is read after the
2797      * end of the exponent is unimportant, but it is filled with zero here.)
2798      * When the most-significant bit of this buffer becomes set, i.e.
2799      * (buf & tblmask) != 0, we have to decide what pattern to multiply
2800      * by, and when to do it.  We decide, remember to do it in future
2801      * after a suitable number of squarings have passed (e.g. a pattern
2802      * of "100" in the buffer requires that we multiply by n^1 immediately;
2803      * a pattern of "110" calls for multiplying by n^3 after one more
2804      * squaring), clear the buffer, and continue.
2805      *
2806      * When we start, there is one more optimization: the result buffer
2807      * is implcitly one, so squaring it or multiplying by it can be
2808      * optimized away.  Further, if we start with a pattern like "100"
2809      * in the lookahead window, rather than placing n into the buffer
2810      * and then starting to square it, we have already computed n^2
2811      * to compute the odd-powers table, so we can place that into
2812      * the buffer and save a squaring.
2813      *
2814      * This means that if you have a k-bit window, to compute n^z,
2815      * where z is the high k bits of the exponent, 1/2 of the time
2816      * it requires no squarings.  1/4 of the time, it requires 1
2817      * squaring, ... 1/2^(k-1) of the time, it reqires k-2 squarings.
2818      * And the remaining 1/2^(k-1) of the time, the top k bits are a
2819      * 1 followed by k-1 0 bits, so it again only requires k-2
2820      * squarings, not k-1.  The average of these is 1.  Add that
2821      * to the one squaring we have to do to compute the table,
2822      * and you'll see that a k-bit window saves k-2 squarings
2823      * as well as reducing the multiplies.  (It actually doesn't
2824      * hurt in the case k = 1, either.)
2825      */
2826         // Special case for exponent of one
2827         if (y.equals(ONE))
2828             return this;
2829 
2830         // Special case for base of zero
2831         if (_signum == 0)
2832             return ZERO;
2833 
2834         int[] base = mag.dup;
2835         int[] exp = y.mag;
2836         int[] mod = z.mag;
2837         int modLen = cast(int)mod.length;
2838 
2839         // Make modLen even. It is conventional to use a cryptographic
2840         // modulus that is 512, 768, 1024, or 2048 bits, so this code
2841         // will not normally be executed. However, it is necessary for
2842         // the correct functioning of the HotSpot intrinsics.
2843         if ((modLen & 1) != 0) {
2844             int[] x = new int[modLen + 1];
2845             // System.arraycopy(mod, 0, x, 1, modLen);
2846             x[1 .. modLen+1] = mod[0 .. modLen];
2847             mod = x;
2848             modLen++;
2849         }
2850 
2851         // Select an appropriate window size
2852         int wbits = 0;
2853         int ebits = bitLength(exp, cast(int)exp.length);
2854         // if exponent is 65537 (0x10001), use minimum window size
2855         if ((ebits != 17) || (exp[0] != 65537)) {
2856             while (ebits > bnExpModThreshTable[wbits]) {
2857                 wbits++;
2858             }
2859         }
2860 
2861         // Calculate appropriate table size
2862         int tblmask = 1 << wbits;
2863 
2864         // Allocate table for precomputed odd powers of base in Montgomery form
2865         int[][] table = new int[][tblmask];
2866         for (int i=0; i < tblmask; i++)
2867             table[i] = new int[modLen];
2868 
2869         // Compute the modular inverse of the least significant 64-bit
2870         // digit of the modulus
2871         long n0 = (mod[modLen-1] & LONG_MASK) + ((mod[modLen-2] & LONG_MASK) << 32);
2872         long inv = -MutableBigInteger.inverseMod64(n0);
2873 
2874         // Convert base to Montgomery form
2875         int[] a = leftShift(base, cast(int)base.length, modLen << 5);
2876 
2877         MutableBigInteger q = new MutableBigInteger(),
2878                           a2 = new MutableBigInteger(a),
2879                           b2 = new MutableBigInteger(mod);
2880         b2.normalize(); // MutableBigInteger.divide() assumes that its
2881                         // divisor is in normal form.
2882 
2883         MutableBigInteger r= a2.divide(b2, q);
2884         table[0] = r.toIntArray();
2885 
2886         // Pad table[0] with leading zeros so its length is at least modLen
2887         if (table[0].length < modLen) {
2888            size_t len = table[0].length;
2889            size_t offset = modLen - len;
2890            int[] t2 = new int[modLen];
2891            t2[offset .. offset+len] = table[0][0 .. $];
2892         //    System.arraycopy(table[0], 0, t2, offset, table[0].length);
2893 
2894            table[0] = t2;
2895         }
2896 
2897         // Set b to the square of the base
2898         int[] b = montgomerySquare(table[0], mod, modLen, inv, null);
2899 
2900         // Set t to high half of b
2901         int[] t = b[0..modLen].dup; // Arrays.copyOf(b, modLen);
2902 
2903         // Fill in the table with odd powers of the base
2904         for (int i=1; i < tblmask; i++) {
2905             table[i] = montgomeryMultiply(t, table[i-1], mod, modLen, inv, null);
2906         }
2907 
2908         // Pre load the window that slides over the exponent
2909         int bitpos = 1 << ((ebits-1) & (32-1));
2910 
2911         int buf = 0;
2912         int elen = cast(int)exp.length;
2913         int eIndex = 0;
2914         for (int i = 0; i <= wbits; i++) {
2915             buf = (buf << 1) | (((exp[eIndex] & bitpos) != 0)?1:0);
2916             bitpos >>>= 1;
2917             if (bitpos == 0) {
2918                 eIndex++;
2919                 bitpos = 1 << (32-1);
2920                 elen--;
2921             }
2922         }
2923 
2924         int multpos = ebits;
2925 
2926         // The first iteration, which is hoisted out of the main loop
2927         ebits--;
2928         bool isone = true;
2929 
2930         multpos = ebits - wbits;
2931         while ((buf & 1) == 0) {
2932             buf >>>= 1;
2933             multpos++;
2934         }
2935 
2936         int[] mult = table[buf >>> 1];
2937 
2938         buf = 0;
2939         if (multpos == ebits)
2940             isone = false;
2941 
2942         // The main loop
2943         while (true) {
2944             ebits--;
2945             // Advance the window
2946             buf <<= 1;
2947 
2948             if (elen != 0) {
2949                 buf |= ((exp[eIndex] & bitpos) != 0) ? 1 : 0;
2950                 bitpos >>>= 1;
2951                 if (bitpos == 0) {
2952                     eIndex++;
2953                     bitpos = 1 << (32-1);
2954                     elen--;
2955                 }
2956             }
2957 
2958             // Examine the window for pending multiplies
2959             if ((buf & tblmask) != 0) {
2960                 multpos = ebits - wbits;
2961                 while ((buf & 1) == 0) {
2962                     buf >>>= 1;
2963                     multpos++;
2964                 }
2965                 mult = table[buf >>> 1];
2966                 buf = 0;
2967             }
2968 
2969             // Perform multiply
2970             if (ebits == multpos) {
2971                 if (isone) {
2972                     b = mult.dup;
2973                     isone = false;
2974                 } else {
2975                     t = b;
2976                     a = montgomeryMultiply(t, mult, mod, modLen, inv, a);
2977                     t = a; a = b; b = t;
2978                 }
2979             }
2980 
2981             // Check if done
2982             if (ebits == 0)
2983                 break;
2984 
2985             // Square the input
2986             if (!isone) {
2987                 t = b;
2988                 a = montgomerySquare(t, mod, modLen, inv, a);
2989                 t = a; a = b; b = t;
2990             }
2991         }
2992 
2993         // Convert result out of Montgomery form and return
2994         int[] t2 = new int[2*modLen];
2995         // System.arraycopy(b, 0, t2, modLen, modLen);
2996         t2[modLen .. modLen+modLen] = b[0 .. modLen];
2997         b = montReduce(t2, mod, modLen, cast(int)inv);
2998         // t2 = Arrays.copyOf(b, modLen);
2999         t2 = b[0 .. modLen].dup;
3000 
3001         return new BigInteger(1, t2);
3002     }
3003 
3004     /**
3005      * Montgomery reduce n, modulo mod.  This reduces modulo mod and divides
3006      * by 2^(32*mlen). Adapted from Colin Plumb's C library.
3007      */
3008     private static int[] montReduce(int[] n, int[] mod, int mlen, int inv) {
3009         int c=0;
3010         int len = mlen;
3011         int offset=0;
3012 
3013         do {
3014             int nEnd = n[n.length-1-offset];
3015             int carry = mulAdd(n, mod, offset, mlen, inv * nEnd);
3016             c += addOne(n, offset, mlen, carry);
3017             offset++;
3018         } while (--len > 0);
3019 
3020         while (c > 0)
3021             c += subN(n, mod, mlen);
3022 
3023         while (intArrayCmpToLen(n, mod, mlen) >= 0)
3024             subN(n, mod, mlen);
3025 
3026         return n;
3027     }
3028 
3029 
3030     /*
3031      * Returns -1, 0 or +1 as big-endian unsigned int array arg1 is less than,
3032      * equal to, or greater than arg2 up to length len.
3033      */
3034     private static int intArrayCmpToLen(int[] arg1, int[] arg2, int len) {
3035         for (int i=0; i < len; i++) {
3036             long b1 = arg1[i] & LONG_MASK;
3037             long b2 = arg2[i] & LONG_MASK;
3038             if (b1 < b2)
3039                 return -1;
3040             if (b1 > b2)
3041                 return 1;
3042         }
3043         return 0;
3044     }
3045 
3046     /**
3047      * Subtracts two numbers of same length, returning borrow.
3048      */
3049     private static int subN(int[] a, int[] b, int len) {
3050         long sum = 0;
3051 
3052         while (--len >= 0) {
3053             sum = (a[len] & LONG_MASK) -
3054                  (b[len] & LONG_MASK) + (sum >> 32);
3055             a[len] = cast(int)sum;
3056         }
3057 
3058         return cast(int)(sum >> 32);
3059     }
3060 
3061     /**
3062      * Multiply an array by one word k and add to result, return the carry
3063      */
3064     static int mulAdd(int[] ot, int[] input, int offset, int len, int k) {
3065         implMulAddCheck(ot, input, offset, len, k);
3066         return implMulAdd(ot, input, offset, len, k);
3067     }
3068 
3069     /**
3070      * Parameters validation.
3071      */
3072     private static void implMulAddCheck(int[] ot, int[] input, int offset, int len, int k) {
3073         if (len > input.length) {
3074             throw new IllegalArgumentException("input length is out of bound: " ~ len.to!string() ~ " > " ~ to!string(input.length));
3075         }
3076         if (offset < 0) {
3077             throw new IllegalArgumentException("input offset is invalid: " ~ offset.to!string());
3078         }
3079         if (offset > (ot.length - 1)) {
3080             throw new IllegalArgumentException("input offset is out of bound: " ~ offset.to!string() ~ " > " ~ to!string(ot.length - 1));
3081         }
3082         if (len > (ot.length - offset)) {
3083             throw new IllegalArgumentException("input len is out of bound: " ~ len.to!string() ~ " > " ~ to!string(ot.length - offset));
3084         }
3085     }
3086 
3087     /**
3088      * Java Runtime may use intrinsic for this method.
3089      */
3090     
3091     private static int implMulAdd(int[] output, int[] input, int offset, int len, int k) {
3092         long kLong = k & LONG_MASK;
3093         long carry = 0;
3094 
3095         offset = cast(int)output.length-offset - 1;
3096         for (int j=len-1; j >= 0; j--) {
3097             long product = (input[j] & LONG_MASK) * kLong +
3098                            (output[offset] & LONG_MASK) + carry;
3099             output[offset--] = cast(int)product;
3100             carry = product >>> 32;
3101         }
3102         return cast(int)carry;
3103     }
3104 
3105     /**
3106      * Add one word to the number a mlen words into a. Return the resulting
3107      * carry.
3108      */
3109     static int addOne(int[] a, int offset, int mlen, int carry) {
3110         offset = cast(int)a.length-1-mlen-offset;
3111         long t = (a[offset] & LONG_MASK) + (carry & LONG_MASK);
3112 
3113         a[offset] = cast(int)t;
3114         if ((t >>> 32) == 0)
3115             return 0;
3116         while (--mlen >= 0) {
3117             if (--offset < 0) { // Carry out of number
3118                 return 1;
3119             } else {
3120                 a[offset]++;
3121                 if (a[offset] != 0)
3122                     return 0;
3123             }
3124         }
3125         return 1;
3126     }
3127 
3128     /**
3129      * Returns a BigInteger whose value is (this ** exponent) mod (2**p)
3130      */
3131     private BigInteger modPow2(BigInteger exponent, int p) {
3132         /*
3133          * Perform exponentiation using repeated squaring trick, chopping off
3134          * high order bits as indicated by modulus.
3135          */
3136         BigInteger result = ONE;
3137         BigInteger baseToPow2 = this.mod2(p);
3138         int expOffset = 0;
3139 
3140         int limit = exponent.bitLength();
3141 
3142         if (this.testBit(0))
3143            limit = (p-1) < limit ? (p-1) : limit;
3144 
3145         while (expOffset < limit) {
3146             if (exponent.testBit(expOffset))
3147                 result = result.multiply(baseToPow2).mod2(p);
3148             expOffset++;
3149             if (expOffset < limit)
3150                 baseToPow2 = baseToPow2.square().mod2(p);
3151         }
3152 
3153         return result;
3154     }
3155 
3156     /**
3157      * Returns a BigInteger whose value is this mod(2**p).
3158      * Assumes that this {@code BigInteger >= 0} and {@code p > 0}.
3159      */
3160     private BigInteger mod2(int p) {
3161         if (bitLength() <= p)
3162             return this;
3163 
3164         // Copy remaining ints of mag
3165         int numInts = (p + 31) >>> 5;
3166         int[] mag = new int[numInts];
3167         // System.arraycopy(this.mag, (this.mag.length - numInts), mag, 0, numInts);
3168         mag[0..numInts] = this.mag[$-numInts .. $].dup;
3169 
3170         // Mask out any excess bits
3171         int excessBits = (numInts << 5) - p;
3172         mag[0] &= (1L << (32-excessBits)) - 1;
3173 
3174         return (mag[0] == 0 ? new BigInteger(1, mag) : new BigInteger(mag, 1));
3175     }
3176 
3177     /**
3178      * Returns a BigInteger whose value is {@code (this}<sup>-1</sup> {@code mod m)}.
3179      *
3180      * @param  m the modulus.
3181      * @return {@code this}<sup>-1</sup> {@code mod m}.
3182      * @throws ArithmeticException {@code  m} &le; 0, or this BigInteger
3183      *         has no multiplicative inverse mod m (that is, this BigInteger
3184      *         is not <i>relatively prime</i> to m).
3185      */
3186     BigInteger modInverse(BigInteger m) {
3187         if (m.signum != 1)
3188             throw new ArithmeticException("BigInteger: modulus not positive");
3189 
3190         if (m.equals(ONE))
3191             return ZERO;
3192 
3193         // Calculate (this mod m)
3194         BigInteger modVal = this;
3195         if (signum < 0 || (this.compareMagnitude(m) >= 0))
3196             modVal = this.mod(m);
3197 
3198         if (modVal.equals(ONE))
3199             return ONE;
3200 
3201         MutableBigInteger a = new MutableBigInteger(modVal);
3202         MutableBigInteger b = new MutableBigInteger(m);
3203 
3204         MutableBigInteger result = a.mutableModInverse(b);
3205         return result.toBigInteger(1);
3206     }
3207 
3208     // Shift Operations
3209 
3210     /**
3211      * Returns a BigInteger whose value is {@code (this << n)}.
3212      * The shift distance, {@code n}, may be negative, in which case
3213      * this method performs a right shift.
3214      * (Computes <code>floor(this * 2<sup>n</sup>)</code>.)
3215      *
3216      * @param  n shift distance, in bits.
3217      * @return {@code this << n}
3218      * @see #shiftRight
3219      */
3220     BigInteger shiftLeft(int n) {
3221         if (_signum == 0)
3222             return ZERO;
3223         if (n > 0) {
3224             return new BigInteger(shiftLeft(mag, n), signum);
3225         } else if (n == 0) {
3226             return this;
3227         } else {
3228             // Possible int overflow in (-n) is not a trouble,
3229             // because shiftRightImpl considers its argument unsigned
3230             return shiftRightImpl(-n);
3231         }
3232     }
3233 
3234     /**
3235      * Returns a magnitude array whose value is {@code (mag << n)}.
3236      * The shift distance, {@code n}, is considered unnsigned.
3237      * (Computes <code>this * 2<sup>n</sup></code>.)
3238      *
3239      * @param mag magnitude, the most-significant int ({@code mag[0]}) must be non-zero.
3240      * @param  n unsigned shift distance, in bits.
3241      * @return {@code mag << n}
3242      */
3243     private static int[] shiftLeft(int[] mag, int n) {
3244         int nInts = n >>> 5;
3245         int nBits = n & 0x1f;
3246         int magLen = cast(int)mag.length;
3247         int[] newMag = null;
3248 
3249         if (nBits == 0) {
3250             newMag = new int[magLen + nInts];
3251             // System.arraycopy(mag, 0, newMag, 0, magLen);
3252             newMag[0..magLen] = mag[0..magLen].dup;
3253         } else {
3254             int i = 0;
3255             int nBits2 = 32 - nBits;
3256             int highBits = mag[0] >>> nBits2;
3257             if (highBits != 0) {
3258                 newMag = new int[magLen + nInts + 1];
3259                 newMag[i++] = highBits;
3260             } else {
3261                 newMag = new int[magLen + nInts];
3262             }
3263             int j=0;
3264             while (j < magLen-1)
3265                 newMag[i++] = mag[j++] << nBits | mag[j] >>> nBits2;
3266             newMag[i] = mag[j] << nBits;
3267         }
3268         return newMag;
3269     }
3270 
3271     /**
3272      * Returns a BigInteger whose value is {@code (this >> n)}.  Sign
3273      * extension is performed.  The shift distance, {@code n}, may be
3274      * negative, in which case this method performs a left shift.
3275      * (Computes <code>floor(this / 2<sup>n</sup>)</code>.)
3276      *
3277      * @param  n shift distance, in bits.
3278      * @return {@code this >> n}
3279      * @see #shiftLeft
3280      */
3281     BigInteger shiftRight(int n) {
3282         if (_signum == 0)
3283             return ZERO;
3284         if (n > 0) {
3285             return shiftRightImpl(n);
3286         } else if (n == 0) {
3287             return this;
3288         } else {
3289             // Possible int overflow in {@code -n} is not a trouble,
3290             // because shiftLeft considers its argument unsigned
3291             return new BigInteger(shiftLeft(mag, -n), signum);
3292         }
3293     }
3294 
3295     /**
3296      * Returns a BigInteger whose value is {@code (this >> n)}. The shift
3297      * distance, {@code n}, is considered unsigned.
3298      * (Computes <code>floor(this * 2<sup>-n</sup>)</code>.)
3299      *
3300      * @param  n unsigned shift distance, in bits.
3301      * @return {@code this >> n}
3302      */
3303     private BigInteger shiftRightImpl(int n) {
3304         int nInts = n >>> 5;
3305         int nBits = n & 0x1f;
3306         int magLen = cast(int)mag.length;
3307         int[] newMag = null;
3308 
3309         // Special case: entire contents shifted off the end
3310         if (nInts >= magLen)
3311             return (signum >= 0 ? ZERO : negConst[1]);
3312 
3313         if (nBits == 0) {
3314             int newMagLen = magLen - nInts;
3315             // newMag = Arrays.copyOf(mag, newMagLen);
3316             newMag = mag[0..newMagLen].dup;
3317         } else {
3318             int i = 0;
3319             int highBits = mag[0] >>> nBits;
3320             if (highBits != 0) {
3321                 newMag = new int[magLen - nInts];
3322                 newMag[i++] = highBits;
3323             } else {
3324                 newMag = new int[magLen - nInts -1];
3325             }
3326 
3327             int nBits2 = 32 - nBits;
3328             int j=0;
3329             while (j < magLen - nInts - 1)
3330                 newMag[i++] = (mag[j++] << nBits2) | (mag[j] >>> nBits);
3331         }
3332 
3333         if (signum < 0) {
3334             // Find out whether any one-bits were shifted off the end.
3335             bool onesLost = false;
3336             for (int i=magLen-1, j=magLen-nInts; i >= j && !onesLost; i--)
3337                 onesLost = (mag[i] != 0);
3338             if (!onesLost && nBits != 0)
3339                 onesLost = (mag[magLen - nInts - 1] << (32 - nBits) != 0);
3340 
3341             if (onesLost)
3342                 newMag = javaIncrement(newMag);
3343         }
3344 
3345         return new BigInteger(newMag, signum);
3346     }
3347 
3348     int[] javaIncrement(int[] val) {
3349         int lastSum = 0;
3350         for (size_t i=val.length-1;  i >= 0 && lastSum == 0; i--)
3351             lastSum = (val[i] += 1);
3352         if (lastSum == 0) {
3353             val = new int[val.length+1];
3354             val[0] = 1;
3355         }
3356         return val;
3357     }
3358 
3359     // Bitwise Operations
3360 
3361     /**
3362      * Returns a BigInteger whose value is {@code (this & val)}.  (This
3363      * method returns a negative BigInteger if and only if this and val are
3364      * both negative.)
3365      *
3366      * @param val value to be AND'ed with this BigInteger.
3367      * @return {@code this & val}
3368      */
3369     BigInteger and(BigInteger val) {
3370         int[] result = new int[std.algorithm.max(intLength(), val.intLength())];
3371         for (int i=0; i < cast(int)result.length; i++)
3372             result[i] = (getInt(cast(int)result.length-i-1)
3373                          & val.getInt(cast(int)result.length-i-1));
3374 
3375         return valueOf(result);
3376     }
3377 
3378     /**
3379      * Returns a BigInteger whose value is {@code (this | val)}.  (This method
3380      * returns a negative BigInteger if and only if either this or val is
3381      * negative.)
3382      *
3383      * @param val value to be OR'ed with this BigInteger.
3384      * @return {@code this | val}
3385      */
3386     BigInteger or(BigInteger val) {
3387         int[] result = new int[std.algorithm.max(intLength(), val.intLength())];
3388         for (int i=0; i < cast(int)result.length; i++)
3389             result[i] = (getInt(cast(int)result.length-i-1)
3390                          | val.getInt(cast(int)result.length-i-1));
3391 
3392         return valueOf(result);
3393     }
3394 
3395     /**
3396      * Returns a BigInteger whose value is {@code (this ^ val)}.  (This method
3397      * returns a negative BigInteger if and only if exactly one of this and
3398      * val are negative.)
3399      *
3400      * @param val value to be XOR'ed with this BigInteger.
3401      * @return {@code this ^ val}
3402      */
3403     BigInteger xor(BigInteger val) {
3404         int[] result = new int[std.algorithm.max(intLength(), val.intLength())];
3405         for (int i=0; i < cast(int)result.length; i++)
3406             result[i] = (getInt(cast(int)result.length-i-1)
3407                          ^ val.getInt(cast(int)result.length-i-1));
3408 
3409         return valueOf(result);
3410     }
3411 
3412     /**
3413      * Returns a BigInteger whose value is {@code (~this)}.  (This method
3414      * returns a negative value if and only if this BigInteger is
3415      * non-negative.)
3416      *
3417      * @return {@code ~this}
3418      */
3419     BigInteger not() {
3420         int[] result = new int[intLength()];
3421         for (int i=0; i < cast(int)result.length; i++)
3422             result[i] = ~getInt(cast(int)result.length-i-1);
3423 
3424         return valueOf(result);
3425     }
3426 
3427     /**
3428      * Returns a BigInteger whose value is {@code (this & ~val)}.  This
3429      * method, which is equivalent to {@code and(val.not())}, is provided as
3430      * a convenience for masking operations.  (This method returns a negative
3431      * BigInteger if and only if {@code this} is negative and {@code val} is
3432      * positive.)
3433      *
3434      * @param val value to be complemented and AND'ed with this BigInteger.
3435      * @return {@code this & ~val}
3436      */
3437     BigInteger andNot(BigInteger val) {
3438         int[] result = new int[std.algorithm.max(intLength(), val.intLength())];
3439         for (int i=0; i < cast(int)result.length; i++)
3440             result[i] = (getInt(cast(int)result.length-i-1)
3441                          & ~val.getInt(cast(int)result.length-i-1));
3442 
3443         return valueOf(result);
3444     }
3445 
3446 
3447     // Single Bit Operations
3448 
3449     /**
3450      * Returns {@code true} if and only if the designated bit is set.
3451      * (Computes {@code ((this & (1<<n)) != 0)}.)
3452      *
3453      * @param  n index of bit to test.
3454      * @return {@code true} if and only if the designated bit is set.
3455      * @throws ArithmeticException {@code n} is negative.
3456      */
3457     bool testBit(int n) {
3458         if (n < 0)
3459             throw new ArithmeticException("Negative bit address");
3460 
3461         return (getInt(n >>> 5) & (1 << (n & 31))) != 0;
3462     }
3463 
3464     /**
3465      * Returns a BigInteger whose value is equivalent to this BigInteger
3466      * with the designated bit set.  (Computes {@code (this | (1<<n))}.)
3467      *
3468      * @param  n index of bit to set.
3469      * @return {@code this | (1<<n)}
3470      * @throws ArithmeticException {@code n} is negative.
3471      */
3472     BigInteger setBit(int n) {
3473         if (n < 0)
3474             throw new ArithmeticException("Negative bit address");
3475 
3476         int intNum = n >>> 5;
3477         int[] result = new int[std.algorithm.max(intLength(), intNum+2)];
3478 
3479         for (int i=0; i < cast(int)result.length; i++)
3480             result[result.length-i-1] = getInt(i);
3481 
3482         result[result.length-intNum-1] |= (1 << (n & 31));
3483 
3484         return valueOf(result);
3485     }
3486 
3487     /**
3488      * Returns a BigInteger whose value is equivalent to this BigInteger
3489      * with the designated bit cleared.
3490      * (Computes {@code (this & ~(1<<n))}.)
3491      *
3492      * @param  n index of bit to clear.
3493      * @return {@code this & ~(1<<n)}
3494      * @throws ArithmeticException {@code n} is negative.
3495      */
3496     BigInteger clearBit(int n) {
3497         if (n < 0)
3498             throw new ArithmeticException("Negative bit address");
3499 
3500         int intNum = n >>> 5;
3501         int[] result = new int[std.algorithm.max(intLength(), ((n + 1) >>> 5) + 1)];
3502 
3503         for (int i=0; i < cast(int)result.length; i++)
3504             result[result.length-i-1] = getInt(i);
3505 
3506         result[result.length-intNum-1] &= ~(1 << (n & 31));
3507 
3508         return valueOf(result);
3509     }
3510 
3511     /**
3512      * Returns a BigInteger whose value is equivalent to this BigInteger
3513      * with the designated bit flipped.
3514      * (Computes {@code (this ^ (1<<n))}.)
3515      *
3516      * @param  n index of bit to flip.
3517      * @return {@code this ^ (1<<n)}
3518      * @throws ArithmeticException {@code n} is negative.
3519      */
3520     BigInteger flipBit(int n) {
3521         if (n < 0)
3522             throw new ArithmeticException("Negative bit address");
3523 
3524         int intNum = n >>> 5;
3525         int[] result = new int[std.algorithm.max(intLength(), intNum+2)];
3526 
3527         for (int i=0; i < cast(int)result.length; i++)
3528             result[result.length-i-1] = getInt(i);
3529 
3530         result[result.length-intNum-1] ^= (1 << (n & 31));
3531 
3532         return valueOf(result);
3533     }
3534 
3535     /**
3536      * Returns the index of the rightmost (lowest-order) one bit in this
3537      * BigInteger (the number of zero bits to the right of the rightmost
3538      * one bit).  Returns -1 if this BigInteger contains no one bits.
3539      * (Computes {@code (this == 0? -1 : log2(this & -this))}.)
3540      *
3541      * @return index of the rightmost one bit in this BigInteger.
3542      */
3543     int getLowestSetBit() {
3544         int lsb = lowestSetBitPlusTwo - 2;
3545         if (lsb == -2) {  // lowestSetBit not initialized yet
3546             lsb = 0;
3547             if (_signum == 0) {
3548                 lsb -= 1;
3549             } else {
3550                 // Search for lowest order nonzero int
3551                 int i,b;
3552                 for (i=0; (b = getInt(i)) == 0; i++) {}
3553                 lsb += (i << 5) + Integer.numberOfTrailingZeros(b);
3554             }
3555             lowestSetBitPlusTwo = lsb + 2;
3556         }
3557         return lsb;
3558     }
3559 
3560 
3561     // Miscellaneous Bit Operations
3562 
3563     /**
3564      * Returns the number of bits in the minimal two's-complement
3565      * representation of this BigInteger, <em>excluding</em> a sign bit.
3566      * For positive BigIntegers, this is equivalent to the number of bits in
3567      * the ordinary binary representation.  (Computes
3568      * {@code (ceil(log2(this < 0 ? -this : this+1)))}.)
3569      *
3570      * @return number of bits in the minimal two's-complement
3571      *         representation of this BigInteger, <em>excluding</em> a sign bit.
3572      */
3573     int bitLength() {
3574         int n = bitLengthPlusOne - 1;
3575         if (n == -1) { // bitLength not initialized yet
3576             int[] m = mag;
3577             int len = cast(int)m.length;
3578             if (len == 0) {
3579                 n = 0; // offset by one to initialize
3580             }  else {
3581                 // Calculate the bit length of the magnitude
3582                 int magBitLength = ((len - 1) << 5) + bitLengthForInt(mag[0]);
3583                  if (signum < 0) {
3584                      // Check if magnitude is a power of two
3585                      bool pow2 = (Integer.bitCount(mag[0]) == 1);
3586                      for (int i=1; i< len && pow2; i++)
3587                          pow2 = (mag[i] == 0);
3588 
3589                      n = (pow2 ? magBitLength -1 : magBitLength);
3590                  } else {
3591                      n = magBitLength;
3592                  }
3593             }
3594             bitLengthPlusOne = n + 1;
3595         }
3596         return n;
3597     }
3598 
3599     /**
3600      * Returns the number of bits in the two's complement representation
3601      * of this BigInteger that differ from its sign bit.  This method is
3602      * useful when implementing bit-vector style sets atop BigIntegers.
3603      *
3604      * @return number of bits in the two's complement representation
3605      *         of this BigInteger that differ from its sign bit.
3606      */
3607     int bitCount() {
3608         int bc = bitCountPlusOne - 1;
3609         if (bc == -1) {  // bitCount not initialized yet
3610             bc = 0;      // offset by one to initialize
3611             // Count the bits in the magnitude
3612             for (int i=0; i < mag.length; i++)
3613                 bc += Integer.bitCount(mag[i]);
3614             if (signum < 0) {
3615                 // Count the trailing zeros in the magnitude
3616                 int magTrailingZeroCount = 0, j;
3617                 for (j=cast(int)mag.length-1; mag[j] == 0; j--)
3618                     magTrailingZeroCount += 32;
3619                 magTrailingZeroCount += Integer.numberOfTrailingZeros(mag[j]);
3620                 bc += magTrailingZeroCount - 1;
3621             }
3622             bitCountPlusOne = bc + 1;
3623         }
3624         return bc;
3625     }
3626 
3627     // Primality Testing
3628 
3629     /**
3630      * Returns {@code true} if this BigInteger is probably prime,
3631      * {@code false} if it's definitely composite.  If
3632      * {@code certainty} is &le; 0, {@code true} is
3633      * returned.
3634      *
3635      * @param  certainty a measure of the uncertainty that the caller is
3636      *         willing to tolerate: if the call returns {@code true}
3637      *         the probability that this BigInteger is prime exceeds
3638      *         (1 - 1/2<sup>{@code certainty}</sup>).  The execution time of
3639      *         this method is proportional to the value of this parameter.
3640      * @return {@code true} if this BigInteger is probably prime,
3641      *         {@code false} if it's definitely composite.
3642      */
3643     bool isProbablePrime(int certainty) {
3644         if (certainty <= 0)
3645             return true;
3646         BigInteger w = this.abs();
3647         if (w.equals(TWO))
3648             return true;
3649         if (!w.testBit(0) || w.equals(ONE))
3650             return false;
3651 
3652         return w.primeToCertainty(certainty, null);
3653     }
3654 
3655     // Comparison Operations
3656 
3657     /**
3658      * Compares this BigInteger with the specified BigInteger.  This
3659      * method is provided in preference to individual methods for each
3660      * of the six bool comparison operators ({@literal <}, ==,
3661      * {@literal >}, {@literal >=}, !=, {@literal <=}).  The suggested
3662      * idiom for performing these comparisons is: {@code
3663      * (x.compareTo(y)} &lt;<i>op</i>&gt; {@code 0)}, where
3664      * &lt;<i>op</i>&gt; is one of the six comparison operators.
3665      *
3666      * @param  val BigInteger to which this BigInteger is to be compared.
3667      * @return -1, 0 or 1 as this BigInteger is numerically less than, equal
3668      *         to, or greater than {@code val}.
3669      */
3670     int compareTo(BigInteger val) {
3671         if (_signum == val.signum) {
3672             switch (signum) {
3673             case 1:
3674                 return compareMagnitude(val);
3675             case -1:
3676                 return val.compareMagnitude(this);
3677             default:
3678                 return 0;
3679             }
3680         }
3681         return signum > val.signum ? 1 : -1;
3682     }
3683 
3684     /**
3685      * Compares the magnitude array of this BigInteger with the specified
3686      * BigInteger's. This is the version of compareTo ignoring sign.
3687      *
3688      * @param val BigInteger whose magnitude array to be compared.
3689      * @return -1, 0 or 1 as this magnitude array is less than, equal to or
3690      *         greater than the magnitude aray for the specified BigInteger's.
3691      */
3692     final int compareMagnitude(BigInteger val) {
3693         int[] m1 = mag;
3694         int len1 = cast(int)m1.length;
3695         int[] m2 = val.mag;
3696         int len2 = cast(int)m2.length;
3697         if (len1 < len2)
3698             return -1;
3699         if (len1 > len2)
3700             return 1;
3701         for (int i = 0; i < len1; i++) {
3702             int a = m1[i];
3703             int b = m2[i];
3704             if (a != b)
3705                 return ((a & LONG_MASK) < (b & LONG_MASK)) ? -1 : 1;
3706         }
3707         return 0;
3708     }
3709 
3710     /**
3711      * Version of compareMagnitude that compares magnitude with long value.
3712      * val can't be long.min.
3713      */
3714     final int compareMagnitude(long val) {
3715         assert(val != long.min);
3716         int[] m1 = mag;
3717         int len = cast(int)m1.length;
3718         if (len > 2) {
3719             return 1;
3720         }
3721         if (val < 0) {
3722             val = -val;
3723         }
3724         int highWord = cast(int)(val >>> 32);
3725         if (highWord == 0) {
3726             if (len < 1)
3727                 return -1;
3728             if (len > 1)
3729                 return 1;
3730             int a = m1[0];
3731             int b = cast(int)val;
3732             if (a != b) {
3733                 return ((a & LONG_MASK) < (b & LONG_MASK))? -1 : 1;
3734             }
3735             return 0;
3736         } else {
3737             if (len < 2)
3738                 return -1;
3739             int a = m1[0];
3740             int b = highWord;
3741             if (a != b) {
3742                 return ((a & LONG_MASK) < (b & LONG_MASK))? -1 : 1;
3743             }
3744             a = m1[1];
3745             b = cast(int)val;
3746             if (a != b) {
3747                 return ((a & LONG_MASK) < (b & LONG_MASK))? -1 : 1;
3748             }
3749             return 0;
3750         }
3751     }
3752 
3753     /**
3754      * Compares this BigInteger with the specified Object for equality.
3755      *
3756      * @param  x Object to which this BigInteger is to be compared.
3757      * @return {@code true} if and only if the specified Object is a
3758      *         BigInteger whose value is numerically equal to this BigInteger.
3759      */
3760     bool equals(Object x) {
3761         return opEquals(x);
3762     }
3763 
3764     override bool opEquals(Object x) {
3765         // This test is just an optimization, which may or may not help
3766         if (x is this)
3767             return true;
3768 
3769         BigInteger xInt = cast(BigInteger) x;
3770         if(xInt is null)
3771             return false;
3772         if (xInt.signum != signum)
3773             return false;
3774 
3775         int[] m = mag;
3776         int len = cast(int)m.length;
3777         int[] xm = xInt.mag;
3778         if (len != xm.length)
3779             return false;
3780 
3781         for (int i = 0; i < len; i++)
3782             if (xm[i] != m[i])
3783                 return false;
3784 
3785         return true;
3786     }
3787 
3788     /**
3789      * Returns the minimum of this BigInteger and {@code val}.
3790      *
3791      * @param  val value with which the minimum is to be computed.
3792      * @return the BigInteger whose value is the lesser of this BigInteger and
3793      *         {@code val}.  If they are equal, either may be returned.
3794      */
3795     BigInteger min(BigInteger val) {
3796         return (compareTo(val) < 0 ? this : val);
3797     }
3798 
3799     /**
3800      * Returns the maximum of this BigInteger and {@code val}.
3801      *
3802      * @param  val value with which the maximum is to be computed.
3803      * @return the BigInteger whose value is the greater of this and
3804      *         {@code val}.  If they are equal, either may be returned.
3805      */
3806     BigInteger max(BigInteger val) {
3807         return (compareTo(val) > 0 ? this : val);
3808     }
3809 
3810 
3811     // Hash Function
3812 
3813     /**
3814      * Returns the hash code for this BigInteger.
3815      *
3816      * @return hash code for this BigInteger.
3817      */
3818     size_t hashCode() {
3819         return toHash();
3820     }
3821 
3822     override size_t toHash() @trusted nothrow {
3823         size_t hashCode = 0;
3824 
3825         for (size_t i=0; i < mag.length; i++)
3826             hashCode = cast(size_t)(31*hashCode + (mag[i] & LONG_MASK));
3827 
3828         return hashCode * _signum;
3829     }
3830 
3831     /**
3832      * Returns the string representation of this BigInteger in the
3833      * given radix.  If the radix is outside the range from {@link
3834      * Character#MIN_RADIX} to {@link Character#MAX_RADIX} inclusive,
3835      * it will default to 10 (as is the case for
3836      * {@code Integer.toString}).  The digit-to-character mapping
3837      * provided by {@code Char.forDigit} is used, and a minus
3838      * sign is prepended if appropriate.  (This representation is
3839      * compatible with the {@link #BigInteger(string, int) (string,
3840      * int)} constructor.)
3841      *
3842      * @param  radix  radix of the string representation.
3843      * @return string representation of this BigInteger in the given radix.
3844      * @see    Integer#toString
3845      * @see    Character#forDigit
3846      * @see    #BigInteger(java.lang.string, int)
3847      */
3848     string toString(int radix) {
3849         if (_signum == 0)
3850             return "0";
3851         if (radix < Char.MIN_RADIX || radix > Char.MAX_RADIX)
3852             radix = 10;
3853 
3854         // If it's small enough, use smallToString.
3855         if (mag.length <= SCHOENHAGE_BASE_CONVERSION_THRESHOLD)
3856            return smallToString(radix);
3857 
3858         // Otherwise use recursive toString, which requires positive arguments.
3859         // The results will be concatenated into this StringBuilder
3860         StringBuilder sb = new StringBuilder();
3861         string r;
3862         if (signum < 0) {
3863             toString(this.negate(), sb, radix, 0);
3864             // sb.insert(0, '-');
3865             r = "-" ~ sb.toString();
3866         }
3867         else {
3868             toString(this, sb, radix, 0);
3869             r = sb.toString();
3870         }
3871 
3872         return r;
3873     }
3874 
3875     /** This method is used to perform toString when arguments are small. */
3876     private string smallToString(int radix) {
3877         if (_signum == 0) {
3878             return "0";
3879         }
3880 
3881         // Compute upper bound on number of digit groups and allocate space
3882         int maxNumDigitGroups = cast(int)(4*mag.length + 6)/7;
3883         string[] digitGroup = new string[maxNumDigitGroups];
3884 
3885         // Translate number to string, a digit group at a time
3886         BigInteger tmp = this.abs();
3887         int numGroups = 0;
3888         while (tmp.signum != 0) {
3889             BigInteger d = longRadix[radix];
3890 
3891             MutableBigInteger q = new MutableBigInteger(),
3892                               a = new MutableBigInteger(tmp.mag),
3893                               b = new MutableBigInteger(d.mag);
3894             MutableBigInteger r = a.divide(b, q);
3895             BigInteger q2 = q.toBigInteger(tmp.signum * d.signum);
3896             BigInteger r2 = r.toBigInteger(tmp.signum * d.signum);
3897 
3898             digitGroup[numGroups++] = to!string(r2.longValue(), radix);
3899             tmp = q2;
3900         }
3901 
3902         // Put sign (if any) and first digit group into result buffer
3903         StringBuilder buf = new StringBuilder(numGroups*digitsPerLong[radix]+1);
3904         if (signum < 0) {
3905             buf.append('-');
3906         }
3907         buf.append(digitGroup[numGroups-1]);
3908 
3909         // Append remaining digit groups padded with leading zeros
3910         for (int i=numGroups-2; i >= 0; i--) {
3911             // Prepend (any) leading zeros for this digit group
3912             int numLeadingZeros = digitsPerLong[radix] - cast(int)digitGroup[i].length;
3913             if (numLeadingZeros != 0) {
3914                 buf.append(zeros[numLeadingZeros]);
3915             }
3916             buf.append(digitGroup[i]);
3917         }
3918         return buf.toString();
3919     }
3920 
3921     /**
3922      * Converts the specified BigInteger to a string and appends to
3923      * {@code sb}.  This implements the recursive Schoenhage algorithm
3924      * for base conversions.
3925      * <p>
3926      * See Knuth, Donald,  _The Art of Computer Programming_, Vol. 2,
3927      * Answers to Exercises (4.4) Question 14.
3928      *
3929      * @param u      The number to convert to a string.
3930      * @param sb     The StringBuilder that will be appended to in place.
3931      * @param radix  The base to convert to.
3932      * @param digits The minimum number of digits to pad to.
3933      */
3934     private static void toString(BigInteger u, StringBuilder sb, int radix,
3935                                  int digits) {
3936         // If we're smaller than a certain threshold, use the smallToString
3937         // method, padding with leading zeroes when necessary.
3938         if (u.mag.length <= SCHOENHAGE_BASE_CONVERSION_THRESHOLD) {
3939             string s = u.smallToString(radix);
3940 
3941             // Pad with internal zeros if necessary.
3942             // Don't pad if we're at the beginning of the string.
3943             if ((s.length < digits) && (sb.length > 0)) {
3944                 for (size_t i=s.length; i < digits; i++) {
3945                     sb.append('0');
3946                 }
3947             }
3948 
3949             sb.append(s);
3950             return;
3951         }
3952 
3953         int b, n;
3954         b = u.bitLength();
3955 
3956         // Calculate a value for n in the equation radix^(2^n) = u
3957         // and subtract 1 from that value.  This is used to find the
3958         // cache index that contains the best value to divide u.
3959         n = cast(int) std.math.round(std.math.log(b * LOG_TWO / logCache[radix]) / LOG_TWO - 1.0);
3960         BigInteger v = getRadixConversionCache(radix, n);
3961         BigInteger[] results;
3962         results = u.divideAndRemainder(v);
3963 
3964         int expectedDigits = 1 << n;
3965 
3966         // Now recursively build the two halves of each number.
3967         toString(results[0], sb, radix, digits-expectedDigits);
3968         toString(results[1], sb, radix, expectedDigits);
3969     }
3970 
3971     /**
3972      * Returns the value radix^(2^exponent) from the cache.
3973      * If this value doesn't already exist in the cache, it is added.
3974      * <p>
3975      * This could be changed to a more complicated caching method using
3976      * {@code Future}.
3977      */
3978     private static BigInteger getRadixConversionCache(int radix, int exponent) {
3979         BigInteger[] cacheLine = powerCache[radix]; // read
3980         if (exponent < cacheLine.length) {
3981             return cacheLine[exponent];
3982         }
3983 
3984         int oldLength = cast(int)cacheLine.length;
3985         BigInteger[] oldCacheLine = cacheLine;
3986         cacheLine = new BigInteger[exponent + 1];
3987         cacheLine[0..oldLength] = oldCacheLine[0..$];
3988         // cacheLine = Arrays.copyOf(cacheLine, exponent + 1);
3989         for (int i = oldLength; i <= exponent; i++) {
3990             cacheLine[i] = cacheLine[i - 1].pow(2);
3991         }
3992 
3993         BigInteger[][] pc = powerCache; // read again
3994         if (exponent >= pc[radix].length) {
3995             pc = pc.dup;
3996             pc[radix] = cacheLine;
3997             powerCache = pc; // write, publish
3998         }
3999         return cacheLine[exponent];
4000     }
4001 
4002     /* zero[i] is a string of i consecutive zeros. */
4003     private __gshared static string[] zeros;
4004     shared static this() {
4005         zeros = new string[64];
4006         zeros[63] = "000000000000000000000000000000000000000000000000000000000000000";
4007         for (int i=0; i < 63; i++)
4008             zeros[i] = zeros[63][0 .. i];
4009     }
4010 
4011     /**
4012      * Returns the decimal string representation of this BigInteger.
4013      * The digit-to-character mapping provided by
4014      * {@code Char.forDigit} is used, and a minus sign is
4015      * prepended if appropriate.  (This representation is compatible
4016      * with the {@link #BigInteger(string) (string)} constructor, and
4017      * allows for string concatenation with Java's + operator.)
4018      *
4019      * @return decimal string representation of this BigInteger.
4020      * @see    Character#forDigit
4021      * @see    #BigInteger(java.lang.string)
4022      */
4023     override string toString() {
4024         return toString(10);
4025     }
4026 
4027     /**
4028      * Returns a byte array containing the two's-complement
4029      * representation of this BigInteger.  The byte array will be in
4030      * <i>big-endian</i> byte-order: the most significant byte is in
4031      * the zeroth element.  The array will contain the minimum number
4032      * of bytes required to represent this BigInteger, including at
4033      * least one sign bit, which is {@code (ceil((this.bitLength() +
4034      * 1)/8))}.  (This representation is compatible with the
4035      * {@link #BigInteger(byte[]) (byte[])} constructor.)
4036      *
4037      * @return a byte array containing the two's-complement representation of
4038      *         this BigInteger.
4039      * @see    #BigInteger(byte[])
4040      */
4041     byte[] toByteArray() {
4042         int byteLen = bitLength()/8 + 1;
4043         byte[] byteArray = new byte[byteLen];
4044 
4045         for (int i=byteLen-1, bytesCopied=4, nextInt=0, intIndex=0; i >= 0; i--) {
4046             if (bytesCopied == 4) {
4047                 nextInt = getInt(intIndex++);
4048                 bytesCopied = 1;
4049             } else {
4050                 nextInt >>>= 8;
4051                 bytesCopied++;
4052             }
4053             byteArray[i] = cast(byte)nextInt;
4054         }
4055         return byteArray;
4056     }
4057 
4058     /**
4059      * Converts this BigInteger to an {@code int}.  This
4060      * conversion is analogous to a
4061      * <i>narrowing primitive conversion</i> from {@code long} to
4062      * {@code int} as defined in
4063      * <cite>The Java&trade; Language Specification</cite>:
4064      * if this BigInteger is too big to fit in an
4065      * {@code int}, only the low-order 32 bits are returned.
4066      * Note that this conversion can lose information about the
4067      * overall magnitude of the BigInteger value as well as return a
4068      * result with the opposite sign.
4069      *
4070      * @return this BigInteger converted to an {@code int}.
4071      * @see #intValueExact()
4072      * @jls 5.1.3 Narrowing Primitive Conversion
4073      */
4074     int intValue() {
4075         int result = 0;
4076         result = getInt(0);
4077         return result;
4078     }
4079 
4080     /**
4081      * Converts this BigInteger to a {@code long}.  This
4082      * conversion is analogous to a
4083      * <i>narrowing primitive conversion</i> from {@code long} to
4084      * {@code int} as defined in
4085      * <cite>The Java&trade; Language Specification</cite>:
4086      * if this BigInteger is too big to fit in a
4087      * {@code long}, only the low-order 64 bits are returned.
4088      * Note that this conversion can lose information about the
4089      * overall magnitude of the BigInteger value as well as return a
4090      * result with the opposite sign.
4091      *
4092      * @return this BigInteger converted to a {@code long}.
4093      * @see #longValueExact()
4094      * @jls 5.1.3 Narrowing Primitive Conversion
4095      */
4096     long longValue() {
4097         long result = 0;
4098 
4099         for (int i=1; i >= 0; i--)
4100             result = (result << 32) + (getInt(i) & LONG_MASK);
4101         return result;
4102     }
4103 
4104     /**
4105      * Converts this BigInteger to a {@code float}.  This
4106      * conversion is similar to the
4107      * <i>narrowing primitive conversion</i> from {@code double} to
4108      * {@code float} as defined in
4109      * <cite>The Java&trade; Language Specification</cite>:
4110      * if this BigInteger has too great a magnitude
4111      * to represent as a {@code float}, it will be converted to
4112      * {@link Float#NEGATIVE_INFINITY} or {@link
4113      * Float#POSITIVE_INFINITY} as appropriate.  Note that even when
4114      * the return value is finite, this conversion can lose
4115      * information about the precision of the BigInteger value.
4116      *
4117      * @return this BigInteger converted to a {@code float}.
4118      * @jls 5.1.3 Narrowing Primitive Conversion
4119      */
4120     float floatValue() {
4121         if (_signum == 0) {
4122             return 0.0f;
4123         }
4124 
4125         int exponent =cast(int)(cast(int)(mag.length - 1) << 5) + bitLengthForInt(mag[0]) - 1;
4126 
4127         // exponent == floor(log2(abs(this)))
4128         if (exponent < Long.SIZE - 1) {
4129             return longValue();
4130         } else if (exponent > Float.MAX_EXPONENT) {
4131             return signum > 0 ? Float.POSITIVE_INFINITY : Float.NEGATIVE_INFINITY;
4132         }
4133 
4134         /*
4135          * We need the top SIGNIFICAND_WIDTH bits, including the "implicit"
4136          * one bit. To make rounding easier, we pick out the top
4137          * SIGNIFICAND_WIDTH + 1 bits, so we have one to help us round up or
4138          * down. twiceSignifFloor will contain the top SIGNIFICAND_WIDTH + 1
4139          * bits, and signifFloor the top SIGNIFICAND_WIDTH.
4140          *
4141          * It helps to consider the real number signif = abs(this) *
4142          * 2^(SIGNIFICAND_WIDTH - 1 - exponent).
4143          */
4144         int shift = exponent - FloatConsts.SIGNIFICAND_WIDTH;
4145 
4146         int twiceSignifFloor;
4147         // twiceSignifFloor will be == abs().shiftRight(shift).intValue()
4148         // We do the shift into an int directly to improve performance.
4149 
4150         int nBits = shift & 0x1f;
4151         int nBits2 = 32 - nBits;
4152 
4153         if (nBits == 0) {
4154             twiceSignifFloor = mag[0];
4155         } else {
4156             twiceSignifFloor = mag[0] >>> nBits;
4157             if (twiceSignifFloor == 0) {
4158                 twiceSignifFloor = (mag[0] << nBits2) | (mag[1] >>> nBits);
4159             }
4160         }
4161 
4162         int signifFloor = twiceSignifFloor >> 1;
4163         signifFloor &= FloatConsts.SIGNIF_BIT_MASK; // remove the implied bit
4164 
4165         /*
4166          * We round up if either the fractional part of signif is strictly
4167          * greater than 0.5 (which is true if the 0.5 bit is set and any lower
4168          * bit is set), or if the fractional part of signif is >= 0.5 and
4169          * signifFloor is odd (which is true if both the 0.5 bit and the 1 bit
4170          * are set). This is equivalent to the desired HALF_EVEN rounding.
4171          */
4172         bool increment = (twiceSignifFloor & 1) != 0
4173                 && ((signifFloor & 1) != 0 || abs().getLowestSetBit() < shift);
4174         int signifRounded = increment ? signifFloor + 1 : signifFloor;
4175         int bits = ((exponent + FloatConsts.EXP_BIAS))
4176                 << (FloatConsts.SIGNIFICAND_WIDTH - 1);
4177         bits += signifRounded;
4178         /*
4179          * If signifRounded == 2^24, we'd need to set all of the significand
4180          * bits to zero and add 1 to the exponent. This is exactly the behavior
4181          * we get from just adding signifRounded to bits directly. If the
4182          * exponent is Float.MAX_EXPONENT, we round up (correctly) to
4183          * Float.POSITIVE_INFINITY.
4184          */
4185         bits |= signum & FloatConsts.SIGN_BIT_MASK;
4186         return Float.intBitsToFloat(bits);
4187     }
4188 
4189     /**
4190      * Converts this BigInteger to a {@code double}.  This
4191      * conversion is similar to the
4192      * <i>narrowing primitive conversion</i> from {@code double} to
4193      * {@code float} as defined in
4194      * <cite>The Java&trade; Language Specification</cite>:
4195      * if this BigInteger has too great a magnitude
4196      * to represent as a {@code double}, it will be converted to
4197      * {@link Double#NEGATIVE_INFINITY} or {@link
4198      * Double#POSITIVE_INFINITY} as appropriate.  Note that even when
4199      * the return value is finite, this conversion can lose
4200      * information about the precision of the BigInteger value.
4201      *
4202      * @return this BigInteger converted to a {@code double}.
4203      * @jls 5.1.3 Narrowing Primitive Conversion
4204      */
4205     double doubleValue() {
4206         if (_signum == 0) {
4207             return 0.0;
4208         }
4209 
4210         int exponent = (cast(int)(mag.length - 1) << 5) + bitLengthForInt(mag[0]) - 1;
4211 
4212         // exponent == floor(log2(abs(this))Double)
4213         if (exponent < Long.SIZE - 1) {
4214             return longValue();
4215         } else if (exponent > Double.MAX_EXPONENT) {
4216             return signum > 0 ? Double.POSITIVE_INFINITY : Double.NEGATIVE_INFINITY;
4217         }
4218 
4219         /*
4220          * We need the top SIGNIFICAND_WIDTH bits, including the "implicit"
4221          * one bit. To make rounding easier, we pick out the top
4222          * SIGNIFICAND_WIDTH + 1 bits, so we have one to help us round up or
4223          * down. twiceSignifFloor will contain the top SIGNIFICAND_WIDTH + 1
4224          * bits, and signifFloor the top SIGNIFICAND_WIDTH.
4225          *
4226          * It helps to consider the real number signif = abs(this) *
4227          * 2^(SIGNIFICAND_WIDTH - 1 - exponent).
4228          */
4229         int shift = exponent - DoubleConsts.SIGNIFICAND_WIDTH;
4230 
4231         long twiceSignifFloor;
4232         // twiceSignifFloor will be == abs().shiftRight(shift).longValue()
4233         // We do the shift into a long directly to improve performance.
4234 
4235         int nBits = shift & 0x1f;
4236         int nBits2 = 32 - nBits;
4237 
4238         int highBits;
4239         int lowBits;
4240         if (nBits == 0) {
4241             highBits = mag[0];
4242             lowBits = mag[1];
4243         } else {
4244             highBits = mag[0] >>> nBits;
4245             lowBits = (mag[0] << nBits2) | (mag[1] >>> nBits);
4246             if (highBits == 0) {
4247                 highBits = lowBits;
4248                 lowBits = (mag[1] << nBits2) | (mag[2] >>> nBits);
4249             }
4250         }
4251 
4252         twiceSignifFloor = ((highBits & LONG_MASK) << 32)
4253                 | (lowBits & LONG_MASK);
4254 
4255         long signifFloor = twiceSignifFloor >> 1;
4256         signifFloor &= DoubleConsts.SIGNIF_BIT_MASK; // remove the implied bit
4257 
4258         /*
4259          * We round up if either the fractional part of signif is strictly
4260          * greater than 0.5 (which is true if the 0.5 bit is set and any lower
4261          * bit is set), or if the fractional part of signif is >= 0.5 and
4262          * signifFloor is odd (which is true if both the 0.5 bit and the 1 bit
4263          * are set). This is equivalent to the desired HALF_EVEN rounding.
4264          */
4265         bool increment = (twiceSignifFloor & 1) != 0
4266                 && ((signifFloor & 1) != 0 || abs().getLowestSetBit() < shift);
4267         long signifRounded = increment ? signifFloor + 1 : signifFloor;
4268         long bits = cast(long) ((exponent + DoubleConsts.EXP_BIAS))
4269                 << (DoubleConsts.SIGNIFICAND_WIDTH - 1);
4270         bits += signifRounded;
4271         /*
4272          * If signifRounded == 2^53, we'd need to set all of the significand
4273          * bits to zero and add 1 to the exponent. This is exactly the behavior
4274          * we get from just adding signifRounded to bits directly. If the
4275          * exponent is Double.MAX_EXPONENT, we round up (correctly) to
4276          * Double.POSITIVE_INFINITY.
4277          */
4278         bits |= signum & DoubleConsts.SIGN_BIT_MASK;
4279         return Double.longBitsToDouble(bits);
4280     }
4281 
4282 
4283     byte byteValue() {
4284         return cast(byte) intValue();
4285     }
4286 
4287     short shortValue() {
4288         return cast(short) intValue();
4289     }
4290 
4291     /**
4292      * Returns a copy of the input array stripped of any leading zero bytes.
4293      */
4294     private static int[] stripLeadingZeroInts(int[] val) {
4295         int vlen = cast(int)val.length;
4296         int keep;
4297 
4298         // Find first nonzero byte
4299         for (keep = 0; keep < vlen && val[keep] == 0; keep++){}
4300         return val[keep .. vlen].dup; // java.util.Arrays.copyOfRange(val, keep, vlen);
4301     }
4302 
4303     /**
4304      * Returns the input array stripped of any leading zero bytes.
4305      * Since the source is trusted the copying may be skipped.
4306      */
4307     private static int[] trustedStripLeadingZeroInts(int[] val) {
4308         int vlen = cast(int)val.length;
4309         int keep;
4310 
4311         // Find first nonzero byte
4312         for (keep = 0; keep < vlen && val[keep] == 0; keep++){}
4313         return keep == 0 ? val : val[keep .. vlen].dup; // java.util.Arrays.copyOfRange(val, keep, vlen);
4314     }
4315 
4316     /**
4317      * Returns a copy of the input array stripped of any leading zero bytes.
4318      */
4319     private static int[] stripLeadingZeroBytes(byte[] a, int off, int len) {
4320         int indexBound = off + len;
4321         int keep;
4322 
4323         // Find first nonzero byte
4324         for (keep = off; keep < indexBound && a[keep] == 0; keep++){}
4325 
4326         // Allocate new array and copy relevant part of input array
4327         int intLength = ((indexBound - keep) + 3) >>> 2;
4328         int[] result = new int[intLength];
4329         int b = indexBound - 1;
4330         for (int i = intLength-1; i >= 0; i--) {
4331             result[i] = a[b--] & 0xff;
4332             int bytesRemaining = b - keep + 1;
4333             int bytesToTransfer = std.algorithm.min(3, bytesRemaining); 
4334             for (int j=8; j <= (bytesToTransfer << 3); j += 8)
4335                 result[i] |= ((a[b--] & 0xff) << j);
4336         }
4337         return result;
4338     }
4339 
4340     /**
4341      * Takes an array a representing a negative 2's-complement number and
4342      * returns the minimal (no leading zero bytes) unsigned whose value is -a.
4343      */
4344     private static int[] makePositive(byte[] a, int off, int len) {
4345         int keep, k;
4346         int indexBound = off + len;
4347 
4348         // Find first non-sign (0xff) byte of input
4349         for (keep=off; keep < indexBound && a[keep] == -1; keep++) {}
4350 
4351 
4352         /* Allocate output array.  If all non-sign bytes are 0x00, we must
4353          * allocate space for one extra output byte. */
4354         for (k=keep; k < indexBound && a[k] == 0; k++) {}
4355 
4356         int extraByte = (k == indexBound) ? 1 : 0;
4357         int intLength = ((indexBound - keep + extraByte) + 3) >>> 2;
4358         int[] result = new int[intLength];
4359 
4360         /* Copy one's complement of input into output, leaving extra
4361          * byte (if it exists) == 0x00 */
4362         int b = indexBound - 1;
4363         for (int i = intLength-1; i >= 0; i--) {
4364             result[i] = a[b--] & 0xff;
4365             int numBytesToTransfer = std.algorithm.min(3, b-keep+1);
4366             if (numBytesToTransfer < 0)
4367                 numBytesToTransfer = 0;
4368             for (int j=8; j <= 8*numBytesToTransfer; j += 8)
4369                 result[i] |= ((a[b--] & 0xff) << j);
4370 
4371             // Mask indicates which bits must be complemented
4372             int mask = -1 >>> (8*(3-numBytesToTransfer));
4373             result[i] = ~result[i] & mask;
4374         }
4375 
4376         // Add one to one's complement to generate two's complement
4377         for (size_t i=result.length-1; i >= 0; i--) {
4378             result[i] = cast(int)((result[i] & LONG_MASK) + 1);
4379             if (result[i] != 0)
4380                 break;
4381         }
4382 
4383         return result;
4384     }
4385 
4386     /**
4387      * Takes an array a representing a negative 2's-complement number and
4388      * returns the minimal (no leading zero ints) unsigned whose value is -a.
4389      */
4390     private static int[] makePositive(int[] a) {
4391         int keep, j;
4392 
4393         // Find first non-sign (0xffffffff) int of input
4394         for (keep=0; keep < a.length && a[keep] == -1; keep++){}
4395 
4396         /* Allocate output array.  If all non-sign ints are 0x00, we must
4397          * allocate space for one extra output int. */
4398         for (j=keep; j < a.length && a[j] == 0; j++){}
4399         int extraInt = (j == a.length ? 1 : 0);
4400         int[] result = new int[a.length - keep + extraInt];
4401 
4402         /* Copy one's complement of input into output, leaving extra
4403          * int (if it exists) == 0x00 */
4404         for (int i = keep; i < a.length; i++)
4405             result[i - keep + extraInt] = ~a[i];
4406 
4407         // Add one to one's complement to generate two's complement
4408         for (size_t i=result.length-1; ++result[i] == 0; i--){}
4409 
4410         return result;
4411     }
4412 
4413     /*
4414      * The following two arrays are used for fast string conversions.  Both
4415      * are indexed by radix.  The first is the number of digits of the given
4416      * radix that can fit in a Java long without "going negative", i.e., the
4417      * highest integer n such that radix**n < 2**63.  The second is the
4418      * "long radix" that tears each number into "long digits", each of which
4419      * consists of the number of digits in the corresponding element in
4420      * digitsPerLong (longRadix[i] = i**digitPerLong[i]).  Both arrays have
4421      * nonsense values in their 0 and 1 elements, as radixes 0 and 1 are not
4422      * used.
4423      */
4424     private static int[] digitsPerLong = [0, 0,
4425         62, 39, 31, 27, 24, 22, 20, 19, 18, 18, 17, 17, 16, 16, 15, 15, 15, 14,
4426         14, 14, 14, 13, 13, 13, 13, 13, 13, 12, 12, 12, 12, 12, 12, 12, 12];
4427 
4428     private __gshared static BigInteger[] longRadix;
4429 
4430     shared static this() {
4431         longRadix = [null, null,
4432         valueOf(0x4000000000000000L), valueOf(0x383d9170b85ff80bL),
4433         valueOf(0x4000000000000000L), valueOf(0x6765c793fa10079dL),
4434         valueOf(0x41c21cb8e1000000L), valueOf(0x3642798750226111L),
4435         valueOf(0x1000000000000000L), valueOf(0x12bf307ae81ffd59L),
4436         valueOf( 0xde0b6b3a7640000L), valueOf(0x4d28cb56c33fa539L),
4437         valueOf(0x1eca170c00000000L), valueOf(0x780c7372621bd74dL),
4438         valueOf(0x1e39a5057d810000L), valueOf(0x5b27ac993df97701L),
4439         valueOf(0x1000000000000000L), valueOf(0x27b95e997e21d9f1L),
4440         valueOf(0x5da0e1e53c5c8000L), valueOf( 0xb16a458ef403f19L),
4441         valueOf(0x16bcc41e90000000L), valueOf(0x2d04b7fdd9c0ef49L),
4442         valueOf(0x5658597bcaa24000L), valueOf( 0x6feb266931a75b7L),
4443         valueOf( 0xc29e98000000000L), valueOf(0x14adf4b7320334b9L),
4444         valueOf(0x226ed36478bfa000L), valueOf(0x383d9170b85ff80bL),
4445         valueOf(0x5a3c23e39c000000L), valueOf( 0x4e900abb53e6b71L),
4446         valueOf( 0x7600ec618141000L), valueOf( 0xaee5720ee830681L),
4447         valueOf(0x1000000000000000L), valueOf(0x172588ad4f5f0981L),
4448         valueOf(0x211e44f7d02c1000L), valueOf(0x2ee56725f06e5c71L),
4449         valueOf(0x41c21cb8e1000000L)];
4450     }
4451 
4452     /*
4453      * These two arrays are the integer analogue of above.
4454      */
4455     private enum int[] digitsPerInt = [0, 0, 30, 19, 15, 13, 11,
4456         11, 10, 9, 9, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6,
4457         6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 5];
4458 
4459     private enum int[] intRadix =[0, 0,
4460         0x40000000, 0x4546b3db, 0x40000000, 0x48c27395, 0x159fd800,
4461         0x75db9c97, 0x40000000, 0x17179149, 0x3b9aca00, 0xcc6db61,
4462         0x19a10000, 0x309f1021, 0x57f6c100, 0xa2f1b6f,  0x10000000,
4463         0x18754571, 0x247dbc80, 0x3547667b, 0x4c4b4000, 0x6b5a6e1d,
4464         0x6c20a40,  0x8d2d931,  0xb640000,  0xe8d4a51,  0x1269ae40,
4465         0x17179149, 0x1cb91000, 0x23744899, 0x2b73a840, 0x34e63b41,
4466         0x40000000, 0x4cfa3cc1, 0x5c13d840, 0x6d91b519, 0x39aa400
4467     ];
4468 
4469     /**
4470      * These routines provide access to the two's complement representation
4471      * of BigIntegers.
4472      */
4473 
4474     /**
4475      * Returns the length of the two's complement representation in ints,
4476      * including space for at least one sign bit.
4477      */
4478     private int intLength() {
4479         return (bitLength() >>> 5) + 1;
4480     }
4481 
4482     /* Returns sign bit */
4483     private int signBit() {
4484         return signum < 0 ? 1 : 0;
4485     }
4486 
4487     /* Returns an int of sign bits */
4488     private int signInt() {
4489         return signum < 0 ? -1 : 0;
4490     }
4491 
4492     /**
4493      * Returns the specified int of the little-endian two's complement
4494      * representation (int 0 is the least significant).  The int number can
4495      * be arbitrarily high (values are logically preceded by infinitely many
4496      * sign ints).
4497      */
4498     private int getInt(int n) {
4499         if (n < 0)
4500             return 0;
4501         if (n >= cast(int)mag.length)
4502             return signInt();
4503 
4504         int magInt = mag[mag.length-n-1];
4505 
4506         return (signum >= 0 ? magInt :
4507                 (n <= firstNonzeroIntNum() ? -magInt : ~magInt));
4508     }
4509 
4510     /**
4511     * Returns the index of the int that contains the first nonzero int in the
4512     * little-endian binary representation of the magnitude (int 0 is the
4513     * least significant). If the magnitude is zero, return value is undefined.
4514     *
4515     * <p>Note: never used for a BigInteger with a magnitude of zero.
4516     * @see #getInt.
4517     */
4518     private int firstNonzeroIntNum() {
4519         int fn = firstNonzeroIntNumPlusTwo - 2;
4520         if (fn == -2) { // firstNonzeroIntNum not initialized yet
4521             // Search for the first nonzero int
4522             int i;
4523             int mlen = cast(int)mag.length;
4524             for (i = mlen - 1; i >= 0 && mag[i] == 0; i--) {}
4525             fn = mlen - i - 1;
4526             firstNonzeroIntNumPlusTwo = fn + 2; // offset by two to initialize
4527         }
4528         return fn;
4529     }
4530 
4531     /** use serialVersionUID from JDK 1.1. for interoperability */
4532     // private static final long serialVersionUID = -8287574255936472291L;
4533 
4534     /**
4535      * Serializable fields for BigInteger.
4536      *
4537      * @serialField signum  int
4538      *              signum of this BigInteger
4539      * @serialField magnitude byte[]
4540      *              magnitude array of this BigInteger
4541      * @serialField bitCount  int
4542      *              appears in the serialized form for backward compatibility
4543      * @serialField bitLength int
4544      *              appears in the serialized form for backward compatibility
4545      * @serialField firstNonzeroByteNum int
4546      *              appears in the serialized form for backward compatibility
4547      * @serialField lowestSetBit int
4548      *              appears in the serialized form for backward compatibility
4549      */
4550     // private static final ObjectStreamField[] serialPersistentFields = {
4551     //     new ObjectStreamField("signum", Integer.TYPE),
4552     //     new ObjectStreamField("magnitude", byte[].class),
4553     //     new ObjectStreamField("bitCount", Integer.TYPE),
4554     //     new ObjectStreamField("bitLength", Integer.TYPE),
4555     //     new ObjectStreamField("firstNonzeroByteNum", Integer.TYPE),
4556     //     new ObjectStreamField("lowestSetBit", Integer.TYPE)
4557     //     };
4558 
4559     /**
4560      * Reconstitute the {@code BigInteger} instance from a stream (that is,
4561      * deserialize it). The magnitude is read in as an array of bytes
4562      * for historical reasons, but it is converted to an array of ints
4563      * and the byte array is discarded.
4564      * Note:
4565      * The current convention is to initialize the cache fields, bitCountPlusOne,
4566      * bitLengthPlusOne and lowestSetBitPlusTwo, to 0 rather than some other
4567      * marker value. Therefore, no explicit action to set these fields needs to
4568      * be taken in readObject because those fields already have a 0 value by
4569      * default since defaultReadObject is not being used.
4570      */
4571     // private void readObject(java.io.ObjectInputStream s)
4572     //     throws java.io.IOException, ClassNotFoundException {
4573     //     // prepare to read the alternate persistent fields
4574     //     ObjectInputStream.GetField fields = s.readFields();
4575 
4576     //     // Read the alternate persistent fields that we care about
4577     //     int sign = fields.get("signum", -2);
4578     //     byte[] magnitude = (byte[])fields.get("magnitude", null);
4579 
4580     //     // Validate signum
4581     //     if (sign < -1 || sign > 1) {
4582     //         string message = "BigInteger: Invalid signum value";
4583     //         if (fields.defaulted("signum"))
4584     //             message = "BigInteger: Signum not present in stream";
4585     //         throw new java.io.StreamCorruptedException(message);
4586     //     }
4587     //     int[] mag = stripLeadingZeroBytes(magnitude, 0, magnitude.length);
4588     //     if (cast(int)(mag.length == 0) != (sign == 0)) {
4589     //         string message = "BigInteger: signum-magnitude mismatch";
4590     //         if (fields.defaulted("magnitude"))
4591     //             message = "BigInteger: Magnitude not present in stream";
4592     //         throw new java.io.StreamCorruptedException(message);
4593     //     }
4594 
4595     //     // Commit final fields via Unsafe
4596     //     UnsafeHolder.putSign(this, sign);
4597 
4598     //     // Calculate mag field from magnitude and discard magnitude
4599     //     UnsafeHolder.putMag(this, mag);
4600     //     if (mag.length >= MAX_MAG_LENGTH) {
4601     //         try {
4602     //             checkRange();
4603     //         } catch (ArithmeticException e) {
4604     //             throw new java.io.StreamCorruptedException("BigInteger: Out of the supported range");
4605     //         }
4606     //     }
4607     // }
4608 
4609     // // Support for resetting final fields while deserializing
4610     // private static class UnsafeHolder {
4611     //     private static final jdk.internal.misc.Unsafe unsafe
4612     //             = jdk.internal.misc.Unsafe.getUnsafe();
4613     //     private static final long signumOffset
4614     //             = unsafe.objectFieldOffset(BigInteger.class, "signum");
4615     //     private static final long magOffset
4616     //             = unsafe.objectFieldOffset(BigInteger.class, "mag");
4617 
4618     //     static void putSign(BigInteger bi, int sign) {
4619     //         unsafe.putInt(bi, signumOffset, sign);
4620     //     }
4621 
4622     //     static void putMag(BigInteger bi, int[] magnitude) {
4623     //         unsafe.putObject(bi, magOffset, magnitude);
4624     //     }
4625     // }
4626 
4627     /**
4628      * Save the {@code BigInteger} instance to a stream.  The magnitude of a
4629      * {@code BigInteger} is serialized as a byte array for historical reasons.
4630      * To maintain compatibility with older implementations, the integers
4631      * -1, -1, -2, and -2 are written as the values of the obsolete fields
4632      * {@code bitCount}, {@code bitLength}, {@code lowestSetBit}, and
4633      * {@code firstNonzeroByteNum}, respectively.  These values are compatible
4634      * with older implementations, but will be ignored by current
4635      * implementations.
4636      */
4637     // private void writeObject(ObjectOutputStream s) throws IOException {
4638     //     // set the values of the Serializable fields
4639     //     ObjectOutputStream.PutField fields = s.putFields();
4640     //     fields.put("signum", signum);
4641     //     fields.put("magnitude", magSerializedForm());
4642     //     // The values written for cached fields are compatible with older
4643     //     // versions, but are ignored in readObject so don't otherwise matter.
4644     //     fields.put("bitCount", -1);
4645     //     fields.put("bitLength", -1);
4646     //     fields.put("lowestSetBit", -2);
4647     //     fields.put("firstNonzeroByteNum", -2);
4648 
4649     //     // save them
4650     //     s.writeFields();
4651     // }
4652 
4653     /**
4654      * Returns the mag array as an array of bytes.
4655      */
4656     private byte[] magSerializedForm() {
4657         int len = cast(int)mag.length;
4658 
4659         int bitLen = (len == 0 ? 0 : ((len - 1) << 5) + bitLengthForInt(mag[0]));
4660         int byteLen = (bitLen + 7) >>> 3;
4661         byte[] result = new byte[byteLen];
4662 
4663         for (int i = byteLen - 1, bytesCopied = 4, intIndex = len - 1, nextInt = 0;
4664              i >= 0; i--) {
4665             if (bytesCopied == 4) {
4666                 nextInt = mag[intIndex--];
4667                 bytesCopied = 1;
4668             } else {
4669                 nextInt >>>= 8;
4670                 bytesCopied++;
4671             }
4672             result[i] = cast(byte)nextInt;
4673         }
4674         return result;
4675     }
4676 
4677     /**
4678      * Converts this {@code BigInteger} to a {@code long}, checking
4679      * for lost information.  If the value of this {@code BigInteger}
4680      * is out of the range of the {@code long} type, then an
4681      * {@code ArithmeticException} is thrown.
4682      *
4683      * @return this {@code BigInteger} converted to a {@code long}.
4684      * @throws ArithmeticException if the value of {@code this} will
4685      * not exactly fit in a {@code long}.
4686      * @see BigInteger#longValue
4687      */
4688     long longValueExact() {
4689         if (mag.length <= 2 && bitLength() <= 63)
4690             return longValue();
4691         else
4692             throw new ArithmeticException("BigInteger out of long range");
4693     }
4694 
4695     /**
4696      * Converts this {@code BigInteger} to an {@code int}, checking
4697      * for lost information.  If the value of this {@code BigInteger}
4698      * is out of the range of the {@code int} type, then an
4699      * {@code ArithmeticException} is thrown.
4700      *
4701      * @return this {@code BigInteger} converted to an {@code int}.
4702      * @throws ArithmeticException if the value of {@code this} will
4703      * not exactly fit in an {@code int}.
4704      * @see BigInteger#intValue
4705      */
4706     int intValueExact() {
4707         if (mag.length <= 1 && bitLength() <= 31)
4708             return intValue();
4709         else
4710             throw new ArithmeticException("BigInteger out of int range");
4711     }
4712 
4713     /**
4714      * Converts this {@code BigInteger} to a {@code short}, checking
4715      * for lost information.  If the value of this {@code BigInteger}
4716      * is out of the range of the {@code short} type, then an
4717      * {@code ArithmeticException} is thrown.
4718      *
4719      * @return this {@code BigInteger} converted to a {@code short}.
4720      * @throws ArithmeticException if the value of {@code this} will
4721      * not exactly fit in a {@code short}.
4722      * @see BigInteger#shortValue
4723      */
4724     short shortValueExact() {
4725         if (mag.length <= 1 && bitLength() <= 31) {
4726             int value = intValue();
4727             if (value >= short.min && value <= short.max)
4728                 return shortValue();
4729         }
4730         throw new ArithmeticException("BigInteger out of short range");
4731     }
4732 
4733     /**
4734      * Converts this {@code BigInteger} to a {@code byte}, checking
4735      * for lost information.  If the value of this {@code BigInteger}
4736      * is out of the range of the {@code byte} type, then an
4737      * {@code ArithmeticException} is thrown.
4738      *
4739      * @return this {@code BigInteger} converted to a {@code byte}.
4740      * @throws ArithmeticException if the value of {@code this} will
4741      * not exactly fit in a {@code byte}.
4742      * @see BigInteger#byteValue
4743      */
4744     byte byteValueExact() {
4745         if (mag.length <= 1 && bitLength() <= 31) {
4746             int value = intValue();
4747             if (value >= byte.min && value <= byte.max)
4748                 return byteValue();
4749         }
4750         throw new ArithmeticException("BigInteger out of byte range");
4751     }
4752 }
4753 
4754 
4755 
4756 class MutableBigInteger {
4757     /**
4758      * Holds the magnitude of this MutableBigInteger in big endian order.
4759      * The magnitude may start at an offset into the value array, and it may
4760      * end before the length of the value array.
4761      */
4762     int[] value;
4763 
4764     /**
4765      * The number of ints of the value array that are currently used
4766      * to hold the magnitude of this MutableBigInteger. The magnitude starts
4767      * at an offset and offset + intLen may be less than value.length.
4768      */
4769     int intLen;
4770 
4771     /**
4772      * The offset into the value array where the magnitude of this
4773      * MutableBigInteger begins.
4774      */
4775     int offset = 0;
4776 
4777     // Constants
4778     /**
4779      * MutableBigInteger with one element value array with the value 1. Used by
4780      * BigDecimal divideAndRound to increment the quotient. Use this constant
4781      * only when the method is not going to modify this object.
4782      */
4783     __gshared MutableBigInteger ONE;
4784 
4785     /**
4786      * The minimum {@code intLen} for cancelling powers of two before
4787      * dividing.
4788      * If the number of ints is less than this threshold,
4789      * {@code divideKnuth} does not eliminate common powers of two from
4790      * the dividend and divisor.
4791      */
4792     enum int KNUTH_POW2_THRESH_LEN = 6;
4793 
4794     /**
4795      * The minimum number of trailing zero ints for cancelling powers of two
4796      * before dividing.
4797      * If the dividend and divisor don't share at least this many zero ints
4798      * at the end, {@code divideKnuth} does not eliminate common powers
4799      * of two from the dividend and divisor.
4800      */
4801     enum int KNUTH_POW2_THRESH_ZEROS = 3;
4802 
4803     private enum long INFLATED = long.min;
4804     private enum LONG_MASK = BigInteger.LONG_MASK;
4805 
4806     shared static this() {
4807         ONE = new MutableBigInteger(1);
4808     }
4809 
4810     // Constructors
4811 
4812     /**
4813      * The default constructor. An empty MutableBigInteger is created with
4814      * a one word capacity.
4815      */
4816     this() {
4817         value = new int[1];
4818         intLen = 0;
4819     }
4820 
4821     /**
4822      * Construct a new MutableBigInteger with a magnitude specified by
4823      * the int val.
4824      */
4825     this(int val) {
4826         value = new int[1];
4827         intLen = 1;
4828         value[0] = val;
4829     }
4830 
4831     /**
4832      * Construct a new MutableBigInteger with the specified value array
4833      * up to the length of the array supplied.
4834      */
4835     this(int[] val) {
4836         value = val;
4837         intLen = cast(int)val.length;
4838     }
4839 
4840     /**
4841      * Construct a new MutableBigInteger with a magnitude equal to the
4842      * specified BigInteger.
4843      */
4844     this(BigInteger b) {
4845         intLen = cast(int)b.mag.length;
4846         // value = Arrays.copyOf(b.mag, intLen);
4847         value = b.mag.dup;
4848     }
4849 
4850     /**
4851      * Construct a new MutableBigInteger with a magnitude equal to the
4852      * specified MutableBigInteger.
4853      */
4854     this(MutableBigInteger val) {
4855         intLen = val.intLen;
4856         // value = Arrays.copyOfRange(val.value, val.offset, val.offset + intLen);
4857         value = val.cloneValue();
4858     }
4859 
4860     int[] cloneValue() {
4861         return value[offset .. offset + intLen].dup;
4862     }
4863 
4864     /**
4865      * Makes this number an {@code n}-int number all of whose bits are ones.
4866      * Used by Burnikel-Ziegler division.
4867      * @param n number of ints in the {@code value} array
4868      * @return a number equal to {@code ((1<<(32*n)))-1}
4869      */
4870     private void ones(int n) {
4871         if (n > value.length)
4872             value = new int[n];
4873         // Arrays.fill(value, -1);
4874         value[] = -1;
4875         offset = 0;
4876         intLen = n;
4877     }
4878 
4879     /**
4880      * Internal helper method to return the magnitude array. The caller is not
4881      * supposed to modify the returned array.
4882      */
4883     private int[] getMagnitudeArray() {
4884         if (offset > 0 || value.length != intLen)
4885             // return Arrays.copyOfRange(value, offset, offset + intLen);
4886             return value[offset .. offset + intLen];
4887         return value;
4888     }
4889 
4890     /**
4891      * Convert this MutableBigInteger to a long value. The caller has to make
4892      * sure this MutableBigInteger can be fit into long.
4893      */
4894     private long toLong() {
4895         assert (intLen <= 2, "this MutableBigInteger exceeds the range of long");
4896         if (intLen == 0)
4897             return 0;
4898         long d = value[offset] & LONG_MASK;
4899         return (intLen == 2) ? d << 32 | (value[offset + 1] & LONG_MASK) : d;
4900     }
4901 
4902     /**
4903      * Convert this MutableBigInteger to a BigInteger object.
4904      */
4905     BigInteger toBigInteger(int sign) {
4906         if (intLen == 0 || sign == 0)
4907             return BigInteger.ZERO;
4908         return new BigInteger(getMagnitudeArray(), sign);
4909     }
4910 
4911     /**
4912      * Converts this number to a nonnegative {@code BigInteger}.
4913      */
4914     BigInteger toBigInteger() {
4915         normalize();
4916         return toBigInteger(isZero() ? 0 : 1);
4917     }
4918 
4919     /**
4920      * Convert this MutableBigInteger to BigDecimal object with the specified sign
4921      * and scale.
4922      */
4923     // BigDecimal toBigDecimal(int sign, int scale) {
4924     //     if (intLen == 0 || sign == 0)
4925     //         return BigDecimal.zeroValueOf(scale);
4926     //     int[] mag = getMagnitudeArray();
4927     //     int len = cast(int)mag.length;
4928     //     int d = mag[0];
4929     //     // If this MutableBigInteger can't be fit into long, we need to
4930     //     // make a BigInteger object for the resultant BigDecimal object.
4931     //     if (len > 2 || (d < 0 && len == 2))
4932     //         return new BigDecimal(new BigInteger(mag, sign), INFLATED, scale, 0);
4933     //     long v = (len == 2) ?
4934     //         ((mag[1] & LONG_MASK) | (d & LONG_MASK) << 32) :
4935     //         d & LONG_MASK;
4936     //     return BigDecimal.valueOf(sign == -1 ? -v : v, scale);
4937     // }
4938 
4939     /**
4940      * This is for internal use in converting from a MutableBigInteger
4941      * object into a long value given a specified sign.
4942      * returns INFLATED if value is not fit into long
4943      */
4944     long toCompactValue(int sign) {
4945         if (intLen == 0 || sign == 0)
4946             return 0L;
4947         int[] mag = getMagnitudeArray();
4948         int len = cast(int)mag.length;
4949         int d = mag[0];
4950         // If this MutableBigInteger can not be fitted into long, we need to
4951         // make a BigInteger object for the resultant BigDecimal object.
4952         if (len > 2 || (d < 0 && len == 2))
4953             return INFLATED;
4954         long v = (len == 2) ?
4955             ((mag[1] & LONG_MASK) | (d & LONG_MASK) << 32) :
4956             d & LONG_MASK;
4957         return sign == -1 ? -v : v;
4958     }
4959 
4960     /**
4961      * Clear out a MutableBigInteger for reuse.
4962      */
4963     void clear() {
4964         offset = intLen = 0;
4965         for (int index=0, n=cast(int)value.length; index < n; index++)
4966             value[index] = 0;
4967     }
4968 
4969     /**
4970      * Set a MutableBigInteger to zero, removing its offset.
4971      */
4972     void reset() {
4973         offset = intLen = 0;
4974     }
4975 
4976     /**
4977      * Compare the magnitude of two MutableBigIntegers. Returns -1, 0 or 1
4978      * as this MutableBigInteger is numerically less than, equal to, or
4979      * greater than {@code b}.
4980      */
4981     final int compare(MutableBigInteger b) {
4982         int blen = b.intLen;
4983         if (intLen < blen)
4984             return -1;
4985         if (intLen > blen)
4986            return 1;
4987 
4988         // Add Integer.MIN_VALUE to make the comparison act as unsigned integer
4989         // comparison.
4990         int[] bval = b.value;
4991         for (int i = offset, j = b.offset; i < intLen + offset; i++, j++) {
4992             int b1 = value[i] + 0x80000000;
4993             int b2 = bval[j]  + 0x80000000;
4994             if (b1 < b2)
4995                 return -1;
4996             if (b1 > b2)
4997                 return 1;
4998         }
4999         return 0;
5000     }
5001 
5002     /**
5003      * Returns a value equal to what {@code b.leftShift(32*ints); return compare(b);}
5004      * would return, but doesn't change the value of {@code b}.
5005      */
5006     private int compareShifted(MutableBigInteger b, int ints) {
5007         int blen = b.intLen;
5008         int alen = intLen - ints;
5009         if (alen < blen)
5010             return -1;
5011         if (alen > blen)
5012            return 1;
5013 
5014         // Add Integer.MIN_VALUE to make the comparison act as unsigned integer
5015         // comparison.
5016         int[] bval = b.value;
5017         for (int i = offset, j = b.offset; i < alen + offset; i++, j++) {
5018             int b1 = value[i] + 0x80000000;
5019             int b2 = bval[j]  + 0x80000000;
5020             if (b1 < b2)
5021                 return -1;
5022             if (b1 > b2)
5023                 return 1;
5024         }
5025         return 0;
5026     }
5027 
5028     /**
5029      * Compare this against half of a MutableBigInteger object (Needed for
5030      * remainder tests).
5031      * Assumes no leading unnecessary zeros, which holds for results
5032      * from divide().
5033      */
5034     final int compareHalf(MutableBigInteger b) {
5035         int blen = b.intLen;
5036         int len = intLen;
5037         if (len <= 0)
5038             return blen <= 0 ? 0 : -1;
5039         if (len > blen)
5040             return 1;
5041         if (len < blen - 1)
5042             return -1;
5043         int[] bval = b.value;
5044         int bstart = 0;
5045         int carry = 0;
5046         // Only 2 cases left:len == blen or len == blen - 1
5047         if (len != blen) { // len == blen - 1
5048             if (bval[bstart] == 1) {
5049                 ++bstart;
5050                 carry = 0x80000000;
5051             } else
5052                 return -1;
5053         }
5054         // compare values with right-shifted values of b,
5055         // carrying shifted-out bits across words
5056         int[] val = value;
5057         for (int i = offset, j = bstart; i < len + offset;) {
5058             int bv = bval[j++];
5059             long hb = ((bv >>> 1) + carry) & LONG_MASK;
5060             long v = val[i++] & LONG_MASK;
5061             if (v != hb)
5062                 return v < hb ? -1 : 1;
5063             carry = (bv & 1) << 31; // carray will be either 0x80000000 or 0
5064         }
5065         return carry == 0 ? 0 : -1;
5066     }
5067 
5068     /**
5069      * Return the index of the lowest set bit in this MutableBigInteger. If the
5070      * magnitude of this MutableBigInteger is zero, -1 is returned.
5071      */
5072     private final int getLowestSetBit() {
5073         if (intLen == 0)
5074             return -1;
5075         int j, b;
5076         for (j=intLen-1; (j > 0) && (value[j+offset] == 0); j--) {}
5077         b = value[j+offset];
5078         if (b == 0)
5079             return -1;
5080         return ((intLen-1-j)<<5) + Integer.numberOfTrailingZeros(b);
5081     }
5082 
5083     /**
5084      * Return the int in use in this MutableBigInteger at the specified
5085      * index. This method is not used because it is not inlined on all
5086      * platforms.
5087      */
5088     private final int getInt(int index) {
5089         return value[offset+index];
5090     }
5091 
5092     /**
5093      * Return a long which is equal to the unsigned value of the int in
5094      * use in this MutableBigInteger at the specified index. This method is
5095      * not used because it is not inlined on all platforms.
5096      */
5097     private final long getLong(int index) {
5098         return value[offset+index] & LONG_MASK;
5099     }
5100 
5101     /**
5102      * Ensure that the MutableBigInteger is in normal form, specifically
5103      * making sure that there are no leading zeros, and that if the
5104      * magnitude is zero, then intLen is zero.
5105      */
5106     final void normalize() {
5107         if (intLen == 0) {
5108             offset = 0;
5109             return;
5110         }
5111 
5112         int index = offset;
5113         if (value[index] != 0)
5114             return;
5115 
5116         int indexBound = index+intLen;
5117         do {
5118             index++;
5119         } while(index < indexBound && value[index] == 0);
5120 
5121         int numZeros = index - offset;
5122         intLen -= numZeros;
5123         offset = (intLen == 0 ?  0 : offset+numZeros);
5124     }
5125 
5126     /**
5127      * If this MutableBigInteger cannot hold len words, increase the size
5128      * of the value array to len words.
5129      */
5130     private final void ensureCapacity(int len) {
5131         if (value.length < len) {
5132             value = new int[len];
5133             offset = 0;
5134             intLen = len;
5135         }
5136     }
5137 
5138     /**
5139      * Convert this MutableBigInteger into an int array with no leading
5140      * zeros, of a length that is equal to this MutableBigInteger's intLen.
5141      */
5142     int[] toIntArray() {
5143         int[] result = new int[intLen];
5144         for(int i=0; i < intLen; i++)
5145             result[i] = value[offset+i];
5146         return result;
5147     }
5148 
5149     /**
5150      * Sets the int at index+offset in this MutableBigInteger to val.
5151      * This does not get inlined on all platforms so it is not used
5152      * as often as originally intended.
5153      */
5154     void setInt(int index, int val) {
5155         value[offset + index] = val;
5156     }
5157 
5158     /**
5159      * Sets this MutableBigInteger's value array to the specified array.
5160      * The intLen is set to the specified length.
5161      */
5162     void setValue(int[] val, int length) {
5163         value = val;
5164         intLen = length;
5165         offset = 0;
5166     }
5167 
5168     /**
5169      * Sets this MutableBigInteger's value array to a copy of the specified
5170      * array. The intLen is set to the length of the new array.
5171      */
5172     void copyValue(MutableBigInteger src) {
5173         int len = src.intLen;
5174         if (value.length < len)
5175             value = new int[len];
5176         //System.arraycopy(src.value, src.offset, value, 0, len);
5177         value[0 .. len] = src.cloneValue();
5178 
5179         intLen = len;
5180         offset = 0;
5181     }
5182 
5183     /**
5184      * Sets this MutableBigInteger's value array to a copy of the specified
5185      * array. The intLen is set to the length of the specified array.
5186      */
5187     void copyValue(int[] val) {
5188         int len = cast(int)val.length;
5189         if (value.length < len)
5190             value = new int[len];
5191         // System.arraycopy(val, 0, value, 0, len);
5192         value[0..len] = val[0 .. len];
5193         intLen = len;
5194         offset = 0;
5195     }
5196 
5197     /**
5198      * Returns true iff this MutableBigInteger has a value of one.
5199      */
5200     bool isOne() {
5201         return (intLen == 1) && (value[offset] == 1);
5202     }
5203 
5204     /**
5205      * Returns true iff this MutableBigInteger has a value of zero.
5206      */
5207     bool isZero() {
5208         return (intLen == 0);
5209     }
5210 
5211     /**
5212      * Returns true iff this MutableBigInteger is even.
5213      */
5214     bool isEven() {
5215         return (intLen == 0) || ((value[offset + intLen - 1] & 1) == 0);
5216     }
5217 
5218     /**
5219      * Returns true iff this MutableBigInteger is odd.
5220      */
5221     bool isOdd() {
5222         return isZero() ? false : ((value[offset + intLen - 1] & 1) == 1);
5223     }
5224 
5225     /**
5226      * Returns true iff this MutableBigInteger is in normal form. A
5227      * MutableBigInteger is in normal form if it has no leading zeros
5228      * after the offset, and intLen + offset <= cast(int)value.length.
5229      */
5230     bool isNormal() {
5231         if (intLen + offset > value.length)
5232             return false;
5233         if (intLen == 0)
5234             return true;
5235         return (value[offset] != 0);
5236     }
5237 
5238     /**
5239      * Returns a string representation of this MutableBigInteger in radix 10.
5240      */
5241     override string toString() {
5242         BigInteger b = toBigInteger(1);
5243         return b.toString();
5244     }
5245 
5246     /**
5247      * Like {@link #rightShift(int)} but {@code n} can be greater than the length of the number.
5248      */
5249     void safeRightShift(int n) {
5250         if (n/32 >= intLen) {
5251             reset();
5252         } else {
5253             rightShift(n);
5254         }
5255     }
5256 
5257     /**
5258      * Right shift this MutableBigInteger n bits. The MutableBigInteger is left
5259      * in normal form.
5260      */
5261     void rightShift(int n) {
5262         if (intLen == 0)
5263             return;
5264         int nInts = n >>> 5;
5265         int nBits = n & 0x1F;
5266         this.intLen -= nInts;
5267         if (nBits == 0)
5268             return;
5269         int bitsInHighWord = BigInteger.bitLengthForInt(value[offset]);
5270         if (nBits >= bitsInHighWord) {
5271             this.primitiveLeftShift(32 - nBits);
5272             this.intLen--;
5273         } else {
5274             primitiveRightShift(nBits);
5275         }
5276     }
5277 
5278     /**
5279      * Like {@link #leftShift(int)} but {@code n} can be zero.
5280      */
5281     void safeLeftShift(int n) {
5282         if (n > 0) {
5283             leftShift(n);
5284         }
5285     }
5286 
5287     /**
5288      * Left shift this MutableBigInteger n bits.
5289      */
5290     void leftShift(int n) {
5291         /*
5292          * If there is enough storage space in this MutableBigInteger already
5293          * the available space will be used. Space to the right of the used
5294          * ints in the value array is faster to utilize, so the extra space
5295          * will be taken from the right if possible.
5296          */
5297         if (intLen == 0)
5298            return;
5299         int nInts = n >>> 5;
5300         int nBits = n&0x1F;
5301         int bitsInHighWord = BigInteger.bitLengthForInt(value[offset]);
5302 
5303         // If shift can be done without moving words, do so
5304         if (n <= (32-bitsInHighWord)) {
5305             primitiveLeftShift(nBits);
5306             return;
5307         }
5308 
5309         int newLen = intLen + nInts +1;
5310         if (nBits <= (32-bitsInHighWord))
5311             newLen--;
5312         if (value.length < newLen) {
5313             // The array must grow
5314             int[] result = new int[newLen];
5315             for (int i=0; i < intLen; i++)
5316                 result[i] = value[offset+i];
5317             setValue(result, newLen);
5318         } else if (value.length - offset >= newLen) {
5319             // Use space on right
5320             for(int i=0; i < newLen - intLen; i++)
5321                 value[offset+intLen+i] = 0;
5322         } else {
5323             // Must use space on left
5324             for (int i=0; i < intLen; i++)
5325                 value[i] = value[offset+i];
5326             for (int i=intLen; i < newLen; i++)
5327                 value[i] = 0;
5328             offset = 0;
5329         }
5330         intLen = newLen;
5331         if (nBits == 0)
5332             return;
5333         if (nBits <= (32-bitsInHighWord))
5334             primitiveLeftShift(nBits);
5335         else
5336             primitiveRightShift(32 -nBits);
5337     }
5338 
5339     /**
5340      * A primitive used for division. This method adds in one multiple of the
5341      * divisor a back to the dividend result at a specified offset. It is used
5342      * when qhat was estimated too large, and must be adjusted.
5343      */
5344     private int divadd(int[] a, int[] result, int offset) {
5345         long carry = 0;
5346 
5347         for (int j=cast(int)a.length-1; j >= 0; j--) {
5348             long sum = (a[j] & LONG_MASK) +
5349                        (result[j+offset] & LONG_MASK) + carry;
5350             result[j+offset] = cast(int)sum;
5351             carry = sum >>> 32;
5352         }
5353         return cast(int)carry;
5354     }
5355 
5356     /**
5357      * This method is used for division. It multiplies an n word input a by one
5358      * word input x, and subtracts the n word product from q. This is needed
5359      * when subtracting qhat*divisor from dividend.
5360      */
5361     private int mulsub(int[] q, int[] a, int x, int len, int offset) {
5362         long xLong = x & LONG_MASK;
5363         long carry = 0;
5364         offset += len;
5365 
5366         for (int j=len-1; j >= 0; j--) {
5367             long product = (a[j] & LONG_MASK) * xLong + carry;
5368             long difference = q[offset] - product;
5369             q[offset--] = cast(int)difference;
5370             carry = (product >>> 32)
5371                      + (((difference & LONG_MASK) >
5372                          (((~cast(int)product) & LONG_MASK))) ? 1:0);
5373         }
5374         return cast(int)carry;
5375     }
5376 
5377     /**
5378      * The method is the same as mulsun, except the fact that q array is not
5379      * updated, the only result of the method is borrow flag.
5380      */
5381     private int mulsubBorrow(int[] q, int[] a, int x, int len, int offset) {
5382         long xLong = x & LONG_MASK;
5383         long carry = 0;
5384         offset += len;
5385         for (int j=len-1; j >= 0; j--) {
5386             long product = (a[j] & LONG_MASK) * xLong + carry;
5387             long difference = q[offset--] - product;
5388             carry = (product >>> 32)
5389                      + (((difference & LONG_MASK) >
5390                          (((~cast(int)product) & LONG_MASK))) ? 1:0);
5391         }
5392         return cast(int)carry;
5393     }
5394 
5395     /**
5396      * Right shift this MutableBigInteger n bits, where n is
5397      * less than 32.
5398      * Assumes that intLen > 0, n > 0 for speed
5399      */
5400     private final void primitiveRightShift(int n) {
5401         int[] val = value;
5402         int n2 = 32 - n;
5403         for (int i=offset+intLen-1, c=val[i]; i > offset; i--) {
5404             int b = c;
5405             c = val[i-1];
5406             val[i] = (c << n2) | (b >>> n);
5407         }
5408         val[offset] >>>= n;
5409     }
5410 
5411     /**
5412      * Left shift this MutableBigInteger n bits, where n is
5413      * less than 32.
5414      * Assumes that intLen > 0, n > 0 for speed
5415      */
5416     private final void primitiveLeftShift(int n) {
5417         int[] val = value;
5418         int n2 = 32 - n;
5419         for (int i=offset, c=val[i], m=i+intLen-1; i < m; i++) {
5420             int b = c;
5421             c = val[i+1];
5422             val[i] = (b << n) | (c >>> n2);
5423         }
5424         val[offset+intLen-1] <<= n;
5425     }
5426 
5427     /**
5428      * Returns a {@code BigInteger} equal to the {@code n}
5429      * low ints of this number.
5430      */
5431     private BigInteger getLower(int n) {
5432         if (isZero()) {
5433             return BigInteger.ZERO;
5434         } else if (intLen < n) {
5435             return toBigInteger(1);
5436         } else {
5437             // strip zeros
5438             int len = n;
5439             while (len > 0 && value[offset+intLen-len] == 0)
5440                 len--;
5441             int sign = len > 0 ? 1 : 0;
5442             // return new BigInteger(Arrays.copyOfRange(value, offset+intLen-len, offset+intLen), sign);
5443             return new BigInteger(value[offset+intLen-len .. offset+intLen], sign);
5444         }
5445     }
5446 
5447     /**
5448      * Discards all ints whose index is greater than {@code n}.
5449      */
5450     private void keepLower(int n) {
5451         if (intLen >= n) {
5452             offset += intLen - n;
5453             intLen = n;
5454         }
5455     }
5456 
5457     /**
5458      * Adds the contents of two MutableBigInteger objects.The result
5459      * is placed within this MutableBigInteger.
5460      * The contents of the addend are not changed.
5461      */
5462     void add(MutableBigInteger addend) {
5463         int x = intLen;
5464         int y = addend.intLen;
5465         int resultLen = (intLen > addend.intLen ? intLen : addend.intLen);
5466         int[] result = (value.length < resultLen ? new int[resultLen] : value);
5467 
5468         int rstart = cast(int)result.length-1;
5469         long sum;
5470         long carry = 0;
5471 
5472         // Add common parts of both numbers
5473         while(x > 0 && y > 0) {
5474             x--; y--;
5475             sum = (value[x+offset] & LONG_MASK) +
5476                 (addend.value[y+addend.offset] & LONG_MASK) + carry;
5477             result[rstart--] = cast(int)sum;
5478             carry = sum >>> 32;
5479         }
5480 
5481         // Add remainder of the longer number
5482         while(x > 0) {
5483             x--;
5484             if (carry == 0 && result == value && rstart == (x + offset))
5485                 return;
5486             sum = (value[x+offset] & LONG_MASK) + carry;
5487             result[rstart--] = cast(int)sum;
5488             carry = sum >>> 32;
5489         }
5490         while(y > 0) {
5491             y--;
5492             sum = (addend.value[y+addend.offset] & LONG_MASK) + carry;
5493             result[rstart--] = cast(int)sum;
5494             carry = sum >>> 32;
5495         }
5496 
5497         if (carry > 0) { // Result must grow in length
5498             resultLen++;
5499             size_t len = cast(int)result.length;
5500             if (len < resultLen) {
5501                 int[] temp = new int[resultLen];
5502                 // Result one word longer from carry-out; copy low-order
5503                 // bits into new result.
5504                 // System.arraycopy(result, 0, temp, 1, result.length);
5505                 temp[1 .. len+1] = result[0..$];
5506                 temp[0] = 1;
5507                 result = temp;
5508             } else {
5509                 result[rstart--] = 1;
5510             }
5511         }
5512 
5513         value = result;
5514         intLen = resultLen;
5515         offset = cast(int)result.length - resultLen;
5516     }
5517 
5518     /**
5519      * Adds the value of {@code addend} shifted {@code n} ints to the left.
5520      * Has the same effect as {@code addend.leftShift(32*ints); add(addend);}
5521      * but doesn't change the value of {@code addend}.
5522      */
5523     void addShifted(MutableBigInteger addend, int n) {
5524         if (addend.isZero()) {
5525             return;
5526         }
5527 
5528         int x = intLen;
5529         int y = addend.intLen + n;
5530         int resultLen = (intLen > y ? intLen : y);
5531         int[] result = (value.length < resultLen ? new int[resultLen] : value);
5532 
5533         int rstart = cast(int)result.length-1;
5534         long sum;
5535         long carry = 0;
5536 
5537         // Add common parts of both numbers
5538         while (x > 0 && y > 0) {
5539             x--; y--;
5540             int bval = y+addend.offset < addend.value.length ? addend.value[y+addend.offset] : 0;
5541             sum = (value[x+offset] & LONG_MASK) +
5542                 (bval & LONG_MASK) + carry;
5543             result[rstart--] = cast(int)sum;
5544             carry = sum >>> 32;
5545         }
5546 
5547         // Add remainder of the longer number
5548         while (x > 0) {
5549             x--;
5550             if (carry == 0 && result == value && rstart == (x + offset)) {
5551                 return;
5552             }
5553             sum = (value[x+offset] & LONG_MASK) + carry;
5554             result[rstart--] = cast(int)sum;
5555             carry = sum >>> 32;
5556         }
5557         while (y > 0) {
5558             y--;
5559             int bval = y+addend.offset < addend.value.length ? addend.value[y+addend.offset] : 0;
5560             sum = (bval & LONG_MASK) + carry;
5561             result[rstart--] = cast(int)sum;
5562             carry = sum >>> 32;
5563         }
5564 
5565         if (carry > 0) { // Result must grow in length
5566             resultLen++;
5567             size_t len = cast(int)result.length;
5568             if (len < resultLen) {
5569                 int[] temp = new int[resultLen];
5570                 // Result one word longer from carry-out; copy low-order
5571                 // bits into new result.
5572                 // System.arraycopy(result, 0, temp, 1, result.length);
5573                 temp[1 .. len+1] = result[0..$];
5574                 temp[0] = 1;
5575                 result = temp;
5576             } else {
5577                 result[rstart--] = 1;
5578             }
5579         }
5580 
5581         value = result;
5582         intLen = resultLen;
5583         offset = cast(int)result.length - resultLen;
5584     }
5585 
5586     /**
5587      * Like {@link #addShifted(MutableBigInteger, int)} but {@code this.intLen} must
5588      * not be greater than {@code n}. In other words, concatenates {@code this}
5589      * and {@code addend}.
5590      */
5591     void addDisjoint(MutableBigInteger addend, int n) {
5592         if (addend.isZero())
5593             return;
5594 
5595         int x = intLen;
5596         int y = addend.intLen + n;
5597         int resultLen = (intLen > y ? intLen : y);
5598         int[] result;
5599         if (value.length < resultLen)
5600             result = new int[resultLen];
5601         else {
5602             result = value;
5603             //Arrays.fill(value, offset+intLen, value.length, 0);
5604             value[offset+intLen .. $] = 0;
5605         }
5606 
5607         int rstart = cast(int)result.length-1;
5608 
5609         // copy from this if needed
5610         // System.arraycopy(value, offset, result, rstart+1-x, x);
5611         result[rstart+1-x .. rstart+1] = value[offset .. x];
5612         y -= x;
5613         rstart -= x;
5614 
5615         int len = std.algorithm.min(y, addend.value.length-addend.offset);
5616         // System.arraycopy(addend.value, addend.offset, result, rstart+1-y, len);
5617         result[rstart+1-y .. rstart+1] = addend.value[addend.offset .. len];
5618 
5619 
5620         // zero the gap
5621         for (int i=rstart+1-y+len; i < rstart+1; i++)
5622             result[i] = 0;
5623 
5624         value = result;
5625         intLen = resultLen;
5626         offset = cast(int)result.length - resultLen;
5627     }
5628 
5629     /**
5630      * Adds the low {@code n} ints of {@code addend}.
5631      */
5632     void addLower(MutableBigInteger addend, int n) {
5633         MutableBigInteger a = new MutableBigInteger(addend);
5634         if (a.offset + a.intLen >= n) {
5635             a.offset = a.offset + a.intLen - n;
5636             a.intLen = n;
5637         }
5638         a.normalize();
5639         add(a);
5640     }
5641 
5642     /**
5643      * Subtracts the smaller of this and b from the larger and places the
5644      * result into this MutableBigInteger.
5645      */
5646     int subtract(MutableBigInteger b) {
5647         MutableBigInteger a = this;
5648 
5649         int[] result = value;
5650         int sign = a.compare(b);
5651 
5652         if (sign == 0) {
5653             reset();
5654             return 0;
5655         }
5656         if (sign < 0) {
5657             MutableBigInteger tmp = a;
5658             a = b;
5659             b = tmp;
5660         }
5661 
5662         int resultLen = a.intLen;
5663         if (result.length < resultLen)
5664             result = new int[resultLen];
5665 
5666         long diff = 0;
5667         int x = a.intLen;
5668         int y = b.intLen;
5669         int rstart = cast(int)result.length - 1;
5670 
5671         // Subtract common parts of both numbers
5672         while (y > 0) {
5673             x--; y--;
5674 
5675             diff = (a.value[x+a.offset] & LONG_MASK) -
5676                    (b.value[y+b.offset] & LONG_MASK) - (cast(int)-(diff>>32));
5677             result[rstart--] = cast(int)diff;
5678         }
5679         // Subtract remainder of longer number
5680         while (x > 0) {
5681             x--;
5682             diff = (a.value[x+a.offset] & LONG_MASK) - (cast(int)-(diff>>32));
5683             result[rstart--] = cast(int)diff;
5684         }
5685 
5686         value = result;
5687         intLen = resultLen;
5688         offset = cast(int)value.length - resultLen;
5689         normalize();
5690         return sign;
5691     }
5692 
5693     /**
5694      * Subtracts the smaller of a and b from the larger and places the result
5695      * into the larger. Returns 1 if the answer is in a, -1 if in b, 0 if no
5696      * operation was performed.
5697      */
5698     private int difference(MutableBigInteger b) {
5699         MutableBigInteger a = this;
5700         int sign = a.compare(b);
5701         if (sign == 0)
5702             return 0;
5703         if (sign < 0) {
5704             MutableBigInteger tmp = a;
5705             a = b;
5706             b = tmp;
5707         }
5708 
5709         long diff = 0;
5710         int x = a.intLen;
5711         int y = b.intLen;
5712 
5713         // Subtract common parts of both numbers
5714         while (y > 0) {
5715             x--; y--;
5716             diff = (a.value[a.offset+ x] & LONG_MASK) -
5717                 (b.value[b.offset+ y] & LONG_MASK) - (cast(int)-(diff>>32));
5718             a.value[a.offset+x] = cast(int)diff;
5719         }
5720         // Subtract remainder of longer number
5721         while (x > 0) {
5722             x--;
5723             diff = (a.value[a.offset+ x] & LONG_MASK) - (cast(int)-(diff>>32));
5724             a.value[a.offset+x] = cast(int)diff;
5725         }
5726 
5727         a.normalize();
5728         return sign;
5729     }
5730 
5731     /**
5732      * Multiply the contents of two MutableBigInteger objects. The result is
5733      * placed into MutableBigInteger z. The contents of y are not changed.
5734      */
5735     void multiply(MutableBigInteger y, MutableBigInteger z) {
5736         int xLen = intLen;
5737         int yLen = y.intLen;
5738         int newLen = xLen + yLen;
5739 
5740         // Put z into an appropriate state to receive product
5741         if (z.value.length < newLen)
5742             z.value = new int[newLen];
5743         z.offset = 0;
5744         z.intLen = newLen;
5745 
5746         // The first iteration is hoisted out of the loop to avoid extra add
5747         long carry = 0;
5748         for (int j=yLen-1, k=yLen+xLen-1; j >= 0; j--, k--) {
5749                 long product = (y.value[j+y.offset] & LONG_MASK) *
5750                                (value[xLen-1+offset] & LONG_MASK) + carry;
5751                 z.value[k] = cast(int)product;
5752                 carry = product >>> 32;
5753         }
5754         z.value[xLen-1] = cast(int)carry;
5755 
5756         // Perform the multiplication word by word
5757         for (int i = xLen-2; i >= 0; i--) {
5758             carry = 0;
5759             for (int j=yLen-1, k=yLen+i; j >= 0; j--, k--) {
5760                 long product = (y.value[j+y.offset] & LONG_MASK) *
5761                                (value[i+offset] & LONG_MASK) +
5762                                (z.value[k] & LONG_MASK) + carry;
5763                 z.value[k] = cast(int)product;
5764                 carry = product >>> 32;
5765             }
5766             z.value[i] = cast(int)carry;
5767         }
5768 
5769         // Remove leading zeros from product
5770         z.normalize();
5771     }
5772 
5773     /**
5774      * Multiply the contents of this MutableBigInteger by the word y. The
5775      * result is placed into z.
5776      */
5777     void mul(int y, MutableBigInteger z) {
5778         if (y == 1) {
5779             z.copyValue(this);
5780             return;
5781         }
5782 
5783         if (y == 0) {
5784             z.clear();
5785             return;
5786         }
5787 
5788         // Perform the multiplication word by word
5789         long ylong = y & LONG_MASK;
5790         int[] zval = (z.value.length < intLen+1 ? new int[intLen + 1]
5791                                               : z.value);
5792         long carry = 0;
5793         for (int i = intLen-1; i >= 0; i--) {
5794             long product = ylong * (value[i+offset] & LONG_MASK) + carry;
5795             zval[i+1] = cast(int)product;
5796             carry = product >>> 32;
5797         }
5798 
5799         if (carry == 0) {
5800             z.offset = 1;
5801             z.intLen = intLen;
5802         } else {
5803             z.offset = 0;
5804             z.intLen = intLen + 1;
5805             zval[0] = cast(int)carry;
5806         }
5807         z.value = zval;
5808     }
5809 
5810      /**
5811      * This method is used for division of an n word dividend by a one word
5812      * divisor. The quotient is placed into quotient. The one word divisor is
5813      * specified by divisor.
5814      *
5815      * @return the remainder of the division is returned.
5816      *
5817      */
5818     int divideOneWord(int divisor, MutableBigInteger quotient) {
5819         long divisorLong = divisor & LONG_MASK;
5820 
5821         // Special case of one word dividend
5822         if (intLen == 1) {
5823             long dividendValue = value[offset] & LONG_MASK;
5824             int q = cast(int) (dividendValue / divisorLong);
5825             int r = cast(int) (dividendValue - q * divisorLong);
5826             quotient.value[0] = q;
5827             quotient.intLen = (q == 0) ? 0 : 1;
5828             quotient.offset = 0;
5829             return r;
5830         }
5831 
5832         if (quotient.value.length < intLen)
5833             quotient.value = new int[intLen];
5834         quotient.offset = 0;
5835         quotient.intLen = intLen;
5836 
5837         // Normalize the divisor
5838         int shift = Integer.numberOfLeadingZeros(divisor);
5839 
5840         int rem = value[offset];
5841         long remLong = rem & LONG_MASK;
5842         if (remLong < divisorLong) {
5843             quotient.value[0] = 0;
5844         } else {
5845             quotient.value[0] = cast(int)(remLong / divisorLong);
5846             rem = cast(int) (remLong - (quotient.value[0] * divisorLong));
5847             remLong = rem & LONG_MASK;
5848         }
5849         int xlen = intLen;
5850         while (--xlen > 0) {
5851             long dividendEstimate = (remLong << 32) |
5852                     (value[offset + intLen - xlen] & LONG_MASK);
5853             int q;
5854             if (dividendEstimate >= 0) {
5855                 q = cast(int) (dividendEstimate / divisorLong);
5856                 rem = cast(int) (dividendEstimate - q * divisorLong);
5857             } else {
5858                 long tmp = divWord(dividendEstimate, divisor);
5859                 q = cast(int) (tmp & LONG_MASK);
5860                 rem = cast(int) (tmp >>> 32);
5861             }
5862             quotient.value[intLen - xlen] = q;
5863             remLong = rem & LONG_MASK;
5864         }
5865 
5866         quotient.normalize();
5867         // Unnormalize
5868         if (shift > 0)
5869             return rem % divisor;
5870         else
5871             return rem;
5872     }
5873 
5874     /**
5875      * Calculates the quotient of this div b and places the quotient in the
5876      * provided MutableBigInteger objects and the remainder object is returned.
5877      *
5878      */
5879     MutableBigInteger divide(MutableBigInteger b, MutableBigInteger quotient) {
5880         return divide(b,quotient,true);
5881     }
5882 
5883     MutableBigInteger divide(MutableBigInteger b, MutableBigInteger quotient, bool needRemainder) {
5884         if (b.intLen < BigInteger.BURNIKEL_ZIEGLER_THRESHOLD ||
5885                 intLen - b.intLen < BigInteger.BURNIKEL_ZIEGLER_OFFSET) {
5886             return divideKnuth(b, quotient, needRemainder);
5887         } else {
5888             return divideAndRemainderBurnikelZiegler(b, quotient);
5889         }
5890     }
5891 
5892     /**
5893      * @see #divideKnuth(MutableBigInteger, MutableBigInteger, bool)
5894      */
5895     MutableBigInteger divideKnuth(MutableBigInteger b, MutableBigInteger quotient) {
5896         return divideKnuth(b,quotient,true);
5897     }
5898 
5899     /**
5900      * Calculates the quotient of this div b and places the quotient in the
5901      * provided MutableBigInteger objects and the remainder object is returned.
5902      *
5903      * Uses Algorithm D in Knuth section 4.3.1.
5904      * Many optimizations to that algorithm have been adapted from the Colin
5905      * Plumb C library.
5906      * It special cases one word divisors for speed. The content of b is not
5907      * changed.
5908      *
5909      */
5910     MutableBigInteger divideKnuth(MutableBigInteger b, MutableBigInteger quotient, bool needRemainder) {
5911         if (b.intLen == 0)
5912             throw new ArithmeticException("BigInteger divide by zero");
5913 
5914         // Dividend is zero
5915         if (intLen == 0) {
5916             quotient.intLen = quotient.offset = 0;
5917             return needRemainder ? new MutableBigInteger() : null;
5918         }
5919 
5920         int cmp = compare(b);
5921         // Dividend less than divisor
5922         if (cmp < 0) {
5923             quotient.intLen = quotient.offset = 0;
5924             return needRemainder ? new MutableBigInteger(this) : null;
5925         }
5926         // Dividend equal to divisor
5927         if (cmp == 0) {
5928             quotient.value[0] = quotient.intLen = 1;
5929             quotient.offset = 0;
5930             return needRemainder ? new MutableBigInteger() : null;
5931         }
5932 
5933         quotient.clear();
5934         // Special case one word divisor
5935         if (b.intLen == 1) {
5936             int r = divideOneWord(b.value[b.offset], quotient);
5937             if(needRemainder) {
5938                 if (r == 0)
5939                     return new MutableBigInteger();
5940                 return new MutableBigInteger(r);
5941             } else {
5942                 return null;
5943             }
5944         }
5945 
5946         // Cancel common powers of two if we're above the KNUTH_POW2_* thresholds
5947         if (intLen >= KNUTH_POW2_THRESH_LEN) {
5948             int trailingZeroBits = std.algorithm.min(getLowestSetBit(), b.getLowestSetBit());
5949             if (trailingZeroBits >= KNUTH_POW2_THRESH_ZEROS*32) {
5950                 MutableBigInteger a = new MutableBigInteger(this);
5951                 b = new MutableBigInteger(b);
5952                 a.rightShift(trailingZeroBits);
5953                 b.rightShift(trailingZeroBits);
5954                 MutableBigInteger r = a.divideKnuth(b, quotient);
5955                 r.leftShift(trailingZeroBits);
5956                 return r;
5957             }
5958         }
5959 
5960         return divideMagnitude(b, quotient, needRemainder);
5961     }
5962 
5963     /**
5964      * Computes {@code this/b} and {@code this%b} using the
5965      * <a href="http://cr.yp.to/bib/1998/burnikel.ps"> Burnikel-Ziegler algorithm</a>.
5966      * This method implements algorithm 3 from pg. 9 of the Burnikel-Ziegler paper.
5967      * The parameter beta was chosen to b 2<sup>32</sup> so almost all shifts are
5968      * multiples of 32 bits.<br/>
5969      * {@code this} and {@code b} must be nonnegative.
5970      * @param b the divisor
5971      * @param quotient output parameter for {@code this/b}
5972      * @return the remainder
5973      */
5974     MutableBigInteger divideAndRemainderBurnikelZiegler(MutableBigInteger b, MutableBigInteger quotient) {
5975         int r = intLen;
5976         int s = b.intLen;
5977 
5978         // Clear the quotient
5979         quotient.offset = quotient.intLen = 0;
5980 
5981         if (r < s) {
5982             return this;
5983         } else {
5984             // Unlike Knuth division, we don't check for common powers of two here because
5985             // BZ already runs faster if both numbers contain powers of two and cancelling them has no
5986             // additional benefit.
5987 
5988             // step 1: let m = min{2^k | (2^k)*BURNIKEL_ZIEGLER_THRESHOLD > s}
5989             int m = 1 << (32-Integer.numberOfLeadingZeros(s/BigInteger.BURNIKEL_ZIEGLER_THRESHOLD));
5990 
5991             int j = (s+m-1) / m;      // step 2a: j = ceil(s/m)
5992             int n = j * m;            // step 2b: block length in 32-bit units
5993             long n32 = 32L * n;         // block length in bits
5994             int sigma = cast(int) std.algorithm.max(0, n32 - b.bitLength());   // step 3: sigma = max{T | (2^T)*B < beta^n}
5995             MutableBigInteger bShifted = new MutableBigInteger(b);
5996             bShifted.safeLeftShift(sigma);   // step 4a: shift b so its length is a multiple of n
5997             MutableBigInteger aShifted = new MutableBigInteger (this);
5998             aShifted.safeLeftShift(sigma);     // step 4b: shift a by the same amount
5999 
6000             // step 5: t is the number of blocks needed to accommodate a plus one additional bit
6001             int t = cast(int) ((aShifted.bitLength()+n32) / n32);
6002             if (t < 2) {
6003                 t = 2;
6004             }
6005 
6006             // step 6: conceptually split a into blocks a[t-1], ..., a[0]
6007             MutableBigInteger a1 = aShifted.getBlock(t-1, t, n);   // the most significant block of a
6008 
6009             // step 7: z[t-2] = [a[t-1], a[t-2]]
6010             MutableBigInteger z = aShifted.getBlock(t-2, t, n);    // the second to most significant block
6011             z.addDisjoint(a1, n);   // z[t-2]
6012 
6013             // do schoolbook division on blocks, dividing 2-block numbers by 1-block numbers
6014             MutableBigInteger qi = new MutableBigInteger();
6015             MutableBigInteger ri;
6016             for (int i=t-2; i > 0; i--) {
6017                 // step 8a: compute (qi,ri) such that z=b*qi+ri
6018                 ri = z.divide2n1n(bShifted, qi);
6019 
6020                 // step 8b: z = [ri, a[i-1]]
6021                 z = aShifted.getBlock(i-1, t, n);   // a[i-1]
6022                 z.addDisjoint(ri, n);
6023                 quotient.addShifted(qi, i*n);   // update q (part of step 9)
6024             }
6025             // final iteration of step 8: do the loop one more time for i=0 but leave z unchanged
6026             ri = z.divide2n1n(bShifted, qi);
6027             quotient.add(qi);
6028 
6029             ri.rightShift(sigma);   // step 9: a and b were shifted, so shift back
6030             return ri;
6031         }
6032     }
6033 
6034     /**
6035      * This method implements algorithm 1 from pg. 4 of the Burnikel-Ziegler paper.
6036      * It divides a 2n-digit number by a n-digit number.<br/>
6037      * The parameter beta is 2<sup>32</sup> so all shifts are multiples of 32 bits.
6038      * <br/>
6039      * {@code this} must be a nonnegative number such that {@code this.bitLength() <= 2*b.bitLength()}
6040      * @param b a positive number such that {@code b.bitLength()} is even
6041      * @param quotient output parameter for {@code this/b}
6042      * @return {@code this%b}
6043      */
6044     private MutableBigInteger divide2n1n(MutableBigInteger b, MutableBigInteger quotient) {
6045         int n = b.intLen;
6046 
6047         // step 1: base case
6048         if (n%2 != 0 || n < BigInteger.BURNIKEL_ZIEGLER_THRESHOLD) {
6049             return divideKnuth(b, quotient);
6050         }
6051 
6052         // step 2: view this as [a1,a2,a3,a4] where each ai is n/2 ints or less
6053         MutableBigInteger aUpper = new MutableBigInteger(this);
6054         aUpper.safeRightShift(32*(n/2));   // aUpper = [a1,a2,a3]
6055         keepLower(n/2);   // this = a4
6056 
6057         // step 3: q1=aUpper/b, r1=aUpper%b
6058         MutableBigInteger q1 = new MutableBigInteger();
6059         MutableBigInteger r1 = aUpper.divide3n2n(b, q1);
6060 
6061         // step 4: quotient=[r1,this]/b, r2=[r1,this]%b
6062         addDisjoint(r1, n/2);   // this = [r1,this]
6063         MutableBigInteger r2 = divide3n2n(b, quotient);
6064 
6065         // step 5: let quotient=[q1,quotient] and return r2
6066         quotient.addDisjoint(q1, n/2);
6067         return r2;
6068     }
6069 
6070     /**
6071      * This method implements algorithm 2 from pg. 5 of the Burnikel-Ziegler paper.
6072      * It divides a 3n-digit number by a 2n-digit number.<br/>
6073      * The parameter beta is 2<sup>32</sup> so all shifts are multiples of 32 bits.<br/>
6074      * <br/>
6075      * {@code this} must be a nonnegative number such that {@code 2*this.bitLength() <= 3*b.bitLength()}
6076      * @param quotient output parameter for {@code this/b}
6077      * @return {@code this%b}
6078      */
6079     private MutableBigInteger divide3n2n(MutableBigInteger b, MutableBigInteger quotient) {
6080         int n = b.intLen / 2;   // half the length of b in ints
6081 
6082         // step 1: view this as [a1,a2,a3] where each ai is n ints or less; let a12=[a1,a2]
6083         MutableBigInteger a12 = new MutableBigInteger(this);
6084         a12.safeRightShift(32*n);
6085 
6086         // step 2: view b as [b1,b2] where each bi is n ints or less
6087         MutableBigInteger b1 = new MutableBigInteger(b);
6088         b1.safeRightShift(n * 32);
6089         BigInteger b2 = b.getLower(n);
6090 
6091         MutableBigInteger r;
6092         MutableBigInteger d;
6093         if (compareShifted(b, n) < 0) {
6094             // step 3a: if a1<b1, let quotient=a12/b1 and r=a12%b1
6095             r = a12.divide2n1n(b1, quotient);
6096 
6097             // step 4: d=quotient*b2
6098             d = new MutableBigInteger(quotient.toBigInteger().multiply(b2));
6099         } else {
6100             // step 3b: if a1>=b1, let quotient=beta^n-1 and r=a12-b1*2^n+b1
6101             quotient.ones(n);
6102             a12.add(b1);
6103             b1.leftShift(32*n);
6104             a12.subtract(b1);
6105             r = a12;
6106 
6107             // step 4: d=quotient*b2=(b2 << 32*n) - b2
6108             d = new MutableBigInteger(b2);
6109             d.leftShift(32 * n);
6110             d.subtract(new MutableBigInteger(b2));
6111         }
6112 
6113         // step 5: r = r*beta^n + a3 - d (paper says a4)
6114         // However, don't subtract d until after the while loop so r doesn't become negative
6115         r.leftShift(32 * n);
6116         r.addLower(this, n);
6117 
6118         // step 6: add b until r>=d
6119         while (r.compare(d) < 0) {
6120             r.add(b);
6121             quotient.subtract(MutableBigInteger.ONE);
6122         }
6123         r.subtract(d);
6124 
6125         return r;
6126     }
6127 
6128     /**
6129      * Returns a {@code MutableBigInteger} containing {@code blockLength} ints from
6130      * {@code this} number, starting at {@code index*blockLength}.<br/>
6131      * Used by Burnikel-Ziegler division.
6132      * @param index the block index
6133      * @param numBlocks the total number of blocks in {@code this} number
6134      * @param blockLength length of one block in units of 32 bits
6135      * @return
6136      */
6137     private MutableBigInteger getBlock(int index, int numBlocks, int blockLength) {
6138         int blockStart = index * blockLength;
6139         if (blockStart >= intLen) {
6140             return new MutableBigInteger();
6141         }
6142 
6143         int blockEnd;
6144         if (index == numBlocks-1) {
6145             blockEnd = intLen;
6146         } else {
6147             blockEnd = (index+1) * blockLength;
6148         }
6149         if (blockEnd > intLen) {
6150             return new MutableBigInteger();
6151         }
6152 
6153         // int[] newVal = Arrays.copyOfRange(value, offset+intLen-blockEnd, offset+intLen-blockStart);
6154         int[] newVal = value[offset+intLen-blockEnd .. offset+intLen-blockStart];
6155         return new MutableBigInteger(newVal);
6156     }
6157 
6158     /** @see BigInteger#bitLength() */
6159     long bitLength() {
6160         if (intLen == 0)
6161             return 0;
6162         return intLen*32L - Integer.numberOfLeadingZeros(value[offset]);
6163     }
6164 
6165     /**
6166      * Internally used  to calculate the quotient of this div v and places the
6167      * quotient in the provided MutableBigInteger object and the remainder is
6168      * returned.
6169      *
6170      * @return the remainder of the division will be returned.
6171      */
6172     long divide(long v, MutableBigInteger quotient) {
6173         if (v == 0)
6174             throw new ArithmeticException("BigInteger divide by zero");
6175 
6176         // Dividend is zero
6177         if (intLen == 0) {
6178             quotient.intLen = quotient.offset = 0;
6179             return 0;
6180         }
6181         if (v < 0)
6182             v = -v;
6183 
6184         int d = cast(int)(v >>> 32);
6185         quotient.clear();
6186         // Special case on word divisor
6187         if (d == 0)
6188             return divideOneWord(cast(int)v, quotient) & LONG_MASK;
6189         else {
6190             return divideLongMagnitude(v, quotient).toLong();
6191         }
6192     }
6193 
6194     private static void copyAndShift(int[] src, int srcFrom, int srcLen, int[] dst, int dstFrom, int shift) {
6195         int n2 = 32 - shift;
6196         int c=src[srcFrom];
6197         for (int i=0; i < srcLen-1; i++) {
6198             int b = c;
6199             c = src[++srcFrom];
6200             dst[dstFrom+i] = (b << shift) | (c >>> n2);
6201         }
6202         dst[dstFrom+srcLen-1] = c << shift;
6203     }
6204 
6205     /**
6206      * Divide this MutableBigInteger by the divisor.
6207      * The quotient will be placed into the provided quotient object &
6208      * the remainder object is returned.
6209      */
6210     private MutableBigInteger divideMagnitude(MutableBigInteger div,
6211                                               MutableBigInteger quotient,
6212                                               bool needRemainder ) {
6213         // assert div.intLen > 1
6214         // D1 normalize the divisor
6215         int shift = Integer.numberOfLeadingZeros(div.value[div.offset]);
6216         // Copy divisor value to protect divisor
6217         int dlen = div.intLen;
6218         int[] divisor;
6219         MutableBigInteger rem; // Remainder starts as dividend with space for a leading zero
6220         if (shift > 0) {
6221             divisor = new int[dlen];
6222             copyAndShift(div.value,div.offset,dlen,divisor,0,shift);
6223             if (Integer.numberOfLeadingZeros(value[offset]) >= shift) {
6224                 int[] remarr = new int[intLen + 1];
6225                 rem = new MutableBigInteger(remarr);
6226                 rem.intLen = intLen;
6227                 rem.offset = 1;
6228                 copyAndShift(value,offset,intLen,remarr,1,shift);
6229             } else {
6230                 int[] remarr = new int[intLen + 2];
6231                 rem = new MutableBigInteger(remarr);
6232                 rem.intLen = intLen+1;
6233                 rem.offset = 1;
6234                 int rFrom = offset;
6235                 int c=0;
6236                 int n2 = 32 - shift;
6237                 for (int i=1; i < intLen+1; i++,rFrom++) {
6238                     int b = c;
6239                     c = value[rFrom];
6240                     remarr[i] = (b << shift) | (c >>> n2);
6241                 }
6242                 remarr[intLen+1] = c << shift;
6243             }
6244         } else {
6245             // divisor = Arrays.copyOfRange(div.value, div.offset, div.offset + div.intLen);
6246             divisor = div.cloneValue();
6247             rem = new MutableBigInteger(new int[intLen + 1]);
6248             // System.arraycopy(value, offset, rem.value, 1, intLen);
6249             rem.value[1 .. 1+intLen] = value[offset .. offset+intLen];
6250             rem.intLen = intLen;
6251             rem.offset = 1;
6252         }
6253 
6254         int nlen = rem.intLen;
6255 
6256         // Set the quotient size
6257         int limit = nlen - dlen + 1;
6258         if (quotient.value.length < limit) {
6259             quotient.value = new int[limit];
6260             quotient.offset = 0;
6261         }
6262         quotient.intLen = limit;
6263         int[] q = quotient.value;
6264 
6265 
6266         // Must insert leading 0 in rem if its length did not change
6267         if (rem.intLen == nlen) {
6268             rem.offset = 0;
6269             rem.value[0] = 0;
6270             rem.intLen++;
6271         }
6272 
6273         int dh = divisor[0];
6274         long dhLong = dh & LONG_MASK;
6275         int dl = divisor[1];
6276 
6277         // D2 Initialize j
6278         for (int j=0; j < limit-1; j++) {
6279             // D3 Calculate qhat
6280             // estimate qhat
6281             int qhat = 0;
6282             int qrem = 0;
6283             bool skipCorrection = false;
6284             int nh = rem.value[j+rem.offset];
6285             int nh2 = nh + 0x80000000;
6286             int nm = rem.value[j+1+rem.offset];
6287 
6288             if (nh == dh) {
6289                 qhat = ~0;
6290                 qrem = nh + nm;
6291                 skipCorrection = qrem + 0x80000000 < nh2;
6292             } else {
6293                 long nChunk = ((cast(long)nh) << 32) | (nm & LONG_MASK);
6294                 if (nChunk >= 0) {
6295                     qhat = cast(int) (nChunk / dhLong);
6296                     qrem = cast(int) (nChunk - (qhat * dhLong));
6297                 } else {
6298                     long tmp = divWord(nChunk, dh);
6299                     qhat = cast(int) (tmp & LONG_MASK);
6300                     qrem = cast(int) (tmp >>> 32);
6301                 }
6302             }
6303 
6304             if (qhat == 0)
6305                 continue;
6306 
6307             if (!skipCorrection) { // Correct qhat
6308                 long nl = rem.value[j+2+rem.offset] & LONG_MASK;
6309                 long rs = ((qrem & LONG_MASK) << 32) | nl;
6310                 long estProduct = (dl & LONG_MASK) * (qhat & LONG_MASK);
6311 
6312                 if (unsignedLongCompare(estProduct, rs)) {
6313                     qhat--;
6314                     qrem = cast(int)((qrem & LONG_MASK) + dhLong);
6315                     if ((qrem & LONG_MASK) >=  dhLong) {
6316                         estProduct -= (dl & LONG_MASK);
6317                         rs = ((qrem & LONG_MASK) << 32) | nl;
6318                         if (unsignedLongCompare(estProduct, rs))
6319                             qhat--;
6320                     }
6321                 }
6322             }
6323 
6324             // D4 Multiply and subtract
6325             rem.value[j+rem.offset] = 0;
6326             int borrow = mulsub(rem.value, divisor, qhat, dlen, j+rem.offset);
6327 
6328             // D5 Test remainder
6329             if (borrow + 0x80000000 > nh2) {
6330                 // D6 Add back
6331                 divadd(divisor, rem.value, j+1+rem.offset);
6332                 qhat--;
6333             }
6334 
6335             // Store the quotient digit
6336             q[j] = qhat;
6337         } // D7 loop on j
6338         // D3 Calculate qhat
6339         // estimate qhat
6340         int qhat = 0;
6341         int qrem = 0;
6342         bool skipCorrection = false;
6343         int nh = rem.value[limit - 1 + rem.offset];
6344         int nh2 = nh + 0x80000000;
6345         int nm = rem.value[limit + rem.offset];
6346 
6347         if (nh == dh) {
6348             qhat = ~0;
6349             qrem = nh + nm;
6350             skipCorrection = qrem + 0x80000000 < nh2;
6351         } else {
6352             long nChunk = ((cast(long) nh) << 32) | (nm & LONG_MASK);
6353             if (nChunk >= 0) {
6354                 qhat = cast(int) (nChunk / dhLong);
6355                 qrem = cast(int) (nChunk - (qhat * dhLong));
6356             } else {
6357                 long tmp = divWord(nChunk, dh);
6358                 qhat = cast(int) (tmp & LONG_MASK);
6359                 qrem = cast(int) (tmp >>> 32);
6360             }
6361         }
6362         if (qhat != 0) {
6363             if (!skipCorrection) { // Correct qhat
6364                 long nl = rem.value[limit + 1 + rem.offset] & LONG_MASK;
6365                 long rs = ((qrem & LONG_MASK) << 32) | nl;
6366                 long estProduct = (dl & LONG_MASK) * (qhat & LONG_MASK);
6367 
6368                 if (unsignedLongCompare(estProduct, rs)) {
6369                     qhat--;
6370                     qrem = cast(int) ((qrem & LONG_MASK) + dhLong);
6371                     if ((qrem & LONG_MASK) >= dhLong) {
6372                         estProduct -= (dl & LONG_MASK);
6373                         rs = ((qrem & LONG_MASK) << 32) | nl;
6374                         if (unsignedLongCompare(estProduct, rs))
6375                             qhat--;
6376                     }
6377                 }
6378             }
6379 
6380 
6381             // D4 Multiply and subtract
6382             int borrow;
6383             rem.value[limit - 1 + rem.offset] = 0;
6384             if(needRemainder)
6385                 borrow = mulsub(rem.value, divisor, qhat, dlen, limit - 1 + rem.offset);
6386             else
6387                 borrow = mulsubBorrow(rem.value, divisor, qhat, dlen, limit - 1 + rem.offset);
6388 
6389             // D5 Test remainder
6390             if (borrow + 0x80000000 > nh2) {
6391                 // D6 Add back
6392                 if(needRemainder)
6393                     divadd(divisor, rem.value, limit - 1 + 1 + rem.offset);
6394                 qhat--;
6395             }
6396 
6397             // Store the quotient digit
6398             q[(limit - 1)] = qhat;
6399         }
6400 
6401 
6402         if (needRemainder) {
6403             // D8 Unnormalize
6404             if (shift > 0)
6405                 rem.rightShift(shift);
6406             rem.normalize();
6407         }
6408         quotient.normalize();
6409         return needRemainder ? rem : null;
6410     }
6411 
6412     /**
6413      * Divide this MutableBigInteger by the divisor represented by positive long
6414      * value. The quotient will be placed into the provided quotient object &
6415      * the remainder object is returned.
6416      */
6417     private MutableBigInteger divideLongMagnitude(long ldivisor, MutableBigInteger quotient) {
6418         // Remainder starts as dividend with space for a leading zero
6419         MutableBigInteger rem = new MutableBigInteger(new int[intLen + 1]);
6420         // System.arraycopy(value, offset, rem.value, 1, intLen);
6421         rem.value[1 .. 1+intLen] = value[offset .. offset+intLen].dup;
6422         rem.intLen = intLen;
6423         rem.offset = 1;
6424 
6425         int nlen = rem.intLen;
6426 
6427         int limit = nlen - 2 + 1;
6428         if (quotient.value.length < limit) {
6429             quotient.value = new int[limit];
6430             quotient.offset = 0;
6431         }
6432         quotient.intLen = limit;
6433         int[] q = quotient.value;
6434 
6435         // D1 normalize the divisor
6436         int shift = Long.numberOfLeadingZeros(ldivisor);
6437         if (shift > 0) {
6438             ldivisor<<=shift;
6439             rem.leftShift(shift);
6440         }
6441 
6442         // Must insert leading 0 in rem if its length did not change
6443         if (rem.intLen == nlen) {
6444             rem.offset = 0;
6445             rem.value[0] = 0;
6446             rem.intLen++;
6447         }
6448 
6449         int dh = cast(int)(ldivisor >>> 32);
6450         long dhLong = dh & LONG_MASK;
6451         int dl = cast(int)(ldivisor & LONG_MASK);
6452 
6453         // D2 Initialize j
6454         for (int j = 0; j < limit; j++) {
6455             // D3 Calculate qhat
6456             // estimate qhat
6457             int qhat = 0;
6458             int qrem = 0;
6459             bool skipCorrection = false;
6460             int nh = rem.value[j + rem.offset];
6461             int nh2 = nh + 0x80000000;
6462             int nm = rem.value[j + 1 + rem.offset];
6463 
6464             if (nh == dh) {
6465                 qhat = ~0;
6466                 qrem = nh + nm;
6467                 skipCorrection = qrem + 0x80000000 < nh2;
6468             } else {
6469                 long nChunk = ((cast(long) nh) << 32) | (nm & LONG_MASK);
6470                 if (nChunk >= 0) {
6471                     qhat = cast(int) (nChunk / dhLong);
6472                     qrem = cast(int) (nChunk - (qhat * dhLong));
6473                 } else {
6474                     long tmp = divWord(nChunk, dh);
6475                     qhat = cast(int)(tmp & LONG_MASK);
6476                     qrem = cast(int)(tmp>>>32);
6477                 }
6478             }
6479 
6480             if (qhat == 0)
6481                 continue;
6482 
6483             if (!skipCorrection) { // Correct qhat
6484                 long nl = rem.value[j + 2 + rem.offset] & LONG_MASK;
6485                 long rs = ((qrem & LONG_MASK) << 32) | nl;
6486                 long estProduct = (dl & LONG_MASK) * (qhat & LONG_MASK);
6487 
6488                 if (unsignedLongCompare(estProduct, rs)) {
6489                     qhat--;
6490                     qrem = cast(int) ((qrem & LONG_MASK) + dhLong);
6491                     if ((qrem & LONG_MASK) >= dhLong) {
6492                         estProduct -= (dl & LONG_MASK);
6493                         rs = ((qrem & LONG_MASK) << 32) | nl;
6494                         if (unsignedLongCompare(estProduct, rs))
6495                             qhat--;
6496                     }
6497                 }
6498             }
6499 
6500             // D4 Multiply and subtract
6501             rem.value[j + rem.offset] = 0;
6502             int borrow = mulsubLong(rem.value, dh, dl, qhat,  j + rem.offset);
6503 
6504             // D5 Test remainder
6505             if (borrow + 0x80000000 > nh2) {
6506                 // D6 Add back
6507                 divaddLong(dh,dl, rem.value, j + 1 + rem.offset);
6508                 qhat--;
6509             }
6510 
6511             // Store the quotient digit
6512             q[j] = qhat;
6513         } // D7 loop on j
6514 
6515         // D8 Unnormalize
6516         if (shift > 0)
6517             rem.rightShift(shift);
6518 
6519         quotient.normalize();
6520         rem.normalize();
6521         return rem;
6522     }
6523 
6524     /**
6525      * A primitive used for division by long.
6526      * Specialized version of the method divadd.
6527      * dh is a high part of the divisor, dl is a low part
6528      */
6529     private int divaddLong(int dh, int dl, int[] result, int offset) {
6530         long carry = 0;
6531 
6532         long sum = (dl & LONG_MASK) + (result[1+offset] & LONG_MASK);
6533         result[1+offset] = cast(int)sum;
6534 
6535         sum = (dh & LONG_MASK) + (result[offset] & LONG_MASK) + carry;
6536         result[offset] = cast(int)sum;
6537         carry = sum >>> 32;
6538         return cast(int)carry;
6539     }
6540 
6541     /**
6542      * This method is used for division by long.
6543      * Specialized version of the method sulsub.
6544      * dh is a high part of the divisor, dl is a low part
6545      */
6546     private int mulsubLong(int[] q, int dh, int dl, int x, int offset) {
6547         long xLong = x & LONG_MASK;
6548         offset += 2;
6549         long product = (dl & LONG_MASK) * xLong;
6550         long difference = q[offset] - product;
6551         q[offset--] = cast(int)difference;
6552         long carry = (product >>> 32)
6553                  + (((difference & LONG_MASK) >
6554                      (((~cast(int)product) & LONG_MASK))) ? 1:0);
6555         product = (dh & LONG_MASK) * xLong + carry;
6556         difference = q[offset] - product;
6557         q[offset--] = cast(int)difference;
6558         carry = (product >>> 32)
6559                  + (((difference & LONG_MASK) >
6560                      (((~cast(int)product) & LONG_MASK))) ? 1:0);
6561         return cast(int)carry;
6562     }
6563 
6564     /**
6565      * Compare two longs as if they were unsigned.
6566      * Returns true iff one is bigger than two.
6567      */
6568     private bool unsignedLongCompare(long one, long two) {
6569         return (one+long.min) > (two+long.min);
6570     }
6571 
6572     /**
6573      * This method divides a long quantity by an int to estimate
6574      * qhat for two multi precision numbers. It is used when
6575      * the signed value of n is less than zero.
6576      * Returns long value where high 32 bits contain remainder value and
6577      * low 32 bits contain quotient value.
6578      */
6579     static long divWord(long n, int d) {
6580         long dLong = d & LONG_MASK;
6581         long r;
6582         long q;
6583         if (dLong == 1) {
6584             q = cast(int)n;
6585             r = 0;
6586             return (r << 32) | (q & LONG_MASK);
6587         }
6588 
6589         // Approximate the quotient and remainder
6590         q = (n >>> 1) / (dLong >>> 1);
6591         r = n - q*dLong;
6592 
6593         // Correct the approximation
6594         while (r < 0) {
6595             r += dLong;
6596             q--;
6597         }
6598         while (r >= dLong) {
6599             r -= dLong;
6600             q++;
6601         }
6602         // n - q*dlong == r && 0 <= r <dLong, hence we're done.
6603         return (r << 32) | (q & LONG_MASK);
6604     }
6605 
6606     /**
6607      * Calculate the integer square root {@code floor(sqrt(this))} where
6608      * {@code sqrt(.)} denotes the mathematical square root. The contents of
6609      * {@code this} are <b>not</b> changed. The value of {@code this} is assumed
6610      * to be non-negative.
6611      *
6612      * @implNote The implementation is based on the material in Henry S. Warren,
6613      * Jr., <i>Hacker's Delight (2nd ed.)</i> (Addison Wesley, 2013), 279-282.
6614      *
6615      * @throws ArithmeticException if the value returned by {@code bitLength()}
6616      * overflows the range of {@code int}.
6617      * @return the integer square root of {@code this}
6618      */
6619     MutableBigInteger sqrt() {
6620         // Special cases.
6621         if (this.isZero()) {
6622             return new MutableBigInteger(0);
6623         } else if (this.value.length == 1
6624                 && (this.value[0] & LONG_MASK) < 4) { // result is unity
6625             return ONE;
6626         }
6627 
6628         if (bitLength() <= 63) {
6629             // Initial estimate is the square root of the positive long value.
6630             long v = new BigInteger(this.value, 1).longValueExact();
6631             long xk = cast(long)std.math.floor(std.math.sqrt(cast(float)v));
6632 
6633             // Refine the estimate.
6634             do {
6635                 long xk1 = (xk + v/xk)/2;
6636 
6637                 // Terminate when non-decreasing.
6638                 if (xk1 >= xk) {
6639                     return new MutableBigInteger( [cast(int)(xk >>> 32), 
6640                         cast(int)(xk & LONG_MASK)] );
6641                 }
6642 
6643                 xk = xk1;
6644             } while (true);
6645         } else {
6646             // Set up the initial estimate of the iteration.
6647 
6648             // Obtain the bitLength > 63.
6649             int bitLength = cast(int) this.bitLength();
6650             if (bitLength != this.bitLength()) {
6651                 throw new ArithmeticException("bitLength() integer overflow");
6652             }
6653 
6654             // Determine an even valued right shift into positive long range.
6655             int shift = bitLength - 63;
6656             if (shift % 2 == 1) {
6657                 shift++;
6658             }
6659 
6660             // Shift the value into positive long range.
6661             MutableBigInteger xk = new MutableBigInteger(this);
6662             xk.rightShift(shift);
6663             xk.normalize();
6664 
6665             // Use the square root of the shifted value as an approximation.
6666             double d = new BigInteger(xk.value, 1).doubleValue();
6667             BigInteger bi = BigInteger.valueOf(cast(long)std.math.ceil(std.math.sqrt(d)));
6668             xk = new MutableBigInteger(bi.mag);
6669 
6670             // Shift the approximate square root back into the original range.
6671             xk.leftShift(shift / 2);
6672 
6673             // Refine the estimate.
6674             MutableBigInteger xk1 = new MutableBigInteger();
6675             do {
6676                 // xk1 = (xk + n/xk)/2
6677                 this.divide(xk, xk1, false);
6678                 xk1.add(xk);
6679                 xk1.rightShift(1);
6680 
6681                 // Terminate when non-decreasing.
6682                 if (xk1.compare(xk) >= 0) {
6683                     return xk;
6684                 }
6685 
6686                 // xk = xk1
6687                 xk.copyValue(xk1);
6688 
6689                 xk1.reset();
6690             } while (true);
6691         }
6692     }
6693 
6694     /**
6695      * Calculate GCD of this and b. This and b are changed by the computation.
6696      */
6697     MutableBigInteger hybridGCD(MutableBigInteger b) {
6698         // Use Euclid's algorithm until the numbers are approximately the
6699         // same length, then use the binary GCD algorithm to find the GCD.
6700         MutableBigInteger a = this;
6701         MutableBigInteger q = new MutableBigInteger();
6702 
6703         while (b.intLen != 0) {
6704             if (std.math.abs(a.intLen - b.intLen) < 2)
6705                 return a.binaryGCD(b);
6706 
6707             MutableBigInteger r = a.divide(b, q);
6708             a = b;
6709             b = r;
6710         }
6711         return a;
6712     }
6713 
6714     /**
6715      * Calculate GCD of this and v.
6716      * Assumes that this and v are not zero.
6717      */
6718     private MutableBigInteger binaryGCD(MutableBigInteger v) {
6719         // Algorithm B from Knuth section 4.5.2
6720         MutableBigInteger u = this;
6721         MutableBigInteger r = new MutableBigInteger();
6722 
6723         // step B1
6724         int s1 = u.getLowestSetBit();
6725         int s2 = v.getLowestSetBit();
6726         int k = (s1 < s2) ? s1 : s2;
6727         if (k != 0) {
6728             u.rightShift(k);
6729             v.rightShift(k);
6730         }
6731 
6732         // step B2
6733         bool uOdd = (k == s1);
6734         MutableBigInteger t = uOdd ? v: u;
6735         int tsign = uOdd ? -1 : 1;
6736 
6737         int lb;
6738         while ((lb = t.getLowestSetBit()) >= 0) {
6739             // steps B3 and B4
6740             t.rightShift(lb);
6741             // step B5
6742             if (tsign > 0)
6743                 u = t;
6744             else
6745                 v = t;
6746 
6747             // Special case one word numbers
6748             if (u.intLen < 2 && v.intLen < 2) {
6749                 int x = u.value[u.offset];
6750                 int y = v.value[v.offset];
6751                 x  = binaryGcd(x, y);
6752                 r.value[0] = x;
6753                 r.intLen = 1;
6754                 r.offset = 0;
6755                 if (k > 0)
6756                     r.leftShift(k);
6757                 return r;
6758             }
6759 
6760             // step B6
6761             if ((tsign = u.difference(v)) == 0)
6762                 break;
6763             t = (tsign >= 0) ? u : v;
6764         }
6765 
6766         if (k > 0)
6767             u.leftShift(k);
6768         return u;
6769     }
6770 
6771     /**
6772      * Calculate GCD of a and b interpreted as unsigned integers.
6773      */
6774     static int binaryGcd(int a, int b) {
6775         if (b == 0)
6776             return a;
6777         if (a == 0)
6778             return b;
6779 
6780         // Right shift a & b till their last bits equal to 1.
6781         int aZeros = Integer.numberOfTrailingZeros(a);
6782         int bZeros = Integer.numberOfTrailingZeros(b);
6783         a >>>= aZeros;
6784         b >>>= bZeros;
6785 
6786         int t = (aZeros < bZeros ? aZeros : bZeros);
6787 
6788         while (a != b) {
6789             if ((a+0x80000000) > (b+0x80000000)) {  // a > b as unsigned
6790                 a -= b;
6791                 a >>>= Integer.numberOfTrailingZeros(a);
6792             } else {
6793                 b -= a;
6794                 b >>>= Integer.numberOfTrailingZeros(b);
6795             }
6796         }
6797         return a<<t;
6798     }
6799 
6800     /**
6801      * Returns the modInverse of this mod p. This and p are not affected by
6802      * the operation.
6803      */
6804     MutableBigInteger mutableModInverse(MutableBigInteger p) {
6805         // Modulus is odd, use Schroeppel's algorithm
6806         if (p.isOdd())
6807             return modInverse(p);
6808 
6809         // Base and modulus are even, throw exception
6810         if (isEven())
6811             throw new ArithmeticException("BigInteger not invertible.");
6812 
6813         // Get even part of modulus expressed as a power of 2
6814         int powersOf2 = p.getLowestSetBit();
6815 
6816         // Construct odd part of modulus
6817         MutableBigInteger oddMod = new MutableBigInteger(p);
6818         oddMod.rightShift(powersOf2);
6819 
6820         if (oddMod.isOne())
6821             return modInverseMP2(powersOf2);
6822 
6823         // Calculate 1/a mod oddMod
6824         MutableBigInteger oddPart = modInverse(oddMod);
6825 
6826         // Calculate 1/a mod evenMod
6827         MutableBigInteger evenPart = modInverseMP2(powersOf2);
6828 
6829         // Combine the results using Chinese Remainder Theorem
6830         MutableBigInteger y1 = modInverseBP2(oddMod, powersOf2);
6831         MutableBigInteger y2 = oddMod.modInverseMP2(powersOf2);
6832 
6833         MutableBigInteger temp1 = new MutableBigInteger();
6834         MutableBigInteger temp2 = new MutableBigInteger();
6835         MutableBigInteger result = new MutableBigInteger();
6836 
6837         oddPart.leftShift(powersOf2);
6838         oddPart.multiply(y1, result);
6839 
6840         evenPart.multiply(oddMod, temp1);
6841         temp1.multiply(y2, temp2);
6842 
6843         result.add(temp2);
6844         return result.divide(p, temp1);
6845     }
6846 
6847     /*
6848      * Calculate the multiplicative inverse of this mod 2^k.
6849      */
6850     MutableBigInteger modInverseMP2(int k) {
6851         if (isEven())
6852             throw new ArithmeticException("Non-invertible. (GCD != 1)");
6853 
6854         if (k > 64)
6855             return euclidModInverse(k);
6856 
6857         int t = inverseMod32(value[offset+intLen-1]);
6858 
6859         if (k < 33) {
6860             t = (k == 32 ? t : t & ((1 << k) - 1));
6861             return new MutableBigInteger(t);
6862         }
6863 
6864         long pLong = (value[offset+intLen-1] & LONG_MASK);
6865         if (intLen > 1)
6866             pLong |=  (cast(long)value[offset+intLen-2] << 32);
6867         long tLong = t & LONG_MASK;
6868         tLong = tLong * (2 - pLong * tLong);  // 1 more Newton iter step
6869         tLong = (k == 64 ? tLong : tLong & ((1L << k) - 1));
6870 
6871         MutableBigInteger result = new MutableBigInteger(new int[2]);
6872         result.value[0] = cast(int)(tLong >>> 32);
6873         result.value[1] = cast(int)tLong;
6874         result.intLen = 2;
6875         result.normalize();
6876         return result;
6877     }
6878 
6879     /**
6880      * Returns the multiplicative inverse of val mod 2^32.  Assumes val is odd.
6881      */
6882     static int inverseMod32(int val) {
6883         // Newton's iteration!
6884         int t = val;
6885         t *= 2 - val*t;
6886         t *= 2 - val*t;
6887         t *= 2 - val*t;
6888         t *= 2 - val*t;
6889         return t;
6890     }
6891 
6892     /**
6893      * Returns the multiplicative inverse of val mod 2^64.  Assumes val is odd.
6894      */
6895     static long inverseMod64(long val) {
6896         // Newton's iteration!
6897         long t = val;
6898         t *= 2 - val*t;
6899         t *= 2 - val*t;
6900         t *= 2 - val*t;
6901         t *= 2 - val*t;
6902         t *= 2 - val*t;
6903         assert(t * val == 1);
6904         return t;
6905     }
6906 
6907     /**
6908      * Calculate the multiplicative inverse of 2^k mod mod, where mod is odd.
6909      */
6910     static MutableBigInteger modInverseBP2(MutableBigInteger mod, int k) {
6911         // Copy the mod to protect original
6912         return fixup(new MutableBigInteger(1), new MutableBigInteger(mod), k);
6913     }
6914 
6915     /**
6916      * Calculate the multiplicative inverse of this mod mod, where mod is odd.
6917      * This and mod are not changed by the calculation.
6918      *
6919      * This method implements an algorithm due to Richard Schroeppel, that uses
6920      * the same intermediate representation as Montgomery Reduction
6921      * ("Montgomery Form").  The algorithm is described in an unpublished
6922      * manuscript entitled "Fast Modular Reciprocals."
6923      */
6924     private MutableBigInteger modInverse(MutableBigInteger mod) {
6925         MutableBigInteger p = new MutableBigInteger(mod);
6926         MutableBigInteger f = new MutableBigInteger(this);
6927         MutableBigInteger g = new MutableBigInteger(p);
6928         SignedMutableBigInteger c = new SignedMutableBigInteger(1);
6929         SignedMutableBigInteger d = new SignedMutableBigInteger();
6930         MutableBigInteger temp = null;
6931         SignedMutableBigInteger sTemp = null;
6932 
6933         int k = 0;
6934         // Right shift f k times until odd, left shift d k times
6935         if (f.isEven()) {
6936             int trailingZeros = f.getLowestSetBit();
6937             f.rightShift(trailingZeros);
6938             d.leftShift(trailingZeros);
6939             k = trailingZeros;
6940         }
6941 
6942         // The Almost Inverse Algorithm
6943         while (!f.isOne()) {
6944             // If gcd(f, g) != 1, number is not invertible modulo mod
6945             if (f.isZero())
6946                 throw new ArithmeticException("BigInteger not invertible.");
6947 
6948             // If f < g exchange f, g and c, d
6949             if (f.compare(g) < 0) {
6950                 temp = f; f = g; g = temp;
6951                 sTemp = d; d = c; c = sTemp;
6952             }
6953 
6954             // If f == g (mod 4)
6955             if (((f.value[f.offset + f.intLen - 1] ^
6956                  g.value[g.offset + g.intLen - 1]) & 3) == 0) {
6957                 f.subtract(g);
6958                 c.signedSubtract(d);
6959             } else { // If f != g (mod 4)
6960                 f.add(g);
6961                 c.signedAdd(d);
6962             }
6963 
6964             // Right shift f k times until odd, left shift d k times
6965             int trailingZeros = f.getLowestSetBit();
6966             f.rightShift(trailingZeros);
6967             d.leftShift(trailingZeros);
6968             k += trailingZeros;
6969         }
6970 
6971         while (c.sign < 0)
6972            c.signedAdd(p);
6973 
6974         return fixup(c, p, k);
6975     }
6976 
6977     /**
6978      * The Fixup Algorithm
6979      * Calculates X such that X = C * 2^(-k) (mod P)
6980      * Assumes C<P and P is odd.
6981      */
6982     static MutableBigInteger fixup(MutableBigInteger c, MutableBigInteger p,
6983                                                                       int k) {
6984         MutableBigInteger temp = new MutableBigInteger();
6985         // Set r to the multiplicative inverse of p mod 2^32
6986         int r = -inverseMod32(p.value[p.offset+p.intLen-1]);
6987 
6988         for (int i=0, numWords = k >> 5; i < numWords; i++) {
6989             // V = R * c (mod 2^j)
6990             int  v = r * c.value[c.offset + c.intLen-1];
6991             // c = c + (v * p)
6992             p.mul(v, temp);
6993             c.add(temp);
6994             // c = c / 2^j
6995             c.intLen--;
6996         }
6997         int numBits = k & 0x1f;
6998         if (numBits != 0) {
6999             // V = R * c (mod 2^j)
7000             int v = r * c.value[c.offset + c.intLen-1];
7001             v &= ((1<<numBits) - 1);
7002             // c = c + (v * p)
7003             p.mul(v, temp);
7004             c.add(temp);
7005             // c = c / 2^j
7006             c.rightShift(numBits);
7007         }
7008 
7009         // In theory, c may be greater than p at this point (Very rare!)
7010         while (c.compare(p) >= 0)
7011             c.subtract(p);
7012 
7013         return c;
7014     }
7015 
7016     /**
7017      * Uses the extended Euclidean algorithm to compute the modInverse of base
7018      * mod a modulus that is a power of 2. The modulus is 2^k.
7019      */
7020     MutableBigInteger euclidModInverse(int k) {
7021         MutableBigInteger b = new MutableBigInteger(1);
7022         b.leftShift(k);
7023         MutableBigInteger mod = new MutableBigInteger(b);
7024 
7025         MutableBigInteger a = new MutableBigInteger(this);
7026         MutableBigInteger q = new MutableBigInteger();
7027         MutableBigInteger r = b.divide(a, q);
7028 
7029         MutableBigInteger swapper = b;
7030         // swap b & r
7031         b = r;
7032         r = swapper;
7033 
7034         MutableBigInteger t1 = new MutableBigInteger(q);
7035         MutableBigInteger t0 = new MutableBigInteger(1);
7036         MutableBigInteger temp = new MutableBigInteger();
7037 
7038         while (!b.isOne()) {
7039             r = a.divide(b, q);
7040 
7041             if (r.intLen == 0)
7042                 throw new ArithmeticException("BigInteger not invertible.");
7043 
7044             swapper = r;
7045             a = swapper;
7046 
7047             if (q.intLen == 1)
7048                 t1.mul(q.value[q.offset], temp);
7049             else
7050                 q.multiply(t1, temp);
7051             swapper = q;
7052             q = temp;
7053             temp = swapper;
7054             t0.add(q);
7055 
7056             if (a.isOne())
7057                 return t0;
7058 
7059             r = b.divide(a, q);
7060 
7061             if (r.intLen == 0)
7062                 throw new ArithmeticException("BigInteger not invertible.");
7063 
7064             swapper = b;
7065             b =  r;
7066 
7067             if (q.intLen == 1)
7068                 t0.mul(q.value[q.offset], temp);
7069             else
7070                 q.multiply(t0, temp);
7071             swapper = q; q = temp; temp = swapper;
7072 
7073             t1.add(q);
7074         }
7075         mod.subtract(t1);
7076         return mod;
7077     }
7078 }
7079 
7080 
7081 
7082 /**
7083  * A class used to represent multiprecision integers that makes efficient
7084  * use of allocated space by allowing a number to occupy only part of
7085  * an array so that the arrays do not have to be reallocated as often.
7086  * When performing an operation with many iterations the array used to
7087  * hold a number is only increased when necessary and does not have to
7088  * be the same size as the number it represents. A mutable number allows
7089  * calculations to occur on the same number without having to create
7090  * a new number for every step of the calculation as occurs with
7091  * BigIntegers.
7092  *
7093  * Note that SignedMutableBigIntegers only support signed addition and
7094  * subtraction. All other operations occur as with MutableBigIntegers.
7095  *
7096  * @see     BigInteger
7097  * @author  Michael McCloskey
7098  */
7099 
7100 class SignedMutableBigInteger : MutableBigInteger {
7101 
7102    /**
7103      * The sign of this MutableBigInteger.
7104      */
7105     int sign = 1;
7106 
7107     // Constructors
7108 
7109     /**
7110      * The default constructor. An empty MutableBigInteger is created with
7111      * a one word capacity.
7112      */
7113     this() {
7114         super();
7115     }
7116 
7117     /**
7118      * Construct a new MutableBigInteger with a magnitude specified by
7119      * the int val.
7120      */
7121     this(int val) {
7122         super(val);
7123     }
7124 
7125     /**
7126      * Construct a new MutableBigInteger with a magnitude equal to the
7127      * specified MutableBigInteger.
7128      */
7129     this(MutableBigInteger val) {
7130         super(val);
7131     }
7132 
7133    // Arithmetic Operations
7134 
7135    /**
7136      * Signed addition built upon unsigned add and subtract.
7137      */
7138     void signedAdd(SignedMutableBigInteger addend) {
7139         if (sign == addend.sign)
7140             add(addend);
7141         else
7142             sign = sign * subtract(addend);
7143 
7144     }
7145 
7146    /**
7147      * Signed addition built upon unsigned add and subtract.
7148      */
7149     void signedAdd(MutableBigInteger addend) {
7150         if (sign == 1)
7151             add(addend);
7152         else
7153             sign = sign * subtract(addend);
7154 
7155     }
7156 
7157    /**
7158      * Signed subtraction built upon unsigned add and subtract.
7159      */
7160     void signedSubtract(SignedMutableBigInteger addend) {
7161         if (sign == addend.sign)
7162             sign = sign * subtract(addend);
7163         else
7164             add(addend);
7165 
7166     }
7167 
7168    /**
7169      * Signed subtraction built upon unsigned add and subtract.
7170      */
7171     void signedSubtract(MutableBigInteger addend) {
7172         if (sign == 1)
7173             sign = sign * subtract(addend);
7174         else
7175             add(addend);
7176         if (intLen == 0)
7177              sign = 1;
7178     }
7179 
7180     /**
7181      * Print out the first intLen ints of this MutableBigInteger's value
7182      * array starting at offset.
7183      */
7184     override string toString() {
7185         return this.toBigInteger(sign).toString();
7186     }
7187 
7188 }
7189 
7190 
7191 
7192 /**
7193  * A simple bit sieve used for finding prime number candidates. Allows setting
7194  * and clearing of bits in a storage array. The size of the sieve is assumed to
7195  * be constant to reduce overhead. All the bits of a new bitSieve are zero, and
7196  * bits are removed from it by setting them.
7197  *
7198  * To reduce storage space and increase efficiency, no even numbers are
7199  * represented in the sieve (each bit in the sieve represents an odd number).
7200  * The relationship between the index of a bit and the number it represents is
7201  * given by
7202  * N = offset + (2*index + 1);
7203  * Where N is the integer represented by a bit in the sieve, offset is some
7204  * even integer offset indicating where the sieve begins, and index is the
7205  * index of a bit in the sieve array.
7206  *
7207  * @see     BigInteger
7208  * @author  Michael McCloskey
7209  */
7210 class BitSieve {
7211     /**
7212      * Stores the bits in this bitSieve.
7213      */
7214     private long[] bits;
7215 
7216     /**
7217      * Length is how many bits this sieve holds.
7218      */
7219     private int length;
7220 
7221     /**
7222      * A small sieve used to filter out multiples of small primes in a search
7223      * sieve.
7224      */
7225     private __gshared BitSieve smallSieve;
7226 
7227     shared static this() {
7228         smallSieve = new BitSieve();
7229     }
7230 
7231     /**
7232      * Construct a "small sieve" with a base of 0.  This constructor is
7233      * used internally to generate the set of "small primes" whose multiples
7234      * are excluded from sieves generated by the main (package private)
7235      * constructor, BitSieve(BigInteger base, int searchLen).  The length
7236      * of the sieve generated by this constructor was chosen for performance;
7237      * it controls a tradeoff between how much time is spent constructing
7238      * other sieves, and how much time is wasted testing composite candidates
7239      * for primality.  The length was chosen experimentally to yield good
7240      * performance.
7241      */
7242     private this() {
7243         length = 150 * 64;
7244         bits = new long[(unitIndex(length - 1) + 1)];
7245 
7246         // Mark 1 as composite
7247         set(0);
7248         int nextIndex = 1;
7249         int nextPrime = 3;
7250 
7251         // Find primes and remove their multiples from sieve
7252         do {
7253             sieveSingle(length, nextIndex + nextPrime, nextPrime);
7254             nextIndex = sieveSearch(length, nextIndex + 1);
7255             nextPrime = 2*nextIndex + 1;
7256         } while((nextIndex > 0) && (nextPrime < length));
7257     }
7258 
7259     /**
7260      * Construct a bit sieve of searchLen bits used for finding prime number
7261      * candidates. The new sieve begins at the specified base, which must
7262      * be even.
7263      */
7264     this(BigInteger base, int searchLen) {
7265         /*
7266          * Candidates are indicated by clear bits in the sieve. As a candidates
7267          * nonprimality is calculated, a bit is set in the sieve to eliminate
7268          * it. To reduce storage space and increase efficiency, no even numbers
7269          * are represented in the sieve (each bit in the sieve represents an
7270          * odd number).
7271          */
7272         bits = new long[(unitIndex(searchLen-1) + 1)];
7273         length = searchLen;
7274         int start = 0;
7275 
7276         int step = smallSieve.sieveSearch(smallSieve.length, start);
7277         int convertedStep = (step *2) + 1;
7278 
7279         // Construct the large sieve at an even offset specified by base
7280         MutableBigInteger b = new MutableBigInteger(base);
7281         MutableBigInteger q = new MutableBigInteger();
7282         do {
7283             // Calculate base mod convertedStep
7284             start = b.divideOneWord(convertedStep, q);
7285 
7286             // Take each multiple of step out of sieve
7287             start = convertedStep - start;
7288             if (start%2 == 0)
7289                 start += convertedStep;
7290             sieveSingle(searchLen, (start-1)/2, convertedStep);
7291 
7292             // Find next prime from small sieve
7293             step = smallSieve.sieveSearch(smallSieve.length, step+1);
7294             convertedStep = (step *2) + 1;
7295         } while (step > 0);
7296     }
7297 
7298     /**
7299      * Given a bit index return unit index containing it.
7300      */
7301     private static int unitIndex(int bitIndex) {
7302         return bitIndex >>> 6;
7303     }
7304 
7305     /**
7306      * Return a unit that masks the specified bit in its unit.
7307      */
7308     private static long bit(int bitIndex) {
7309         return 1L << (bitIndex & ((1<<6) - 1));
7310     }
7311 
7312     /**
7313      * Get the value of the bit at the specified index.
7314      */
7315     private bool get(int bitIndex) {
7316         int unitIndex = unitIndex(bitIndex);
7317         return ((bits[unitIndex] & bit(bitIndex)) != 0);
7318     }
7319 
7320     /**
7321      * Set the bit at the specified index.
7322      */
7323     private void set(int bitIndex) {
7324         int unitIndex = unitIndex(bitIndex);
7325         bits[unitIndex] |= bit(bitIndex);
7326     }
7327 
7328     /**
7329      * This method returns the index of the first clear bit in the search
7330      * array that occurs at or after start. It will not search past the
7331      * specified limit. It returns -1 if there is no such clear bit.
7332      */
7333     private int sieveSearch(int limit, int start) {
7334         if (start >= limit)
7335             return -1;
7336 
7337         int index = start;
7338         do {
7339             if (!get(index))
7340                 return index;
7341             index++;
7342         } while(index < limit-1);
7343         return -1;
7344     }
7345 
7346     /**
7347      * Sieve a single set of multiples out of the sieve. Begin to remove
7348      * multiples of the specified step starting at the specified start index,
7349      * up to the specified limit.
7350      */
7351     private void sieveSingle(int limit, int start, int step) {
7352         while(start < limit) {
7353             set(start);
7354             start += step;
7355         }
7356     }
7357 
7358     /**
7359      * Test probable primes in the sieve and return successful candidates.
7360      */
7361     BigInteger retrieve(BigInteger initValue, int certainty, Random* random) {
7362         // Examine the sieve one long at a time to find possible primes
7363         int offset = 1;
7364         for (int i=0; i<bits.length; i++) {
7365             long nextLong = ~bits[i];
7366             for (int j=0; j<64; j++) {
7367                 if ((nextLong & 1) == 1) {
7368                     BigInteger candidate = initValue.add(
7369                                            BigInteger.valueOf(offset));
7370                     if (candidate.primeToCertainty(certainty, random))
7371                         return candidate;
7372                 }
7373                 nextLong >>>= 1;
7374                 offset+=2;
7375             }
7376         }
7377         return null;
7378     }
7379 
7380 }