emul/compact/src/main/java/java/math/MutableBigInteger.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Sat, 07 Sep 2013 13:51:24 +0200
branchjdk7-b147
changeset 1258 724f3e1ea53e
permissions -rw-r--r--
Additional set of classes to make porting of lookup library more easier
jaroslav@1258
     1
/*
jaroslav@1258
     2
 * Copyright (c) 1999, 2007, Oracle and/or its affiliates. All rights reserved.
jaroslav@1258
     3
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
jaroslav@1258
     4
 *
jaroslav@1258
     5
 * This code is free software; you can redistribute it and/or modify it
jaroslav@1258
     6
 * under the terms of the GNU General Public License version 2 only, as
jaroslav@1258
     7
 * published by the Free Software Foundation.  Oracle designates this
jaroslav@1258
     8
 * particular file as subject to the "Classpath" exception as provided
jaroslav@1258
     9
 * by Oracle in the LICENSE file that accompanied this code.
jaroslav@1258
    10
 *
jaroslav@1258
    11
 * This code is distributed in the hope that it will be useful, but WITHOUT
jaroslav@1258
    12
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
jaroslav@1258
    13
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
jaroslav@1258
    14
 * version 2 for more details (a copy is included in the LICENSE file that
jaroslav@1258
    15
 * accompanied this code).
jaroslav@1258
    16
 *
jaroslav@1258
    17
 * You should have received a copy of the GNU General Public License version
jaroslav@1258
    18
 * 2 along with this work; if not, write to the Free Software Foundation,
jaroslav@1258
    19
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
jaroslav@1258
    20
 *
jaroslav@1258
    21
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
jaroslav@1258
    22
 * or visit www.oracle.com if you need additional information or have any
jaroslav@1258
    23
 * questions.
jaroslav@1258
    24
 */
jaroslav@1258
    25
jaroslav@1258
    26
package java.math;
jaroslav@1258
    27
jaroslav@1258
    28
/**
jaroslav@1258
    29
 * A class used to represent multiprecision integers that makes efficient
jaroslav@1258
    30
 * use of allocated space by allowing a number to occupy only part of
jaroslav@1258
    31
 * an array so that the arrays do not have to be reallocated as often.
jaroslav@1258
    32
 * When performing an operation with many iterations the array used to
jaroslav@1258
    33
 * hold a number is only reallocated when necessary and does not have to
jaroslav@1258
    34
 * be the same size as the number it represents. A mutable number allows
jaroslav@1258
    35
 * calculations to occur on the same number without having to create
jaroslav@1258
    36
 * a new number for every step of the calculation as occurs with
jaroslav@1258
    37
 * BigIntegers.
jaroslav@1258
    38
 *
jaroslav@1258
    39
 * @see     BigInteger
jaroslav@1258
    40
 * @author  Michael McCloskey
jaroslav@1258
    41
 * @since   1.3
jaroslav@1258
    42
 */
jaroslav@1258
    43
jaroslav@1258
    44
import java.util.Arrays;
jaroslav@1258
    45
jaroslav@1258
    46
import static java.math.BigInteger.LONG_MASK;
jaroslav@1258
    47
import static java.math.BigDecimal.INFLATED;
jaroslav@1258
    48
jaroslav@1258
    49
class MutableBigInteger {
jaroslav@1258
    50
    /**
jaroslav@1258
    51
     * Holds the magnitude of this MutableBigInteger in big endian order.
jaroslav@1258
    52
     * The magnitude may start at an offset into the value array, and it may
jaroslav@1258
    53
     * end before the length of the value array.
jaroslav@1258
    54
     */
jaroslav@1258
    55
    int[] value;
jaroslav@1258
    56
jaroslav@1258
    57
    /**
jaroslav@1258
    58
     * The number of ints of the value array that are currently used
jaroslav@1258
    59
     * to hold the magnitude of this MutableBigInteger. The magnitude starts
jaroslav@1258
    60
     * at an offset and offset + intLen may be less than value.length.
jaroslav@1258
    61
     */
jaroslav@1258
    62
    int intLen;
jaroslav@1258
    63
jaroslav@1258
    64
    /**
jaroslav@1258
    65
     * The offset into the value array where the magnitude of this
jaroslav@1258
    66
     * MutableBigInteger begins.
jaroslav@1258
    67
     */
jaroslav@1258
    68
    int offset = 0;
jaroslav@1258
    69
jaroslav@1258
    70
    // Constants
jaroslav@1258
    71
    /**
jaroslav@1258
    72
     * MutableBigInteger with one element value array with the value 1. Used by
jaroslav@1258
    73
     * BigDecimal divideAndRound to increment the quotient. Use this constant
jaroslav@1258
    74
     * only when the method is not going to modify this object.
jaroslav@1258
    75
     */
jaroslav@1258
    76
    static final MutableBigInteger ONE = new MutableBigInteger(1);
jaroslav@1258
    77
jaroslav@1258
    78
    // Constructors
jaroslav@1258
    79
jaroslav@1258
    80
    /**
jaroslav@1258
    81
     * The default constructor. An empty MutableBigInteger is created with
jaroslav@1258
    82
     * a one word capacity.
jaroslav@1258
    83
     */
jaroslav@1258
    84
    MutableBigInteger() {
jaroslav@1258
    85
        value = new int[1];
jaroslav@1258
    86
        intLen = 0;
jaroslav@1258
    87
    }
jaroslav@1258
    88
jaroslav@1258
    89
    /**
jaroslav@1258
    90
     * Construct a new MutableBigInteger with a magnitude specified by
jaroslav@1258
    91
     * the int val.
jaroslav@1258
    92
     */
jaroslav@1258
    93
    MutableBigInteger(int val) {
jaroslav@1258
    94
        value = new int[1];
jaroslav@1258
    95
        intLen = 1;
jaroslav@1258
    96
        value[0] = val;
jaroslav@1258
    97
    }
jaroslav@1258
    98
jaroslav@1258
    99
    /**
jaroslav@1258
   100
     * Construct a new MutableBigInteger with the specified value array
jaroslav@1258
   101
     * up to the length of the array supplied.
jaroslav@1258
   102
     */
jaroslav@1258
   103
    MutableBigInteger(int[] val) {
jaroslav@1258
   104
        value = val;
jaroslav@1258
   105
        intLen = val.length;
jaroslav@1258
   106
    }
jaroslav@1258
   107
jaroslav@1258
   108
    /**
jaroslav@1258
   109
     * Construct a new MutableBigInteger with a magnitude equal to the
jaroslav@1258
   110
     * specified BigInteger.
jaroslav@1258
   111
     */
jaroslav@1258
   112
    MutableBigInteger(BigInteger b) {
jaroslav@1258
   113
        intLen = b.mag.length;
jaroslav@1258
   114
        value = Arrays.copyOf(b.mag, intLen);
jaroslav@1258
   115
    }
jaroslav@1258
   116
jaroslav@1258
   117
    /**
jaroslav@1258
   118
     * Construct a new MutableBigInteger with a magnitude equal to the
jaroslav@1258
   119
     * specified MutableBigInteger.
jaroslav@1258
   120
     */
jaroslav@1258
   121
    MutableBigInteger(MutableBigInteger val) {
jaroslav@1258
   122
        intLen = val.intLen;
jaroslav@1258
   123
        value = Arrays.copyOfRange(val.value, val.offset, val.offset + intLen);
jaroslav@1258
   124
    }
jaroslav@1258
   125
jaroslav@1258
   126
    /**
jaroslav@1258
   127
     * Internal helper method to return the magnitude array. The caller is not
jaroslav@1258
   128
     * supposed to modify the returned array.
jaroslav@1258
   129
     */
jaroslav@1258
   130
    private int[] getMagnitudeArray() {
jaroslav@1258
   131
        if (offset > 0 || value.length != intLen)
jaroslav@1258
   132
            return Arrays.copyOfRange(value, offset, offset + intLen);
jaroslav@1258
   133
        return value;
jaroslav@1258
   134
    }
jaroslav@1258
   135
jaroslav@1258
   136
    /**
jaroslav@1258
   137
     * Convert this MutableBigInteger to a long value. The caller has to make
jaroslav@1258
   138
     * sure this MutableBigInteger can be fit into long.
jaroslav@1258
   139
     */
jaroslav@1258
   140
    private long toLong() {
jaroslav@1258
   141
        assert (intLen <= 2) : "this MutableBigInteger exceeds the range of long";
jaroslav@1258
   142
        if (intLen == 0)
jaroslav@1258
   143
            return 0;
jaroslav@1258
   144
        long d = value[offset] & LONG_MASK;
jaroslav@1258
   145
        return (intLen == 2) ? d << 32 | (value[offset + 1] & LONG_MASK) : d;
jaroslav@1258
   146
    }
jaroslav@1258
   147
jaroslav@1258
   148
    /**
jaroslav@1258
   149
     * Convert this MutableBigInteger to a BigInteger object.
jaroslav@1258
   150
     */
jaroslav@1258
   151
    BigInteger toBigInteger(int sign) {
jaroslav@1258
   152
        if (intLen == 0 || sign == 0)
jaroslav@1258
   153
            return BigInteger.ZERO;
jaroslav@1258
   154
        return new BigInteger(getMagnitudeArray(), sign);
jaroslav@1258
   155
    }
jaroslav@1258
   156
jaroslav@1258
   157
    /**
jaroslav@1258
   158
     * Convert this MutableBigInteger to BigDecimal object with the specified sign
jaroslav@1258
   159
     * and scale.
jaroslav@1258
   160
     */
jaroslav@1258
   161
    BigDecimal toBigDecimal(int sign, int scale) {
jaroslav@1258
   162
        if (intLen == 0 || sign == 0)
jaroslav@1258
   163
            return BigDecimal.valueOf(0, scale);
jaroslav@1258
   164
        int[] mag = getMagnitudeArray();
jaroslav@1258
   165
        int len = mag.length;
jaroslav@1258
   166
        int d = mag[0];
jaroslav@1258
   167
        // If this MutableBigInteger can't be fit into long, we need to
jaroslav@1258
   168
        // make a BigInteger object for the resultant BigDecimal object.
jaroslav@1258
   169
        if (len > 2 || (d < 0 && len == 2))
jaroslav@1258
   170
            return new BigDecimal(new BigInteger(mag, sign), INFLATED, scale, 0);
jaroslav@1258
   171
        long v = (len == 2) ?
jaroslav@1258
   172
            ((mag[1] & LONG_MASK) | (d & LONG_MASK) << 32) :
jaroslav@1258
   173
            d & LONG_MASK;
jaroslav@1258
   174
        return new BigDecimal(null, sign == -1 ? -v : v, scale, 0);
jaroslav@1258
   175
    }
jaroslav@1258
   176
jaroslav@1258
   177
    /**
jaroslav@1258
   178
     * Clear out a MutableBigInteger for reuse.
jaroslav@1258
   179
     */
jaroslav@1258
   180
    void clear() {
jaroslav@1258
   181
        offset = intLen = 0;
jaroslav@1258
   182
        for (int index=0, n=value.length; index < n; index++)
jaroslav@1258
   183
            value[index] = 0;
jaroslav@1258
   184
    }
jaroslav@1258
   185
jaroslav@1258
   186
    /**
jaroslav@1258
   187
     * Set a MutableBigInteger to zero, removing its offset.
jaroslav@1258
   188
     */
jaroslav@1258
   189
    void reset() {
jaroslav@1258
   190
        offset = intLen = 0;
jaroslav@1258
   191
    }
jaroslav@1258
   192
jaroslav@1258
   193
    /**
jaroslav@1258
   194
     * Compare the magnitude of two MutableBigIntegers. Returns -1, 0 or 1
jaroslav@1258
   195
     * as this MutableBigInteger is numerically less than, equal to, or
jaroslav@1258
   196
     * greater than <tt>b</tt>.
jaroslav@1258
   197
     */
jaroslav@1258
   198
    final int compare(MutableBigInteger b) {
jaroslav@1258
   199
        int blen = b.intLen;
jaroslav@1258
   200
        if (intLen < blen)
jaroslav@1258
   201
            return -1;
jaroslav@1258
   202
        if (intLen > blen)
jaroslav@1258
   203
           return 1;
jaroslav@1258
   204
jaroslav@1258
   205
        // Add Integer.MIN_VALUE to make the comparison act as unsigned integer
jaroslav@1258
   206
        // comparison.
jaroslav@1258
   207
        int[] bval = b.value;
jaroslav@1258
   208
        for (int i = offset, j = b.offset; i < intLen + offset; i++, j++) {
jaroslav@1258
   209
            int b1 = value[i] + 0x80000000;
jaroslav@1258
   210
            int b2 = bval[j]  + 0x80000000;
jaroslav@1258
   211
            if (b1 < b2)
jaroslav@1258
   212
                return -1;
jaroslav@1258
   213
            if (b1 > b2)
jaroslav@1258
   214
                return 1;
jaroslav@1258
   215
        }
jaroslav@1258
   216
        return 0;
jaroslav@1258
   217
    }
jaroslav@1258
   218
jaroslav@1258
   219
    /**
jaroslav@1258
   220
     * Compare this against half of a MutableBigInteger object (Needed for
jaroslav@1258
   221
     * remainder tests).
jaroslav@1258
   222
     * Assumes no leading unnecessary zeros, which holds for results
jaroslav@1258
   223
     * from divide().
jaroslav@1258
   224
     */
jaroslav@1258
   225
    final int compareHalf(MutableBigInteger b) {
jaroslav@1258
   226
        int blen = b.intLen;
jaroslav@1258
   227
        int len = intLen;
jaroslav@1258
   228
        if (len <= 0)
jaroslav@1258
   229
            return blen <=0 ? 0 : -1;
jaroslav@1258
   230
        if (len > blen)
jaroslav@1258
   231
            return 1;
jaroslav@1258
   232
        if (len < blen - 1)
jaroslav@1258
   233
            return -1;
jaroslav@1258
   234
        int[] bval = b.value;
jaroslav@1258
   235
        int bstart = 0;
jaroslav@1258
   236
        int carry = 0;
jaroslav@1258
   237
        // Only 2 cases left:len == blen or len == blen - 1
jaroslav@1258
   238
        if (len != blen) { // len == blen - 1
jaroslav@1258
   239
            if (bval[bstart] == 1) {
jaroslav@1258
   240
                ++bstart;
jaroslav@1258
   241
                carry = 0x80000000;
jaroslav@1258
   242
            } else
jaroslav@1258
   243
                return -1;
jaroslav@1258
   244
        }
jaroslav@1258
   245
        // compare values with right-shifted values of b,
jaroslav@1258
   246
        // carrying shifted-out bits across words
jaroslav@1258
   247
        int[] val = value;
jaroslav@1258
   248
        for (int i = offset, j = bstart; i < len + offset;) {
jaroslav@1258
   249
            int bv = bval[j++];
jaroslav@1258
   250
            long hb = ((bv >>> 1) + carry) & LONG_MASK;
jaroslav@1258
   251
            long v = val[i++] & LONG_MASK;
jaroslav@1258
   252
            if (v != hb)
jaroslav@1258
   253
                return v < hb ? -1 : 1;
jaroslav@1258
   254
            carry = (bv & 1) << 31; // carray will be either 0x80000000 or 0
jaroslav@1258
   255
        }
jaroslav@1258
   256
        return carry == 0? 0 : -1;
jaroslav@1258
   257
    }
jaroslav@1258
   258
jaroslav@1258
   259
    /**
jaroslav@1258
   260
     * Return the index of the lowest set bit in this MutableBigInteger. If the
jaroslav@1258
   261
     * magnitude of this MutableBigInteger is zero, -1 is returned.
jaroslav@1258
   262
     */
jaroslav@1258
   263
    private final int getLowestSetBit() {
jaroslav@1258
   264
        if (intLen == 0)
jaroslav@1258
   265
            return -1;
jaroslav@1258
   266
        int j, b;
jaroslav@1258
   267
        for (j=intLen-1; (j>0) && (value[j+offset]==0); j--)
jaroslav@1258
   268
            ;
jaroslav@1258
   269
        b = value[j+offset];
jaroslav@1258
   270
        if (b==0)
jaroslav@1258
   271
            return -1;
jaroslav@1258
   272
        return ((intLen-1-j)<<5) + Integer.numberOfTrailingZeros(b);
jaroslav@1258
   273
    }
jaroslav@1258
   274
jaroslav@1258
   275
    /**
jaroslav@1258
   276
     * Return the int in use in this MutableBigInteger at the specified
jaroslav@1258
   277
     * index. This method is not used because it is not inlined on all
jaroslav@1258
   278
     * platforms.
jaroslav@1258
   279
     */
jaroslav@1258
   280
    private final int getInt(int index) {
jaroslav@1258
   281
        return value[offset+index];
jaroslav@1258
   282
    }
jaroslav@1258
   283
jaroslav@1258
   284
    /**
jaroslav@1258
   285
     * Return a long which is equal to the unsigned value of the int in
jaroslav@1258
   286
     * use in this MutableBigInteger at the specified index. This method is
jaroslav@1258
   287
     * not used because it is not inlined on all platforms.
jaroslav@1258
   288
     */
jaroslav@1258
   289
    private final long getLong(int index) {
jaroslav@1258
   290
        return value[offset+index] & LONG_MASK;
jaroslav@1258
   291
    }
jaroslav@1258
   292
jaroslav@1258
   293
    /**
jaroslav@1258
   294
     * Ensure that the MutableBigInteger is in normal form, specifically
jaroslav@1258
   295
     * making sure that there are no leading zeros, and that if the
jaroslav@1258
   296
     * magnitude is zero, then intLen is zero.
jaroslav@1258
   297
     */
jaroslav@1258
   298
    final void normalize() {
jaroslav@1258
   299
        if (intLen == 0) {
jaroslav@1258
   300
            offset = 0;
jaroslav@1258
   301
            return;
jaroslav@1258
   302
        }
jaroslav@1258
   303
jaroslav@1258
   304
        int index = offset;
jaroslav@1258
   305
        if (value[index] != 0)
jaroslav@1258
   306
            return;
jaroslav@1258
   307
jaroslav@1258
   308
        int indexBound = index+intLen;
jaroslav@1258
   309
        do {
jaroslav@1258
   310
            index++;
jaroslav@1258
   311
        } while(index < indexBound && value[index]==0);
jaroslav@1258
   312
jaroslav@1258
   313
        int numZeros = index - offset;
jaroslav@1258
   314
        intLen -= numZeros;
jaroslav@1258
   315
        offset = (intLen==0 ?  0 : offset+numZeros);
jaroslav@1258
   316
    }
jaroslav@1258
   317
jaroslav@1258
   318
    /**
jaroslav@1258
   319
     * If this MutableBigInteger cannot hold len words, increase the size
jaroslav@1258
   320
     * of the value array to len words.
jaroslav@1258
   321
     */
jaroslav@1258
   322
    private final void ensureCapacity(int len) {
jaroslav@1258
   323
        if (value.length < len) {
jaroslav@1258
   324
            value = new int[len];
jaroslav@1258
   325
            offset = 0;
jaroslav@1258
   326
            intLen = len;
jaroslav@1258
   327
        }
jaroslav@1258
   328
    }
jaroslav@1258
   329
jaroslav@1258
   330
    /**
jaroslav@1258
   331
     * Convert this MutableBigInteger into an int array with no leading
jaroslav@1258
   332
     * zeros, of a length that is equal to this MutableBigInteger's intLen.
jaroslav@1258
   333
     */
jaroslav@1258
   334
    int[] toIntArray() {
jaroslav@1258
   335
        int[] result = new int[intLen];
jaroslav@1258
   336
        for(int i=0; i<intLen; i++)
jaroslav@1258
   337
            result[i] = value[offset+i];
jaroslav@1258
   338
        return result;
jaroslav@1258
   339
    }
jaroslav@1258
   340
jaroslav@1258
   341
    /**
jaroslav@1258
   342
     * Sets the int at index+offset in this MutableBigInteger to val.
jaroslav@1258
   343
     * This does not get inlined on all platforms so it is not used
jaroslav@1258
   344
     * as often as originally intended.
jaroslav@1258
   345
     */
jaroslav@1258
   346
    void setInt(int index, int val) {
jaroslav@1258
   347
        value[offset + index] = val;
jaroslav@1258
   348
    }
jaroslav@1258
   349
jaroslav@1258
   350
    /**
jaroslav@1258
   351
     * Sets this MutableBigInteger's value array to the specified array.
jaroslav@1258
   352
     * The intLen is set to the specified length.
jaroslav@1258
   353
     */
jaroslav@1258
   354
    void setValue(int[] val, int length) {
jaroslav@1258
   355
        value = val;
jaroslav@1258
   356
        intLen = length;
jaroslav@1258
   357
        offset = 0;
jaroslav@1258
   358
    }
jaroslav@1258
   359
jaroslav@1258
   360
    /**
jaroslav@1258
   361
     * Sets this MutableBigInteger's value array to a copy of the specified
jaroslav@1258
   362
     * array. The intLen is set to the length of the new array.
jaroslav@1258
   363
     */
jaroslav@1258
   364
    void copyValue(MutableBigInteger src) {
jaroslav@1258
   365
        int len = src.intLen;
jaroslav@1258
   366
        if (value.length < len)
jaroslav@1258
   367
            value = new int[len];
jaroslav@1258
   368
        System.arraycopy(src.value, src.offset, value, 0, len);
jaroslav@1258
   369
        intLen = len;
jaroslav@1258
   370
        offset = 0;
jaroslav@1258
   371
    }
jaroslav@1258
   372
jaroslav@1258
   373
    /**
jaroslav@1258
   374
     * Sets this MutableBigInteger's value array to a copy of the specified
jaroslav@1258
   375
     * array. The intLen is set to the length of the specified array.
jaroslav@1258
   376
     */
jaroslav@1258
   377
    void copyValue(int[] val) {
jaroslav@1258
   378
        int len = val.length;
jaroslav@1258
   379
        if (value.length < len)
jaroslav@1258
   380
            value = new int[len];
jaroslav@1258
   381
        System.arraycopy(val, 0, value, 0, len);
jaroslav@1258
   382
        intLen = len;
jaroslav@1258
   383
        offset = 0;
jaroslav@1258
   384
    }
jaroslav@1258
   385
jaroslav@1258
   386
    /**
jaroslav@1258
   387
     * Returns true iff this MutableBigInteger has a value of one.
jaroslav@1258
   388
     */
jaroslav@1258
   389
    boolean isOne() {
jaroslav@1258
   390
        return (intLen == 1) && (value[offset] == 1);
jaroslav@1258
   391
    }
jaroslav@1258
   392
jaroslav@1258
   393
    /**
jaroslav@1258
   394
     * Returns true iff this MutableBigInteger has a value of zero.
jaroslav@1258
   395
     */
jaroslav@1258
   396
    boolean isZero() {
jaroslav@1258
   397
        return (intLen == 0);
jaroslav@1258
   398
    }
jaroslav@1258
   399
jaroslav@1258
   400
    /**
jaroslav@1258
   401
     * Returns true iff this MutableBigInteger is even.
jaroslav@1258
   402
     */
jaroslav@1258
   403
    boolean isEven() {
jaroslav@1258
   404
        return (intLen == 0) || ((value[offset + intLen - 1] & 1) == 0);
jaroslav@1258
   405
    }
jaroslav@1258
   406
jaroslav@1258
   407
    /**
jaroslav@1258
   408
     * Returns true iff this MutableBigInteger is odd.
jaroslav@1258
   409
     */
jaroslav@1258
   410
    boolean isOdd() {
jaroslav@1258
   411
        return isZero() ? false : ((value[offset + intLen - 1] & 1) == 1);
jaroslav@1258
   412
    }
jaroslav@1258
   413
jaroslav@1258
   414
    /**
jaroslav@1258
   415
     * Returns true iff this MutableBigInteger is in normal form. A
jaroslav@1258
   416
     * MutableBigInteger is in normal form if it has no leading zeros
jaroslav@1258
   417
     * after the offset, and intLen + offset <= value.length.
jaroslav@1258
   418
     */
jaroslav@1258
   419
    boolean isNormal() {
jaroslav@1258
   420
        if (intLen + offset > value.length)
jaroslav@1258
   421
            return false;
jaroslav@1258
   422
        if (intLen ==0)
jaroslav@1258
   423
            return true;
jaroslav@1258
   424
        return (value[offset] != 0);
jaroslav@1258
   425
    }
jaroslav@1258
   426
jaroslav@1258
   427
    /**
jaroslav@1258
   428
     * Returns a String representation of this MutableBigInteger in radix 10.
jaroslav@1258
   429
     */
jaroslav@1258
   430
    public String toString() {
jaroslav@1258
   431
        BigInteger b = toBigInteger(1);
jaroslav@1258
   432
        return b.toString();
jaroslav@1258
   433
    }
jaroslav@1258
   434
jaroslav@1258
   435
    /**
jaroslav@1258
   436
     * Right shift this MutableBigInteger n bits. The MutableBigInteger is left
jaroslav@1258
   437
     * in normal form.
jaroslav@1258
   438
     */
jaroslav@1258
   439
    void rightShift(int n) {
jaroslav@1258
   440
        if (intLen == 0)
jaroslav@1258
   441
            return;
jaroslav@1258
   442
        int nInts = n >>> 5;
jaroslav@1258
   443
        int nBits = n & 0x1F;
jaroslav@1258
   444
        this.intLen -= nInts;
jaroslav@1258
   445
        if (nBits == 0)
jaroslav@1258
   446
            return;
jaroslav@1258
   447
        int bitsInHighWord = BigInteger.bitLengthForInt(value[offset]);
jaroslav@1258
   448
        if (nBits >= bitsInHighWord) {
jaroslav@1258
   449
            this.primitiveLeftShift(32 - nBits);
jaroslav@1258
   450
            this.intLen--;
jaroslav@1258
   451
        } else {
jaroslav@1258
   452
            primitiveRightShift(nBits);
jaroslav@1258
   453
        }
jaroslav@1258
   454
    }
jaroslav@1258
   455
jaroslav@1258
   456
    /**
jaroslav@1258
   457
     * Left shift this MutableBigInteger n bits.
jaroslav@1258
   458
     */
jaroslav@1258
   459
    void leftShift(int n) {
jaroslav@1258
   460
        /*
jaroslav@1258
   461
         * If there is enough storage space in this MutableBigInteger already
jaroslav@1258
   462
         * the available space will be used. Space to the right of the used
jaroslav@1258
   463
         * ints in the value array is faster to utilize, so the extra space
jaroslav@1258
   464
         * will be taken from the right if possible.
jaroslav@1258
   465
         */
jaroslav@1258
   466
        if (intLen == 0)
jaroslav@1258
   467
           return;
jaroslav@1258
   468
        int nInts = n >>> 5;
jaroslav@1258
   469
        int nBits = n&0x1F;
jaroslav@1258
   470
        int bitsInHighWord = BigInteger.bitLengthForInt(value[offset]);
jaroslav@1258
   471
jaroslav@1258
   472
        // If shift can be done without moving words, do so
jaroslav@1258
   473
        if (n <= (32-bitsInHighWord)) {
jaroslav@1258
   474
            primitiveLeftShift(nBits);
jaroslav@1258
   475
            return;
jaroslav@1258
   476
        }
jaroslav@1258
   477
jaroslav@1258
   478
        int newLen = intLen + nInts +1;
jaroslav@1258
   479
        if (nBits <= (32-bitsInHighWord))
jaroslav@1258
   480
            newLen--;
jaroslav@1258
   481
        if (value.length < newLen) {
jaroslav@1258
   482
            // The array must grow
jaroslav@1258
   483
            int[] result = new int[newLen];
jaroslav@1258
   484
            for (int i=0; i<intLen; i++)
jaroslav@1258
   485
                result[i] = value[offset+i];
jaroslav@1258
   486
            setValue(result, newLen);
jaroslav@1258
   487
        } else if (value.length - offset >= newLen) {
jaroslav@1258
   488
            // Use space on right
jaroslav@1258
   489
            for(int i=0; i<newLen - intLen; i++)
jaroslav@1258
   490
                value[offset+intLen+i] = 0;
jaroslav@1258
   491
        } else {
jaroslav@1258
   492
            // Must use space on left
jaroslav@1258
   493
            for (int i=0; i<intLen; i++)
jaroslav@1258
   494
                value[i] = value[offset+i];
jaroslav@1258
   495
            for (int i=intLen; i<newLen; i++)
jaroslav@1258
   496
                value[i] = 0;
jaroslav@1258
   497
            offset = 0;
jaroslav@1258
   498
        }
jaroslav@1258
   499
        intLen = newLen;
jaroslav@1258
   500
        if (nBits == 0)
jaroslav@1258
   501
            return;
jaroslav@1258
   502
        if (nBits <= (32-bitsInHighWord))
jaroslav@1258
   503
            primitiveLeftShift(nBits);
jaroslav@1258
   504
        else
jaroslav@1258
   505
            primitiveRightShift(32 -nBits);
jaroslav@1258
   506
    }
jaroslav@1258
   507
jaroslav@1258
   508
    /**
jaroslav@1258
   509
     * A primitive used for division. This method adds in one multiple of the
jaroslav@1258
   510
     * divisor a back to the dividend result at a specified offset. It is used
jaroslav@1258
   511
     * when qhat was estimated too large, and must be adjusted.
jaroslav@1258
   512
     */
jaroslav@1258
   513
    private int divadd(int[] a, int[] result, int offset) {
jaroslav@1258
   514
        long carry = 0;
jaroslav@1258
   515
jaroslav@1258
   516
        for (int j=a.length-1; j >= 0; j--) {
jaroslav@1258
   517
            long sum = (a[j] & LONG_MASK) +
jaroslav@1258
   518
                       (result[j+offset] & LONG_MASK) + carry;
jaroslav@1258
   519
            result[j+offset] = (int)sum;
jaroslav@1258
   520
            carry = sum >>> 32;
jaroslav@1258
   521
        }
jaroslav@1258
   522
        return (int)carry;
jaroslav@1258
   523
    }
jaroslav@1258
   524
jaroslav@1258
   525
    /**
jaroslav@1258
   526
     * This method is used for division. It multiplies an n word input a by one
jaroslav@1258
   527
     * word input x, and subtracts the n word product from q. This is needed
jaroslav@1258
   528
     * when subtracting qhat*divisor from dividend.
jaroslav@1258
   529
     */
jaroslav@1258
   530
    private int mulsub(int[] q, int[] a, int x, int len, int offset) {
jaroslav@1258
   531
        long xLong = x & LONG_MASK;
jaroslav@1258
   532
        long carry = 0;
jaroslav@1258
   533
        offset += len;
jaroslav@1258
   534
jaroslav@1258
   535
        for (int j=len-1; j >= 0; j--) {
jaroslav@1258
   536
            long product = (a[j] & LONG_MASK) * xLong + carry;
jaroslav@1258
   537
            long difference = q[offset] - product;
jaroslav@1258
   538
            q[offset--] = (int)difference;
jaroslav@1258
   539
            carry = (product >>> 32)
jaroslav@1258
   540
                     + (((difference & LONG_MASK) >
jaroslav@1258
   541
                         (((~(int)product) & LONG_MASK))) ? 1:0);
jaroslav@1258
   542
        }
jaroslav@1258
   543
        return (int)carry;
jaroslav@1258
   544
    }
jaroslav@1258
   545
jaroslav@1258
   546
    /**
jaroslav@1258
   547
     * Right shift this MutableBigInteger n bits, where n is
jaroslav@1258
   548
     * less than 32.
jaroslav@1258
   549
     * Assumes that intLen > 0, n > 0 for speed
jaroslav@1258
   550
     */
jaroslav@1258
   551
    private final void primitiveRightShift(int n) {
jaroslav@1258
   552
        int[] val = value;
jaroslav@1258
   553
        int n2 = 32 - n;
jaroslav@1258
   554
        for (int i=offset+intLen-1, c=val[i]; i>offset; i--) {
jaroslav@1258
   555
            int b = c;
jaroslav@1258
   556
            c = val[i-1];
jaroslav@1258
   557
            val[i] = (c << n2) | (b >>> n);
jaroslav@1258
   558
        }
jaroslav@1258
   559
        val[offset] >>>= n;
jaroslav@1258
   560
    }
jaroslav@1258
   561
jaroslav@1258
   562
    /**
jaroslav@1258
   563
     * Left shift this MutableBigInteger n bits, where n is
jaroslav@1258
   564
     * less than 32.
jaroslav@1258
   565
     * Assumes that intLen > 0, n > 0 for speed
jaroslav@1258
   566
     */
jaroslav@1258
   567
    private final void primitiveLeftShift(int n) {
jaroslav@1258
   568
        int[] val = value;
jaroslav@1258
   569
        int n2 = 32 - n;
jaroslav@1258
   570
        for (int i=offset, c=val[i], m=i+intLen-1; i<m; i++) {
jaroslav@1258
   571
            int b = c;
jaroslav@1258
   572
            c = val[i+1];
jaroslav@1258
   573
            val[i] = (b << n) | (c >>> n2);
jaroslav@1258
   574
        }
jaroslav@1258
   575
        val[offset+intLen-1] <<= n;
jaroslav@1258
   576
    }
jaroslav@1258
   577
jaroslav@1258
   578
    /**
jaroslav@1258
   579
     * Adds the contents of two MutableBigInteger objects.The result
jaroslav@1258
   580
     * is placed within this MutableBigInteger.
jaroslav@1258
   581
     * The contents of the addend are not changed.
jaroslav@1258
   582
     */
jaroslav@1258
   583
    void add(MutableBigInteger addend) {
jaroslav@1258
   584
        int x = intLen;
jaroslav@1258
   585
        int y = addend.intLen;
jaroslav@1258
   586
        int resultLen = (intLen > addend.intLen ? intLen : addend.intLen);
jaroslav@1258
   587
        int[] result = (value.length < resultLen ? new int[resultLen] : value);
jaroslav@1258
   588
jaroslav@1258
   589
        int rstart = result.length-1;
jaroslav@1258
   590
        long sum;
jaroslav@1258
   591
        long carry = 0;
jaroslav@1258
   592
jaroslav@1258
   593
        // Add common parts of both numbers
jaroslav@1258
   594
        while(x>0 && y>0) {
jaroslav@1258
   595
            x--; y--;
jaroslav@1258
   596
            sum = (value[x+offset] & LONG_MASK) +
jaroslav@1258
   597
                (addend.value[y+addend.offset] & LONG_MASK) + carry;
jaroslav@1258
   598
            result[rstart--] = (int)sum;
jaroslav@1258
   599
            carry = sum >>> 32;
jaroslav@1258
   600
        }
jaroslav@1258
   601
jaroslav@1258
   602
        // Add remainder of the longer number
jaroslav@1258
   603
        while(x>0) {
jaroslav@1258
   604
            x--;
jaroslav@1258
   605
            if (carry == 0 && result == value && rstart == (x + offset))
jaroslav@1258
   606
                return;
jaroslav@1258
   607
            sum = (value[x+offset] & LONG_MASK) + carry;
jaroslav@1258
   608
            result[rstart--] = (int)sum;
jaroslav@1258
   609
            carry = sum >>> 32;
jaroslav@1258
   610
        }
jaroslav@1258
   611
        while(y>0) {
jaroslav@1258
   612
            y--;
jaroslav@1258
   613
            sum = (addend.value[y+addend.offset] & LONG_MASK) + carry;
jaroslav@1258
   614
            result[rstart--] = (int)sum;
jaroslav@1258
   615
            carry = sum >>> 32;
jaroslav@1258
   616
        }
jaroslav@1258
   617
jaroslav@1258
   618
        if (carry > 0) { // Result must grow in length
jaroslav@1258
   619
            resultLen++;
jaroslav@1258
   620
            if (result.length < resultLen) {
jaroslav@1258
   621
                int temp[] = new int[resultLen];
jaroslav@1258
   622
                // Result one word longer from carry-out; copy low-order
jaroslav@1258
   623
                // bits into new result.
jaroslav@1258
   624
                System.arraycopy(result, 0, temp, 1, result.length);
jaroslav@1258
   625
                temp[0] = 1;
jaroslav@1258
   626
                result = temp;
jaroslav@1258
   627
            } else {
jaroslav@1258
   628
                result[rstart--] = 1;
jaroslav@1258
   629
            }
jaroslav@1258
   630
        }
jaroslav@1258
   631
jaroslav@1258
   632
        value = result;
jaroslav@1258
   633
        intLen = resultLen;
jaroslav@1258
   634
        offset = result.length - resultLen;
jaroslav@1258
   635
    }
jaroslav@1258
   636
jaroslav@1258
   637
jaroslav@1258
   638
    /**
jaroslav@1258
   639
     * Subtracts the smaller of this and b from the larger and places the
jaroslav@1258
   640
     * result into this MutableBigInteger.
jaroslav@1258
   641
     */
jaroslav@1258
   642
    int subtract(MutableBigInteger b) {
jaroslav@1258
   643
        MutableBigInteger a = this;
jaroslav@1258
   644
jaroslav@1258
   645
        int[] result = value;
jaroslav@1258
   646
        int sign = a.compare(b);
jaroslav@1258
   647
jaroslav@1258
   648
        if (sign == 0) {
jaroslav@1258
   649
            reset();
jaroslav@1258
   650
            return 0;
jaroslav@1258
   651
        }
jaroslav@1258
   652
        if (sign < 0) {
jaroslav@1258
   653
            MutableBigInteger tmp = a;
jaroslav@1258
   654
            a = b;
jaroslav@1258
   655
            b = tmp;
jaroslav@1258
   656
        }
jaroslav@1258
   657
jaroslav@1258
   658
        int resultLen = a.intLen;
jaroslav@1258
   659
        if (result.length < resultLen)
jaroslav@1258
   660
            result = new int[resultLen];
jaroslav@1258
   661
jaroslav@1258
   662
        long diff = 0;
jaroslav@1258
   663
        int x = a.intLen;
jaroslav@1258
   664
        int y = b.intLen;
jaroslav@1258
   665
        int rstart = result.length - 1;
jaroslav@1258
   666
jaroslav@1258
   667
        // Subtract common parts of both numbers
jaroslav@1258
   668
        while (y>0) {
jaroslav@1258
   669
            x--; y--;
jaroslav@1258
   670
jaroslav@1258
   671
            diff = (a.value[x+a.offset] & LONG_MASK) -
jaroslav@1258
   672
                   (b.value[y+b.offset] & LONG_MASK) - ((int)-(diff>>32));
jaroslav@1258
   673
            result[rstart--] = (int)diff;
jaroslav@1258
   674
        }
jaroslav@1258
   675
        // Subtract remainder of longer number
jaroslav@1258
   676
        while (x>0) {
jaroslav@1258
   677
            x--;
jaroslav@1258
   678
            diff = (a.value[x+a.offset] & LONG_MASK) - ((int)-(diff>>32));
jaroslav@1258
   679
            result[rstart--] = (int)diff;
jaroslav@1258
   680
        }
jaroslav@1258
   681
jaroslav@1258
   682
        value = result;
jaroslav@1258
   683
        intLen = resultLen;
jaroslav@1258
   684
        offset = value.length - resultLen;
jaroslav@1258
   685
        normalize();
jaroslav@1258
   686
        return sign;
jaroslav@1258
   687
    }
jaroslav@1258
   688
jaroslav@1258
   689
    /**
jaroslav@1258
   690
     * Subtracts the smaller of a and b from the larger and places the result
jaroslav@1258
   691
     * into the larger. Returns 1 if the answer is in a, -1 if in b, 0 if no
jaroslav@1258
   692
     * operation was performed.
jaroslav@1258
   693
     */
jaroslav@1258
   694
    private int difference(MutableBigInteger b) {
jaroslav@1258
   695
        MutableBigInteger a = this;
jaroslav@1258
   696
        int sign = a.compare(b);
jaroslav@1258
   697
        if (sign ==0)
jaroslav@1258
   698
            return 0;
jaroslav@1258
   699
        if (sign < 0) {
jaroslav@1258
   700
            MutableBigInteger tmp = a;
jaroslav@1258
   701
            a = b;
jaroslav@1258
   702
            b = tmp;
jaroslav@1258
   703
        }
jaroslav@1258
   704
jaroslav@1258
   705
        long diff = 0;
jaroslav@1258
   706
        int x = a.intLen;
jaroslav@1258
   707
        int y = b.intLen;
jaroslav@1258
   708
jaroslav@1258
   709
        // Subtract common parts of both numbers
jaroslav@1258
   710
        while (y>0) {
jaroslav@1258
   711
            x--; y--;
jaroslav@1258
   712
            diff = (a.value[a.offset+ x] & LONG_MASK) -
jaroslav@1258
   713
                (b.value[b.offset+ y] & LONG_MASK) - ((int)-(diff>>32));
jaroslav@1258
   714
            a.value[a.offset+x] = (int)diff;
jaroslav@1258
   715
        }
jaroslav@1258
   716
        // Subtract remainder of longer number
jaroslav@1258
   717
        while (x>0) {
jaroslav@1258
   718
            x--;
jaroslav@1258
   719
            diff = (a.value[a.offset+ x] & LONG_MASK) - ((int)-(diff>>32));
jaroslav@1258
   720
            a.value[a.offset+x] = (int)diff;
jaroslav@1258
   721
        }
jaroslav@1258
   722
jaroslav@1258
   723
        a.normalize();
jaroslav@1258
   724
        return sign;
jaroslav@1258
   725
    }
jaroslav@1258
   726
jaroslav@1258
   727
    /**
jaroslav@1258
   728
     * Multiply the contents of two MutableBigInteger objects. The result is
jaroslav@1258
   729
     * placed into MutableBigInteger z. The contents of y are not changed.
jaroslav@1258
   730
     */
jaroslav@1258
   731
    void multiply(MutableBigInteger y, MutableBigInteger z) {
jaroslav@1258
   732
        int xLen = intLen;
jaroslav@1258
   733
        int yLen = y.intLen;
jaroslav@1258
   734
        int newLen = xLen + yLen;
jaroslav@1258
   735
jaroslav@1258
   736
        // Put z into an appropriate state to receive product
jaroslav@1258
   737
        if (z.value.length < newLen)
jaroslav@1258
   738
            z.value = new int[newLen];
jaroslav@1258
   739
        z.offset = 0;
jaroslav@1258
   740
        z.intLen = newLen;
jaroslav@1258
   741
jaroslav@1258
   742
        // The first iteration is hoisted out of the loop to avoid extra add
jaroslav@1258
   743
        long carry = 0;
jaroslav@1258
   744
        for (int j=yLen-1, k=yLen+xLen-1; j >= 0; j--, k--) {
jaroslav@1258
   745
                long product = (y.value[j+y.offset] & LONG_MASK) *
jaroslav@1258
   746
                               (value[xLen-1+offset] & LONG_MASK) + carry;
jaroslav@1258
   747
                z.value[k] = (int)product;
jaroslav@1258
   748
                carry = product >>> 32;
jaroslav@1258
   749
        }
jaroslav@1258
   750
        z.value[xLen-1] = (int)carry;
jaroslav@1258
   751
jaroslav@1258
   752
        // Perform the multiplication word by word
jaroslav@1258
   753
        for (int i = xLen-2; i >= 0; i--) {
jaroslav@1258
   754
            carry = 0;
jaroslav@1258
   755
            for (int j=yLen-1, k=yLen+i; j >= 0; j--, k--) {
jaroslav@1258
   756
                long product = (y.value[j+y.offset] & LONG_MASK) *
jaroslav@1258
   757
                               (value[i+offset] & LONG_MASK) +
jaroslav@1258
   758
                               (z.value[k] & LONG_MASK) + carry;
jaroslav@1258
   759
                z.value[k] = (int)product;
jaroslav@1258
   760
                carry = product >>> 32;
jaroslav@1258
   761
            }
jaroslav@1258
   762
            z.value[i] = (int)carry;
jaroslav@1258
   763
        }
jaroslav@1258
   764
jaroslav@1258
   765
        // Remove leading zeros from product
jaroslav@1258
   766
        z.normalize();
jaroslav@1258
   767
    }
jaroslav@1258
   768
jaroslav@1258
   769
    /**
jaroslav@1258
   770
     * Multiply the contents of this MutableBigInteger by the word y. The
jaroslav@1258
   771
     * result is placed into z.
jaroslav@1258
   772
     */
jaroslav@1258
   773
    void mul(int y, MutableBigInteger z) {
jaroslav@1258
   774
        if (y == 1) {
jaroslav@1258
   775
            z.copyValue(this);
jaroslav@1258
   776
            return;
jaroslav@1258
   777
        }
jaroslav@1258
   778
jaroslav@1258
   779
        if (y == 0) {
jaroslav@1258
   780
            z.clear();
jaroslav@1258
   781
            return;
jaroslav@1258
   782
        }
jaroslav@1258
   783
jaroslav@1258
   784
        // Perform the multiplication word by word
jaroslav@1258
   785
        long ylong = y & LONG_MASK;
jaroslav@1258
   786
        int[] zval = (z.value.length<intLen+1 ? new int[intLen + 1]
jaroslav@1258
   787
                                              : z.value);
jaroslav@1258
   788
        long carry = 0;
jaroslav@1258
   789
        for (int i = intLen-1; i >= 0; i--) {
jaroslav@1258
   790
            long product = ylong * (value[i+offset] & LONG_MASK) + carry;
jaroslav@1258
   791
            zval[i+1] = (int)product;
jaroslav@1258
   792
            carry = product >>> 32;
jaroslav@1258
   793
        }
jaroslav@1258
   794
jaroslav@1258
   795
        if (carry == 0) {
jaroslav@1258
   796
            z.offset = 1;
jaroslav@1258
   797
            z.intLen = intLen;
jaroslav@1258
   798
        } else {
jaroslav@1258
   799
            z.offset = 0;
jaroslav@1258
   800
            z.intLen = intLen + 1;
jaroslav@1258
   801
            zval[0] = (int)carry;
jaroslav@1258
   802
        }
jaroslav@1258
   803
        z.value = zval;
jaroslav@1258
   804
    }
jaroslav@1258
   805
jaroslav@1258
   806
     /**
jaroslav@1258
   807
     * This method is used for division of an n word dividend by a one word
jaroslav@1258
   808
     * divisor. The quotient is placed into quotient. The one word divisor is
jaroslav@1258
   809
     * specified by divisor.
jaroslav@1258
   810
     *
jaroslav@1258
   811
     * @return the remainder of the division is returned.
jaroslav@1258
   812
     *
jaroslav@1258
   813
     */
jaroslav@1258
   814
    int divideOneWord(int divisor, MutableBigInteger quotient) {
jaroslav@1258
   815
        long divisorLong = divisor & LONG_MASK;
jaroslav@1258
   816
jaroslav@1258
   817
        // Special case of one word dividend
jaroslav@1258
   818
        if (intLen == 1) {
jaroslav@1258
   819
            long dividendValue = value[offset] & LONG_MASK;
jaroslav@1258
   820
            int q = (int) (dividendValue / divisorLong);
jaroslav@1258
   821
            int r = (int) (dividendValue - q * divisorLong);
jaroslav@1258
   822
            quotient.value[0] = q;
jaroslav@1258
   823
            quotient.intLen = (q == 0) ? 0 : 1;
jaroslav@1258
   824
            quotient.offset = 0;
jaroslav@1258
   825
            return r;
jaroslav@1258
   826
        }
jaroslav@1258
   827
jaroslav@1258
   828
        if (quotient.value.length < intLen)
jaroslav@1258
   829
            quotient.value = new int[intLen];
jaroslav@1258
   830
        quotient.offset = 0;
jaroslav@1258
   831
        quotient.intLen = intLen;
jaroslav@1258
   832
jaroslav@1258
   833
        // Normalize the divisor
jaroslav@1258
   834
        int shift = Integer.numberOfLeadingZeros(divisor);
jaroslav@1258
   835
jaroslav@1258
   836
        int rem = value[offset];
jaroslav@1258
   837
        long remLong = rem & LONG_MASK;
jaroslav@1258
   838
        if (remLong < divisorLong) {
jaroslav@1258
   839
            quotient.value[0] = 0;
jaroslav@1258
   840
        } else {
jaroslav@1258
   841
            quotient.value[0] = (int)(remLong / divisorLong);
jaroslav@1258
   842
            rem = (int) (remLong - (quotient.value[0] * divisorLong));
jaroslav@1258
   843
            remLong = rem & LONG_MASK;
jaroslav@1258
   844
        }
jaroslav@1258
   845
jaroslav@1258
   846
        int xlen = intLen;
jaroslav@1258
   847
        int[] qWord = new int[2];
jaroslav@1258
   848
        while (--xlen > 0) {
jaroslav@1258
   849
            long dividendEstimate = (remLong<<32) |
jaroslav@1258
   850
                (value[offset + intLen - xlen] & LONG_MASK);
jaroslav@1258
   851
            if (dividendEstimate >= 0) {
jaroslav@1258
   852
                qWord[0] = (int) (dividendEstimate / divisorLong);
jaroslav@1258
   853
                qWord[1] = (int) (dividendEstimate - qWord[0] * divisorLong);
jaroslav@1258
   854
            } else {
jaroslav@1258
   855
                divWord(qWord, dividendEstimate, divisor);
jaroslav@1258
   856
            }
jaroslav@1258
   857
            quotient.value[intLen - xlen] = qWord[0];
jaroslav@1258
   858
            rem = qWord[1];
jaroslav@1258
   859
            remLong = rem & LONG_MASK;
jaroslav@1258
   860
        }
jaroslav@1258
   861
jaroslav@1258
   862
        quotient.normalize();
jaroslav@1258
   863
        // Unnormalize
jaroslav@1258
   864
        if (shift > 0)
jaroslav@1258
   865
            return rem % divisor;
jaroslav@1258
   866
        else
jaroslav@1258
   867
            return rem;
jaroslav@1258
   868
    }
jaroslav@1258
   869
jaroslav@1258
   870
    /**
jaroslav@1258
   871
     * Calculates the quotient of this div b and places the quotient in the
jaroslav@1258
   872
     * provided MutableBigInteger objects and the remainder object is returned.
jaroslav@1258
   873
     *
jaroslav@1258
   874
     * Uses Algorithm D in Knuth section 4.3.1.
jaroslav@1258
   875
     * Many optimizations to that algorithm have been adapted from the Colin
jaroslav@1258
   876
     * Plumb C library.
jaroslav@1258
   877
     * It special cases one word divisors for speed. The content of b is not
jaroslav@1258
   878
     * changed.
jaroslav@1258
   879
     *
jaroslav@1258
   880
     */
jaroslav@1258
   881
    MutableBigInteger divide(MutableBigInteger b, MutableBigInteger quotient) {
jaroslav@1258
   882
        if (b.intLen == 0)
jaroslav@1258
   883
            throw new ArithmeticException("BigInteger divide by zero");
jaroslav@1258
   884
jaroslav@1258
   885
        // Dividend is zero
jaroslav@1258
   886
        if (intLen == 0) {
jaroslav@1258
   887
            quotient.intLen = quotient.offset;
jaroslav@1258
   888
            return new MutableBigInteger();
jaroslav@1258
   889
        }
jaroslav@1258
   890
jaroslav@1258
   891
        int cmp = compare(b);
jaroslav@1258
   892
        // Dividend less than divisor
jaroslav@1258
   893
        if (cmp < 0) {
jaroslav@1258
   894
            quotient.intLen = quotient.offset = 0;
jaroslav@1258
   895
            return new MutableBigInteger(this);
jaroslav@1258
   896
        }
jaroslav@1258
   897
        // Dividend equal to divisor
jaroslav@1258
   898
        if (cmp == 0) {
jaroslav@1258
   899
            quotient.value[0] = quotient.intLen = 1;
jaroslav@1258
   900
            quotient.offset = 0;
jaroslav@1258
   901
            return new MutableBigInteger();
jaroslav@1258
   902
        }
jaroslav@1258
   903
jaroslav@1258
   904
        quotient.clear();
jaroslav@1258
   905
        // Special case one word divisor
jaroslav@1258
   906
        if (b.intLen == 1) {
jaroslav@1258
   907
            int r = divideOneWord(b.value[b.offset], quotient);
jaroslav@1258
   908
            if (r == 0)
jaroslav@1258
   909
                return new MutableBigInteger();
jaroslav@1258
   910
            return new MutableBigInteger(r);
jaroslav@1258
   911
        }
jaroslav@1258
   912
jaroslav@1258
   913
        // Copy divisor value to protect divisor
jaroslav@1258
   914
        int[] div = Arrays.copyOfRange(b.value, b.offset, b.offset + b.intLen);
jaroslav@1258
   915
        return divideMagnitude(div, quotient);
jaroslav@1258
   916
    }
jaroslav@1258
   917
jaroslav@1258
   918
    /**
jaroslav@1258
   919
     * Internally used  to calculate the quotient of this div v and places the
jaroslav@1258
   920
     * quotient in the provided MutableBigInteger object and the remainder is
jaroslav@1258
   921
     * returned.
jaroslav@1258
   922
     *
jaroslav@1258
   923
     * @return the remainder of the division will be returned.
jaroslav@1258
   924
     */
jaroslav@1258
   925
    long divide(long v, MutableBigInteger quotient) {
jaroslav@1258
   926
        if (v == 0)
jaroslav@1258
   927
            throw new ArithmeticException("BigInteger divide by zero");
jaroslav@1258
   928
jaroslav@1258
   929
        // Dividend is zero
jaroslav@1258
   930
        if (intLen == 0) {
jaroslav@1258
   931
            quotient.intLen = quotient.offset = 0;
jaroslav@1258
   932
            return 0;
jaroslav@1258
   933
        }
jaroslav@1258
   934
        if (v < 0)
jaroslav@1258
   935
            v = -v;
jaroslav@1258
   936
jaroslav@1258
   937
        int d = (int)(v >>> 32);
jaroslav@1258
   938
        quotient.clear();
jaroslav@1258
   939
        // Special case on word divisor
jaroslav@1258
   940
        if (d == 0)
jaroslav@1258
   941
            return divideOneWord((int)v, quotient) & LONG_MASK;
jaroslav@1258
   942
        else {
jaroslav@1258
   943
            int[] div = new int[]{ d, (int)(v & LONG_MASK) };
jaroslav@1258
   944
            return divideMagnitude(div, quotient).toLong();
jaroslav@1258
   945
        }
jaroslav@1258
   946
    }
jaroslav@1258
   947
jaroslav@1258
   948
    /**
jaroslav@1258
   949
     * Divide this MutableBigInteger by the divisor represented by its magnitude
jaroslav@1258
   950
     * array. The quotient will be placed into the provided quotient object &
jaroslav@1258
   951
     * the remainder object is returned.
jaroslav@1258
   952
     */
jaroslav@1258
   953
    private MutableBigInteger divideMagnitude(int[] divisor,
jaroslav@1258
   954
                                              MutableBigInteger quotient) {
jaroslav@1258
   955
jaroslav@1258
   956
        // Remainder starts as dividend with space for a leading zero
jaroslav@1258
   957
        MutableBigInteger rem = new MutableBigInteger(new int[intLen + 1]);
jaroslav@1258
   958
        System.arraycopy(value, offset, rem.value, 1, intLen);
jaroslav@1258
   959
        rem.intLen = intLen;
jaroslav@1258
   960
        rem.offset = 1;
jaroslav@1258
   961
jaroslav@1258
   962
        int nlen = rem.intLen;
jaroslav@1258
   963
jaroslav@1258
   964
        // Set the quotient size
jaroslav@1258
   965
        int dlen = divisor.length;
jaroslav@1258
   966
        int limit = nlen - dlen + 1;
jaroslav@1258
   967
        if (quotient.value.length < limit) {
jaroslav@1258
   968
            quotient.value = new int[limit];
jaroslav@1258
   969
            quotient.offset = 0;
jaroslav@1258
   970
        }
jaroslav@1258
   971
        quotient.intLen = limit;
jaroslav@1258
   972
        int[] q = quotient.value;
jaroslav@1258
   973
jaroslav@1258
   974
        // D1 normalize the divisor
jaroslav@1258
   975
        int shift = Integer.numberOfLeadingZeros(divisor[0]);
jaroslav@1258
   976
        if (shift > 0) {
jaroslav@1258
   977
            // First shift will not grow array
jaroslav@1258
   978
            BigInteger.primitiveLeftShift(divisor, dlen, shift);
jaroslav@1258
   979
            // But this one might
jaroslav@1258
   980
            rem.leftShift(shift);
jaroslav@1258
   981
        }
jaroslav@1258
   982
jaroslav@1258
   983
        // Must insert leading 0 in rem if its length did not change
jaroslav@1258
   984
        if (rem.intLen == nlen) {
jaroslav@1258
   985
            rem.offset = 0;
jaroslav@1258
   986
            rem.value[0] = 0;
jaroslav@1258
   987
            rem.intLen++;
jaroslav@1258
   988
        }
jaroslav@1258
   989
jaroslav@1258
   990
        int dh = divisor[0];
jaroslav@1258
   991
        long dhLong = dh & LONG_MASK;
jaroslav@1258
   992
        int dl = divisor[1];
jaroslav@1258
   993
        int[] qWord = new int[2];
jaroslav@1258
   994
jaroslav@1258
   995
        // D2 Initialize j
jaroslav@1258
   996
        for(int j=0; j<limit; j++) {
jaroslav@1258
   997
            // D3 Calculate qhat
jaroslav@1258
   998
            // estimate qhat
jaroslav@1258
   999
            int qhat = 0;
jaroslav@1258
  1000
            int qrem = 0;
jaroslav@1258
  1001
            boolean skipCorrection = false;
jaroslav@1258
  1002
            int nh = rem.value[j+rem.offset];
jaroslav@1258
  1003
            int nh2 = nh + 0x80000000;
jaroslav@1258
  1004
            int nm = rem.value[j+1+rem.offset];
jaroslav@1258
  1005
jaroslav@1258
  1006
            if (nh == dh) {
jaroslav@1258
  1007
                qhat = ~0;
jaroslav@1258
  1008
                qrem = nh + nm;
jaroslav@1258
  1009
                skipCorrection = qrem + 0x80000000 < nh2;
jaroslav@1258
  1010
            } else {
jaroslav@1258
  1011
                long nChunk = (((long)nh) << 32) | (nm & LONG_MASK);
jaroslav@1258
  1012
                if (nChunk >= 0) {
jaroslav@1258
  1013
                    qhat = (int) (nChunk / dhLong);
jaroslav@1258
  1014
                    qrem = (int) (nChunk - (qhat * dhLong));
jaroslav@1258
  1015
                } else {
jaroslav@1258
  1016
                    divWord(qWord, nChunk, dh);
jaroslav@1258
  1017
                    qhat = qWord[0];
jaroslav@1258
  1018
                    qrem = qWord[1];
jaroslav@1258
  1019
                }
jaroslav@1258
  1020
            }
jaroslav@1258
  1021
jaroslav@1258
  1022
            if (qhat == 0)
jaroslav@1258
  1023
                continue;
jaroslav@1258
  1024
jaroslav@1258
  1025
            if (!skipCorrection) { // Correct qhat
jaroslav@1258
  1026
                long nl = rem.value[j+2+rem.offset] & LONG_MASK;
jaroslav@1258
  1027
                long rs = ((qrem & LONG_MASK) << 32) | nl;
jaroslav@1258
  1028
                long estProduct = (dl & LONG_MASK) * (qhat & LONG_MASK);
jaroslav@1258
  1029
jaroslav@1258
  1030
                if (unsignedLongCompare(estProduct, rs)) {
jaroslav@1258
  1031
                    qhat--;
jaroslav@1258
  1032
                    qrem = (int)((qrem & LONG_MASK) + dhLong);
jaroslav@1258
  1033
                    if ((qrem & LONG_MASK) >=  dhLong) {
jaroslav@1258
  1034
                        estProduct -= (dl & LONG_MASK);
jaroslav@1258
  1035
                        rs = ((qrem & LONG_MASK) << 32) | nl;
jaroslav@1258
  1036
                        if (unsignedLongCompare(estProduct, rs))
jaroslav@1258
  1037
                            qhat--;
jaroslav@1258
  1038
                    }
jaroslav@1258
  1039
                }
jaroslav@1258
  1040
            }
jaroslav@1258
  1041
jaroslav@1258
  1042
            // D4 Multiply and subtract
jaroslav@1258
  1043
            rem.value[j+rem.offset] = 0;
jaroslav@1258
  1044
            int borrow = mulsub(rem.value, divisor, qhat, dlen, j+rem.offset);
jaroslav@1258
  1045
jaroslav@1258
  1046
            // D5 Test remainder
jaroslav@1258
  1047
            if (borrow + 0x80000000 > nh2) {
jaroslav@1258
  1048
                // D6 Add back
jaroslav@1258
  1049
                divadd(divisor, rem.value, j+1+rem.offset);
jaroslav@1258
  1050
                qhat--;
jaroslav@1258
  1051
            }
jaroslav@1258
  1052
jaroslav@1258
  1053
            // Store the quotient digit
jaroslav@1258
  1054
            q[j] = qhat;
jaroslav@1258
  1055
        } // D7 loop on j
jaroslav@1258
  1056
jaroslav@1258
  1057
        // D8 Unnormalize
jaroslav@1258
  1058
        if (shift > 0)
jaroslav@1258
  1059
            rem.rightShift(shift);
jaroslav@1258
  1060
jaroslav@1258
  1061
        quotient.normalize();
jaroslav@1258
  1062
        rem.normalize();
jaroslav@1258
  1063
        return rem;
jaroslav@1258
  1064
    }
jaroslav@1258
  1065
jaroslav@1258
  1066
    /**
jaroslav@1258
  1067
     * Compare two longs as if they were unsigned.
jaroslav@1258
  1068
     * Returns true iff one is bigger than two.
jaroslav@1258
  1069
     */
jaroslav@1258
  1070
    private boolean unsignedLongCompare(long one, long two) {
jaroslav@1258
  1071
        return (one+Long.MIN_VALUE) > (two+Long.MIN_VALUE);
jaroslav@1258
  1072
    }
jaroslav@1258
  1073
jaroslav@1258
  1074
    /**
jaroslav@1258
  1075
     * This method divides a long quantity by an int to estimate
jaroslav@1258
  1076
     * qhat for two multi precision numbers. It is used when
jaroslav@1258
  1077
     * the signed value of n is less than zero.
jaroslav@1258
  1078
     */
jaroslav@1258
  1079
    private void divWord(int[] result, long n, int d) {
jaroslav@1258
  1080
        long dLong = d & LONG_MASK;
jaroslav@1258
  1081
jaroslav@1258
  1082
        if (dLong == 1) {
jaroslav@1258
  1083
            result[0] = (int)n;
jaroslav@1258
  1084
            result[1] = 0;
jaroslav@1258
  1085
            return;
jaroslav@1258
  1086
        }
jaroslav@1258
  1087
jaroslav@1258
  1088
        // Approximate the quotient and remainder
jaroslav@1258
  1089
        long q = (n >>> 1) / (dLong >>> 1);
jaroslav@1258
  1090
        long r = n - q*dLong;
jaroslav@1258
  1091
jaroslav@1258
  1092
        // Correct the approximation
jaroslav@1258
  1093
        while (r < 0) {
jaroslav@1258
  1094
            r += dLong;
jaroslav@1258
  1095
            q--;
jaroslav@1258
  1096
        }
jaroslav@1258
  1097
        while (r >= dLong) {
jaroslav@1258
  1098
            r -= dLong;
jaroslav@1258
  1099
            q++;
jaroslav@1258
  1100
        }
jaroslav@1258
  1101
jaroslav@1258
  1102
        // n - q*dlong == r && 0 <= r <dLong, hence we're done.
jaroslav@1258
  1103
        result[0] = (int)q;
jaroslav@1258
  1104
        result[1] = (int)r;
jaroslav@1258
  1105
    }
jaroslav@1258
  1106
jaroslav@1258
  1107
    /**
jaroslav@1258
  1108
     * Calculate GCD of this and b. This and b are changed by the computation.
jaroslav@1258
  1109
     */
jaroslav@1258
  1110
    MutableBigInteger hybridGCD(MutableBigInteger b) {
jaroslav@1258
  1111
        // Use Euclid's algorithm until the numbers are approximately the
jaroslav@1258
  1112
        // same length, then use the binary GCD algorithm to find the GCD.
jaroslav@1258
  1113
        MutableBigInteger a = this;
jaroslav@1258
  1114
        MutableBigInteger q = new MutableBigInteger();
jaroslav@1258
  1115
jaroslav@1258
  1116
        while (b.intLen != 0) {
jaroslav@1258
  1117
            if (Math.abs(a.intLen - b.intLen) < 2)
jaroslav@1258
  1118
                return a.binaryGCD(b);
jaroslav@1258
  1119
jaroslav@1258
  1120
            MutableBigInteger r = a.divide(b, q);
jaroslav@1258
  1121
            a = b;
jaroslav@1258
  1122
            b = r;
jaroslav@1258
  1123
        }
jaroslav@1258
  1124
        return a;
jaroslav@1258
  1125
    }
jaroslav@1258
  1126
jaroslav@1258
  1127
    /**
jaroslav@1258
  1128
     * Calculate GCD of this and v.
jaroslav@1258
  1129
     * Assumes that this and v are not zero.
jaroslav@1258
  1130
     */
jaroslav@1258
  1131
    private MutableBigInteger binaryGCD(MutableBigInteger v) {
jaroslav@1258
  1132
        // Algorithm B from Knuth section 4.5.2
jaroslav@1258
  1133
        MutableBigInteger u = this;
jaroslav@1258
  1134
        MutableBigInteger r = new MutableBigInteger();
jaroslav@1258
  1135
jaroslav@1258
  1136
        // step B1
jaroslav@1258
  1137
        int s1 = u.getLowestSetBit();
jaroslav@1258
  1138
        int s2 = v.getLowestSetBit();
jaroslav@1258
  1139
        int k = (s1 < s2) ? s1 : s2;
jaroslav@1258
  1140
        if (k != 0) {
jaroslav@1258
  1141
            u.rightShift(k);
jaroslav@1258
  1142
            v.rightShift(k);
jaroslav@1258
  1143
        }
jaroslav@1258
  1144
jaroslav@1258
  1145
        // step B2
jaroslav@1258
  1146
        boolean uOdd = (k==s1);
jaroslav@1258
  1147
        MutableBigInteger t = uOdd ? v: u;
jaroslav@1258
  1148
        int tsign = uOdd ? -1 : 1;
jaroslav@1258
  1149
jaroslav@1258
  1150
        int lb;
jaroslav@1258
  1151
        while ((lb = t.getLowestSetBit()) >= 0) {
jaroslav@1258
  1152
            // steps B3 and B4
jaroslav@1258
  1153
            t.rightShift(lb);
jaroslav@1258
  1154
            // step B5
jaroslav@1258
  1155
            if (tsign > 0)
jaroslav@1258
  1156
                u = t;
jaroslav@1258
  1157
            else
jaroslav@1258
  1158
                v = t;
jaroslav@1258
  1159
jaroslav@1258
  1160
            // Special case one word numbers
jaroslav@1258
  1161
            if (u.intLen < 2 && v.intLen < 2) {
jaroslav@1258
  1162
                int x = u.value[u.offset];
jaroslav@1258
  1163
                int y = v.value[v.offset];
jaroslav@1258
  1164
                x  = binaryGcd(x, y);
jaroslav@1258
  1165
                r.value[0] = x;
jaroslav@1258
  1166
                r.intLen = 1;
jaroslav@1258
  1167
                r.offset = 0;
jaroslav@1258
  1168
                if (k > 0)
jaroslav@1258
  1169
                    r.leftShift(k);
jaroslav@1258
  1170
                return r;
jaroslav@1258
  1171
            }
jaroslav@1258
  1172
jaroslav@1258
  1173
            // step B6
jaroslav@1258
  1174
            if ((tsign = u.difference(v)) == 0)
jaroslav@1258
  1175
                break;
jaroslav@1258
  1176
            t = (tsign >= 0) ? u : v;
jaroslav@1258
  1177
        }
jaroslav@1258
  1178
jaroslav@1258
  1179
        if (k > 0)
jaroslav@1258
  1180
            u.leftShift(k);
jaroslav@1258
  1181
        return u;
jaroslav@1258
  1182
    }
jaroslav@1258
  1183
jaroslav@1258
  1184
    /**
jaroslav@1258
  1185
     * Calculate GCD of a and b interpreted as unsigned integers.
jaroslav@1258
  1186
     */
jaroslav@1258
  1187
    static int binaryGcd(int a, int b) {
jaroslav@1258
  1188
        if (b==0)
jaroslav@1258
  1189
            return a;
jaroslav@1258
  1190
        if (a==0)
jaroslav@1258
  1191
            return b;
jaroslav@1258
  1192
jaroslav@1258
  1193
        // Right shift a & b till their last bits equal to 1.
jaroslav@1258
  1194
        int aZeros = Integer.numberOfTrailingZeros(a);
jaroslav@1258
  1195
        int bZeros = Integer.numberOfTrailingZeros(b);
jaroslav@1258
  1196
        a >>>= aZeros;
jaroslav@1258
  1197
        b >>>= bZeros;
jaroslav@1258
  1198
jaroslav@1258
  1199
        int t = (aZeros < bZeros ? aZeros : bZeros);
jaroslav@1258
  1200
jaroslav@1258
  1201
        while (a != b) {
jaroslav@1258
  1202
            if ((a+0x80000000) > (b+0x80000000)) {  // a > b as unsigned
jaroslav@1258
  1203
                a -= b;
jaroslav@1258
  1204
                a >>>= Integer.numberOfTrailingZeros(a);
jaroslav@1258
  1205
            } else {
jaroslav@1258
  1206
                b -= a;
jaroslav@1258
  1207
                b >>>= Integer.numberOfTrailingZeros(b);
jaroslav@1258
  1208
            }
jaroslav@1258
  1209
        }
jaroslav@1258
  1210
        return a<<t;
jaroslav@1258
  1211
    }
jaroslav@1258
  1212
jaroslav@1258
  1213
    /**
jaroslav@1258
  1214
     * Returns the modInverse of this mod p. This and p are not affected by
jaroslav@1258
  1215
     * the operation.
jaroslav@1258
  1216
     */
jaroslav@1258
  1217
    MutableBigInteger mutableModInverse(MutableBigInteger p) {
jaroslav@1258
  1218
        // Modulus is odd, use Schroeppel's algorithm
jaroslav@1258
  1219
        if (p.isOdd())
jaroslav@1258
  1220
            return modInverse(p);
jaroslav@1258
  1221
jaroslav@1258
  1222
        // Base and modulus are even, throw exception
jaroslav@1258
  1223
        if (isEven())
jaroslav@1258
  1224
            throw new ArithmeticException("BigInteger not invertible.");
jaroslav@1258
  1225
jaroslav@1258
  1226
        // Get even part of modulus expressed as a power of 2
jaroslav@1258
  1227
        int powersOf2 = p.getLowestSetBit();
jaroslav@1258
  1228
jaroslav@1258
  1229
        // Construct odd part of modulus
jaroslav@1258
  1230
        MutableBigInteger oddMod = new MutableBigInteger(p);
jaroslav@1258
  1231
        oddMod.rightShift(powersOf2);
jaroslav@1258
  1232
jaroslav@1258
  1233
        if (oddMod.isOne())
jaroslav@1258
  1234
            return modInverseMP2(powersOf2);
jaroslav@1258
  1235
jaroslav@1258
  1236
        // Calculate 1/a mod oddMod
jaroslav@1258
  1237
        MutableBigInteger oddPart = modInverse(oddMod);
jaroslav@1258
  1238
jaroslav@1258
  1239
        // Calculate 1/a mod evenMod
jaroslav@1258
  1240
        MutableBigInteger evenPart = modInverseMP2(powersOf2);
jaroslav@1258
  1241
jaroslav@1258
  1242
        // Combine the results using Chinese Remainder Theorem
jaroslav@1258
  1243
        MutableBigInteger y1 = modInverseBP2(oddMod, powersOf2);
jaroslav@1258
  1244
        MutableBigInteger y2 = oddMod.modInverseMP2(powersOf2);
jaroslav@1258
  1245
jaroslav@1258
  1246
        MutableBigInteger temp1 = new MutableBigInteger();
jaroslav@1258
  1247
        MutableBigInteger temp2 = new MutableBigInteger();
jaroslav@1258
  1248
        MutableBigInteger result = new MutableBigInteger();
jaroslav@1258
  1249
jaroslav@1258
  1250
        oddPart.leftShift(powersOf2);
jaroslav@1258
  1251
        oddPart.multiply(y1, result);
jaroslav@1258
  1252
jaroslav@1258
  1253
        evenPart.multiply(oddMod, temp1);
jaroslav@1258
  1254
        temp1.multiply(y2, temp2);
jaroslav@1258
  1255
jaroslav@1258
  1256
        result.add(temp2);
jaroslav@1258
  1257
        return result.divide(p, temp1);
jaroslav@1258
  1258
    }
jaroslav@1258
  1259
jaroslav@1258
  1260
    /*
jaroslav@1258
  1261
     * Calculate the multiplicative inverse of this mod 2^k.
jaroslav@1258
  1262
     */
jaroslav@1258
  1263
    MutableBigInteger modInverseMP2(int k) {
jaroslav@1258
  1264
        if (isEven())
jaroslav@1258
  1265
            throw new ArithmeticException("Non-invertible. (GCD != 1)");
jaroslav@1258
  1266
jaroslav@1258
  1267
        if (k > 64)
jaroslav@1258
  1268
            return euclidModInverse(k);
jaroslav@1258
  1269
jaroslav@1258
  1270
        int t = inverseMod32(value[offset+intLen-1]);
jaroslav@1258
  1271
jaroslav@1258
  1272
        if (k < 33) {
jaroslav@1258
  1273
            t = (k == 32 ? t : t & ((1 << k) - 1));
jaroslav@1258
  1274
            return new MutableBigInteger(t);
jaroslav@1258
  1275
        }
jaroslav@1258
  1276
jaroslav@1258
  1277
        long pLong = (value[offset+intLen-1] & LONG_MASK);
jaroslav@1258
  1278
        if (intLen > 1)
jaroslav@1258
  1279
            pLong |=  ((long)value[offset+intLen-2] << 32);
jaroslav@1258
  1280
        long tLong = t & LONG_MASK;
jaroslav@1258
  1281
        tLong = tLong * (2 - pLong * tLong);  // 1 more Newton iter step
jaroslav@1258
  1282
        tLong = (k == 64 ? tLong : tLong & ((1L << k) - 1));
jaroslav@1258
  1283
jaroslav@1258
  1284
        MutableBigInteger result = new MutableBigInteger(new int[2]);
jaroslav@1258
  1285
        result.value[0] = (int)(tLong >>> 32);
jaroslav@1258
  1286
        result.value[1] = (int)tLong;
jaroslav@1258
  1287
        result.intLen = 2;
jaroslav@1258
  1288
        result.normalize();
jaroslav@1258
  1289
        return result;
jaroslav@1258
  1290
    }
jaroslav@1258
  1291
jaroslav@1258
  1292
    /*
jaroslav@1258
  1293
     * Returns the multiplicative inverse of val mod 2^32.  Assumes val is odd.
jaroslav@1258
  1294
     */
jaroslav@1258
  1295
    static int inverseMod32(int val) {
jaroslav@1258
  1296
        // Newton's iteration!
jaroslav@1258
  1297
        int t = val;
jaroslav@1258
  1298
        t *= 2 - val*t;
jaroslav@1258
  1299
        t *= 2 - val*t;
jaroslav@1258
  1300
        t *= 2 - val*t;
jaroslav@1258
  1301
        t *= 2 - val*t;
jaroslav@1258
  1302
        return t;
jaroslav@1258
  1303
    }
jaroslav@1258
  1304
jaroslav@1258
  1305
    /*
jaroslav@1258
  1306
     * Calculate the multiplicative inverse of 2^k mod mod, where mod is odd.
jaroslav@1258
  1307
     */
jaroslav@1258
  1308
    static MutableBigInteger modInverseBP2(MutableBigInteger mod, int k) {
jaroslav@1258
  1309
        // Copy the mod to protect original
jaroslav@1258
  1310
        return fixup(new MutableBigInteger(1), new MutableBigInteger(mod), k);
jaroslav@1258
  1311
    }
jaroslav@1258
  1312
jaroslav@1258
  1313
    /**
jaroslav@1258
  1314
     * Calculate the multiplicative inverse of this mod mod, where mod is odd.
jaroslav@1258
  1315
     * This and mod are not changed by the calculation.
jaroslav@1258
  1316
     *
jaroslav@1258
  1317
     * This method implements an algorithm due to Richard Schroeppel, that uses
jaroslav@1258
  1318
     * the same intermediate representation as Montgomery Reduction
jaroslav@1258
  1319
     * ("Montgomery Form").  The algorithm is described in an unpublished
jaroslav@1258
  1320
     * manuscript entitled "Fast Modular Reciprocals."
jaroslav@1258
  1321
     */
jaroslav@1258
  1322
    private MutableBigInteger modInverse(MutableBigInteger mod) {
jaroslav@1258
  1323
        MutableBigInteger p = new MutableBigInteger(mod);
jaroslav@1258
  1324
        MutableBigInteger f = new MutableBigInteger(this);
jaroslav@1258
  1325
        MutableBigInteger g = new MutableBigInteger(p);
jaroslav@1258
  1326
        SignedMutableBigInteger c = new SignedMutableBigInteger(1);
jaroslav@1258
  1327
        SignedMutableBigInteger d = new SignedMutableBigInteger();
jaroslav@1258
  1328
        MutableBigInteger temp = null;
jaroslav@1258
  1329
        SignedMutableBigInteger sTemp = null;
jaroslav@1258
  1330
jaroslav@1258
  1331
        int k = 0;
jaroslav@1258
  1332
        // Right shift f k times until odd, left shift d k times
jaroslav@1258
  1333
        if (f.isEven()) {
jaroslav@1258
  1334
            int trailingZeros = f.getLowestSetBit();
jaroslav@1258
  1335
            f.rightShift(trailingZeros);
jaroslav@1258
  1336
            d.leftShift(trailingZeros);
jaroslav@1258
  1337
            k = trailingZeros;
jaroslav@1258
  1338
        }
jaroslav@1258
  1339
jaroslav@1258
  1340
        // The Almost Inverse Algorithm
jaroslav@1258
  1341
        while(!f.isOne()) {
jaroslav@1258
  1342
            // If gcd(f, g) != 1, number is not invertible modulo mod
jaroslav@1258
  1343
            if (f.isZero())
jaroslav@1258
  1344
                throw new ArithmeticException("BigInteger not invertible.");
jaroslav@1258
  1345
jaroslav@1258
  1346
            // If f < g exchange f, g and c, d
jaroslav@1258
  1347
            if (f.compare(g) < 0) {
jaroslav@1258
  1348
                temp = f; f = g; g = temp;
jaroslav@1258
  1349
                sTemp = d; d = c; c = sTemp;
jaroslav@1258
  1350
            }
jaroslav@1258
  1351
jaroslav@1258
  1352
            // If f == g (mod 4)
jaroslav@1258
  1353
            if (((f.value[f.offset + f.intLen - 1] ^
jaroslav@1258
  1354
                 g.value[g.offset + g.intLen - 1]) & 3) == 0) {
jaroslav@1258
  1355
                f.subtract(g);
jaroslav@1258
  1356
                c.signedSubtract(d);
jaroslav@1258
  1357
            } else { // If f != g (mod 4)
jaroslav@1258
  1358
                f.add(g);
jaroslav@1258
  1359
                c.signedAdd(d);
jaroslav@1258
  1360
            }
jaroslav@1258
  1361
jaroslav@1258
  1362
            // Right shift f k times until odd, left shift d k times
jaroslav@1258
  1363
            int trailingZeros = f.getLowestSetBit();
jaroslav@1258
  1364
            f.rightShift(trailingZeros);
jaroslav@1258
  1365
            d.leftShift(trailingZeros);
jaroslav@1258
  1366
            k += trailingZeros;
jaroslav@1258
  1367
        }
jaroslav@1258
  1368
jaroslav@1258
  1369
        while (c.sign < 0)
jaroslav@1258
  1370
           c.signedAdd(p);
jaroslav@1258
  1371
jaroslav@1258
  1372
        return fixup(c, p, k);
jaroslav@1258
  1373
    }
jaroslav@1258
  1374
jaroslav@1258
  1375
    /*
jaroslav@1258
  1376
     * The Fixup Algorithm
jaroslav@1258
  1377
     * Calculates X such that X = C * 2^(-k) (mod P)
jaroslav@1258
  1378
     * Assumes C<P and P is odd.
jaroslav@1258
  1379
     */
jaroslav@1258
  1380
    static MutableBigInteger fixup(MutableBigInteger c, MutableBigInteger p,
jaroslav@1258
  1381
                                                                      int k) {
jaroslav@1258
  1382
        MutableBigInteger temp = new MutableBigInteger();
jaroslav@1258
  1383
        // Set r to the multiplicative inverse of p mod 2^32
jaroslav@1258
  1384
        int r = -inverseMod32(p.value[p.offset+p.intLen-1]);
jaroslav@1258
  1385
jaroslav@1258
  1386
        for(int i=0, numWords = k >> 5; i<numWords; i++) {
jaroslav@1258
  1387
            // V = R * c (mod 2^j)
jaroslav@1258
  1388
            int  v = r * c.value[c.offset + c.intLen-1];
jaroslav@1258
  1389
            // c = c + (v * p)
jaroslav@1258
  1390
            p.mul(v, temp);
jaroslav@1258
  1391
            c.add(temp);
jaroslav@1258
  1392
            // c = c / 2^j
jaroslav@1258
  1393
            c.intLen--;
jaroslav@1258
  1394
        }
jaroslav@1258
  1395
        int numBits = k & 0x1f;
jaroslav@1258
  1396
        if (numBits != 0) {
jaroslav@1258
  1397
            // V = R * c (mod 2^j)
jaroslav@1258
  1398
            int v = r * c.value[c.offset + c.intLen-1];
jaroslav@1258
  1399
            v &= ((1<<numBits) - 1);
jaroslav@1258
  1400
            // c = c + (v * p)
jaroslav@1258
  1401
            p.mul(v, temp);
jaroslav@1258
  1402
            c.add(temp);
jaroslav@1258
  1403
            // c = c / 2^j
jaroslav@1258
  1404
            c.rightShift(numBits);
jaroslav@1258
  1405
        }
jaroslav@1258
  1406
jaroslav@1258
  1407
        // In theory, c may be greater than p at this point (Very rare!)
jaroslav@1258
  1408
        while (c.compare(p) >= 0)
jaroslav@1258
  1409
            c.subtract(p);
jaroslav@1258
  1410
jaroslav@1258
  1411
        return c;
jaroslav@1258
  1412
    }
jaroslav@1258
  1413
jaroslav@1258
  1414
    /**
jaroslav@1258
  1415
     * Uses the extended Euclidean algorithm to compute the modInverse of base
jaroslav@1258
  1416
     * mod a modulus that is a power of 2. The modulus is 2^k.
jaroslav@1258
  1417
     */
jaroslav@1258
  1418
    MutableBigInteger euclidModInverse(int k) {
jaroslav@1258
  1419
        MutableBigInteger b = new MutableBigInteger(1);
jaroslav@1258
  1420
        b.leftShift(k);
jaroslav@1258
  1421
        MutableBigInteger mod = new MutableBigInteger(b);
jaroslav@1258
  1422
jaroslav@1258
  1423
        MutableBigInteger a = new MutableBigInteger(this);
jaroslav@1258
  1424
        MutableBigInteger q = new MutableBigInteger();
jaroslav@1258
  1425
        MutableBigInteger r = b.divide(a, q);
jaroslav@1258
  1426
jaroslav@1258
  1427
        MutableBigInteger swapper = b;
jaroslav@1258
  1428
        // swap b & r
jaroslav@1258
  1429
        b = r;
jaroslav@1258
  1430
        r = swapper;
jaroslav@1258
  1431
jaroslav@1258
  1432
        MutableBigInteger t1 = new MutableBigInteger(q);
jaroslav@1258
  1433
        MutableBigInteger t0 = new MutableBigInteger(1);
jaroslav@1258
  1434
        MutableBigInteger temp = new MutableBigInteger();
jaroslav@1258
  1435
jaroslav@1258
  1436
        while (!b.isOne()) {
jaroslav@1258
  1437
            r = a.divide(b, q);
jaroslav@1258
  1438
jaroslav@1258
  1439
            if (r.intLen == 0)
jaroslav@1258
  1440
                throw new ArithmeticException("BigInteger not invertible.");
jaroslav@1258
  1441
jaroslav@1258
  1442
            swapper = r;
jaroslav@1258
  1443
            a = swapper;
jaroslav@1258
  1444
jaroslav@1258
  1445
            if (q.intLen == 1)
jaroslav@1258
  1446
                t1.mul(q.value[q.offset], temp);
jaroslav@1258
  1447
            else
jaroslav@1258
  1448
                q.multiply(t1, temp);
jaroslav@1258
  1449
            swapper = q;
jaroslav@1258
  1450
            q = temp;
jaroslav@1258
  1451
            temp = swapper;
jaroslav@1258
  1452
            t0.add(q);
jaroslav@1258
  1453
jaroslav@1258
  1454
            if (a.isOne())
jaroslav@1258
  1455
                return t0;
jaroslav@1258
  1456
jaroslav@1258
  1457
            r = b.divide(a, q);
jaroslav@1258
  1458
jaroslav@1258
  1459
            if (r.intLen == 0)
jaroslav@1258
  1460
                throw new ArithmeticException("BigInteger not invertible.");
jaroslav@1258
  1461
jaroslav@1258
  1462
            swapper = b;
jaroslav@1258
  1463
            b =  r;
jaroslav@1258
  1464
jaroslav@1258
  1465
            if (q.intLen == 1)
jaroslav@1258
  1466
                t0.mul(q.value[q.offset], temp);
jaroslav@1258
  1467
            else
jaroslav@1258
  1468
                q.multiply(t0, temp);
jaroslav@1258
  1469
            swapper = q; q = temp; temp = swapper;
jaroslav@1258
  1470
jaroslav@1258
  1471
            t1.add(q);
jaroslav@1258
  1472
        }
jaroslav@1258
  1473
        mod.subtract(t1);
jaroslav@1258
  1474
        return mod;
jaroslav@1258
  1475
    }
jaroslav@1258
  1476
jaroslav@1258
  1477
}