2 Copyright (C) 1999, 2000, 2001, 2004 Free Software Foundation, Inc.
4 This file is part of GNU Classpath.
6 GNU Classpath is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2, or (at your option)
11 GNU Classpath is distributed in the hope that it will be useful, but
12 WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with GNU Classpath; see the file COPYING. If not, write to the
18 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
21 Linking this library statically or dynamically with other modules is
22 making a combined work based on this library. Thus, the terms and
23 conditions of the GNU General Public License cover the whole
26 As a special exception, the copyright holders of this library give you
27 permission to link this library with independent modules to produce an
28 executable, regardless of the license terms of these independent
29 modules, and to copy and distribute the resulting executable under
30 terms of your choice, provided that you also meet, for each linked
31 independent module, the terms and conditions of the license of that
32 module. An independent module is a module which is not derived from
33 or based on this library. If you modify this library, you may extend
34 this exception to your version of the library, but you are not
35 obligated to do so. If you do not wish to do so, delete this
36 exception statement from your version. */
38 // Included from Kawa 1.6.62 with permission of the author,
39 // Per Bothner <per@bothner.com>.
41 //package gnu.java.math;
43 /** This contains various low-level routines for unsigned bigints.
44 * The interfaces match the mpn interfaces in gmp,
45 * so it should be easy to replace them with fast native functions
46 * that are trivial wrappers around the mpn_ functions in gmp
47 * (at least on platforms that use 32-bit "limbs").
52 /** Add x[0:size-1] and y, and write the size least
53 * significant words of the result to dest.
54 * Return carry, either 0 or 1.
55 * All values are unsigned.
56 * This is basically the same as gmp's mpn_add_1. */
57 public static int add_1 (int[] dest, int[] x, int size, int y)
59 long carry = (long) y & 0xffffffffL;
60 for (int i = 0; i < size; i++)
62 carry += ((long) x[i] & 0xffffffffL);
63 dest[i] = (int) carry;
69 /** Add x[0:len-1] and y[0:len-1] and write the len least
70 * significant words of the result to dest[0:len-1].
71 * All words are treated as unsigned.
72 * @return the carry, either 0 or 1
73 * This function is basically the same as gmp's mpn_add_n.
75 public static int add_n (int dest[], int[] x, int[] y, int len)
78 for (int i = 0; i < len; i++)
80 carry += ((long) x[i] & 0xffffffffL)
81 + ((long) y[i] & 0xffffffffL);
82 dest[i] = (int) carry;
88 /** Subtract Y[0:size-1] from X[0:size-1], and write
89 * the size least significant words of the result to dest[0:size-1].
90 * Return borrow, either 0 or 1.
91 * This is basically the same as gmp's mpn_sub_n function.
94 public static int sub_n (int[] dest, int[] X, int[] Y, int size)
97 for (int i = 0; i < size; i++)
101 y += cy; /* add previous carry to subtrahend */
102 // Invert the high-order bit, because: (unsigned) X > (unsigned) Y
103 // iff: (int) (X^0x80000000) > (int) (Y^0x80000000).
104 cy = (y^0x80000000) < (cy^0x80000000) ? 1 : 0;
106 cy += (y^0x80000000) > (x ^ 0x80000000) ? 1 : 0;
112 /** Multiply x[0:len-1] by y, and write the len least
113 * significant words of the product to dest[0:len-1].
114 * Return the most significant word of the product.
115 * All values are treated as if they were unsigned
116 * (i.e. masked with 0xffffffffL).
117 * OK if dest==x (not sure if this is guaranteed for mpn_mul_1).
118 * This function is basically the same as gmp's mpn_mul_1.
121 public static int mul_1 (int[] dest, int[] x, int len, int y)
123 long yword = (long) y & 0xffffffffL;
125 for (int j = 0; j < len; j++)
127 carry += ((long) x[j] & 0xffffffffL) * yword;
128 dest[j] = (int) carry;
135 * Multiply x[0:xlen-1] and y[0:ylen-1], and
136 * write the result to dest[0:xlen+ylen-1].
137 * The destination has to have space for xlen+ylen words,
138 * even if the result might be one limb smaller.
139 * This function requires that xlen >= ylen.
140 * The destination must be distinct from either input operands.
141 * All operands are unsigned.
142 * This function is basically the same gmp's mpn_mul. */
144 public static void mul (int[] dest,
148 dest[xlen] = MPN.mul_1 (dest, x, xlen, y[0]);
150 for (int i = 1; i < ylen; i++)
152 long yword = (long) y[i] & 0xffffffffL;
154 for (int j = 0; j < xlen; j++)
156 carry += ((long) x[j] & 0xffffffffL) * yword
157 + ((long) dest[i+j] & 0xffffffffL);
158 dest[i+j] = (int) carry;
161 dest[i+xlen] = (int) carry;
165 /* Divide (unsigned long) N by (unsigned int) D.
166 * Returns (remainder << 32)+(unsigned int)(quotient).
167 * Assumes (unsigned int)(N>>32) < (unsigned int)D.
168 * Code transcribed from gmp-2.0's mpn_udiv_w_sdiv function.
170 public static long udiv_qrnnd (long N, int D)
174 long a0 = N & 0xffffffffL;
177 if (a1 < ((D - a1 - (a0 >>> 31)) & 0xffffffffL))
179 /* dividend, divisor, and quotient are nonnegative */
185 /* Compute c1*2^32 + c0 = a1*2^32 + a0 - 2^31*d */
186 long c = N - ((long) D << 31);
187 /* Divide (c1*2^32 + c0) by d */
190 /* Add 2^31 to quotient */
196 long b1 = D >>> 1; /* d/2, between 2^30 and 2^31 - 1 */
197 //long c1 = (a1 >> 1); /* A/2 */
198 //int c0 = (a1 << 31) + (a0 >> 1);
200 if (a1 < b1 || (a1 >> 1) < b1)
207 else /* c1 < b1, so 2^31 <= (A/2)/b1 < 2^32 */
209 c = ~(c - (b1 << 32));
210 q = c / b1; /* (A/2) / (d/2) */
212 q = (~q) & 0xffffffffL; /* (A/2)/b1 */
213 r = (b1 - 1) - r; /* r < b1 => new r >= 0 */
215 r = 2 * r + (a0 & 1);
220 } else if (q - r <= ((long) D & 0xffffffffL)) {
229 else /* Implies c1 = b1 */
230 { /* Hence a1 = d - 1 = 2*b1 - 1 */
231 if (a0 >= ((long)(-D) & 0xffffffffL))
244 return (r << 32) | (q & 0xFFFFFFFFl);
247 /** Divide divident[0:len-1] by (unsigned int)divisor.
248 * Write result into quotient[0:len-1.
249 * Return the one-word (unsigned) remainder.
250 * OK for quotient==dividend.
253 public static int divmod_1 (int[] quotient, int[] dividend,
254 int len, int divisor)
257 long r = dividend[i];
258 if ((r & 0xffffffffL) >= ((long)divisor & 0xffffffffL))
268 int n0 = dividend[i];
269 r = (r & ~0xffffffffL) | (n0 & 0xffffffffL);
270 r = udiv_qrnnd (r, divisor);
271 quotient[i] = (int) r;
273 return (int)(r >> 32);
276 /* Subtract x[0:len-1]*y from dest[offset:offset+len-1].
277 * All values are treated as if unsigned.
278 * @return the most significant word of
279 * the product, minus borrow-out from the subtraction.
281 public static int submul_1 (int[] dest, int offset, int[] x, int len, int y)
283 long yl = (long) y & 0xffffffffL;
288 long prod = ((long) x[j] & 0xffffffffL) * yl;
289 int prod_low = (int) prod;
290 int prod_high = (int) (prod >> 32);
292 // Invert the high-order bit, because: (unsigned) X > (unsigned) Y
293 // iff: (int) (X^0x80000000) > (int) (Y^0x80000000).
294 carry = ((prod_low ^ 0x80000000) < (carry ^ 0x80000000) ? 1 : 0)
296 int x_j = dest[offset+j];
297 prod_low = x_j - prod_low;
298 if ((prod_low ^ 0x80000000) > (x_j ^ 0x80000000))
300 dest[offset+j] = prod_low;
306 /** Divide zds[0:nx] by y[0:ny-1].
307 * The remainder ends up in zds[0:ny-1].
308 * The quotient ends up in zds[ny:nx].
310 * (int)y[ny-1] < 0 (i.e. most significant bit set)
313 public static void divide (int[] zds, int nx, int[] y, int ny)
315 // This is basically Knuth's formulation of the classical algorithm,
316 // but translated from in scm_divbigbig in Jaffar's SCM implementation.
318 // Correspondance with Knuth's notation:
319 // Knuth's u[0:m+n] == zds[nx:0].
320 // Knuth's v[1:n] == y[ny-1:0]
322 // Knuth's m == nx-ny.
323 // Our nx == Knuth's m+n.
325 // Could be re-implemented using gmp's mpn_divrem:
326 // zds[nx] = mpn_divrem (&zds[ny], 0, zds, nx, y, ny).
330 { // loop over digits of quotient
331 // Knuth's j == our nx-j.
332 // Knuth's u[j:j+n] == our zds[j:j-ny].
333 int qhat; // treated as unsigned
335 qhat = -1; // 0xffffffff
338 long w = (((long)(zds[j])) << 32) + ((long)zds[j-1] & 0xffffffffL);
339 qhat = (int) udiv_qrnnd (w, y[ny-1]);
343 int borrow = submul_1 (zds, j - ny, y, ny, qhat);
345 long num = ((long)save&0xffffffffL) - ((long)borrow&0xffffffffL);
350 for (int i = 0; i < ny; i++)
352 carry += ((long) zds[j-ny+i] & 0xffffffffL)
353 + ((long) y[i] & 0xffffffffL);
354 zds[j-ny+i] = (int) carry;
357 zds[j] += (int)carry;
365 /** Number of digits in the conversion base that always fits in a word.
366 * For example, for base 10 this is 9, since 10**9 is the
367 * largest number that fits into a words (assuming 32-bit words).
368 * This is the same as gmp's __mp_bases[radix].chars_per_limb.
369 * @param radix the base
370 * @return number of digits */
371 public static int chars_per_word (int radix)
391 else if (radix <= 16)
393 else if (radix <= 23)
395 else if (radix <= 40)
397 // The following are conservative, but we don't care.
398 else if (radix <= 256)
404 /** Count the number of leading zero bits in an int. */
405 public static int count_leading_zeros (int i)
410 for (int k = 16; k > 0; k = k >> 1) {
420 public static int set_str (int dest[], byte[] str, int str_len, int base)
423 if ((base & (base - 1)) == 0)
425 // The base is a power of 2. Read the input string from
426 // least to most significant character/digit. */
429 int bits_per_indigit = 0;
430 for (int i = base; (i >>= 1) != 0; ) bits_per_indigit++;
433 for (int i = str_len; --i >= 0; )
435 int inp_digit = str[i];
436 res_digit |= inp_digit << next_bitpos;
437 next_bitpos += bits_per_indigit;
438 if (next_bitpos >= 32)
440 dest[size++] = res_digit;
442 res_digit = inp_digit >> (bits_per_indigit - next_bitpos);
447 dest[size++] = res_digit;
451 // General case. The base is not a power of 2.
452 int indigits_per_limb = MPN.chars_per_word (base);
455 while (str_pos < str_len)
457 int chunk = str_len - str_pos;
458 if (chunk > indigits_per_limb)
459 chunk = indigits_per_limb;
460 int res_digit = str[str_pos++];
465 res_digit = res_digit * base + str[str_pos++];
474 cy_limb = MPN.mul_1 (dest, dest, size, big_base);
475 cy_limb += MPN.add_1 (dest, dest, size, res_digit);
478 dest[size++] = cy_limb;
484 /** Compare x[0:size-1] with y[0:size-1], treating them as unsigned integers.
485 * @result -1, 0, or 1 depending on if x<y, x==y, or x>y.
486 * This is basically the same as gmp's mpn_cmp function.
488 public static int cmp (int[] x, int[] y, int size)
492 int x_word = x[size];
493 int y_word = y[size];
494 if (x_word != y_word)
496 // Invert the high-order bit, because:
497 // (unsigned) X > (unsigned) Y iff
498 // (int) (X^0x80000000) > (int) (Y^0x80000000).
499 return (x_word ^ 0x80000000) > (y_word ^0x80000000) ? 1 : -1;
506 * Compare x[0:xlen-1] with y[0:ylen-1], treating them as unsigned integers.
508 * @return -1, 0, or 1 depending on if x<y, x==y, or x>y.
510 public static int cmp (int[] x, int xlen, int[] y, int ylen)
512 return xlen > ylen ? 1 : xlen < ylen ? -1 : cmp (x, y, xlen);
516 * Shift x[x_start:x_start+len-1] count bits to the "right"
517 * (i.e. divide by 2**count).
518 * Store the len least significant words of the result at dest.
519 * The bits shifted out to the right are returned.
521 * Assumes: 0 < count < 32
523 public static int rshift (int[] dest, int[] x, int x_start,
526 int count_2 = 32 - count;
527 int low_word = x[x_start];
528 int retval = low_word << count_2;
532 int high_word = x[x_start+i];
533 dest[i-1] = (low_word >>> count) | (high_word << count_2);
534 low_word = high_word;
536 dest[i-1] = low_word >>> count;
541 * Shift x[x_start:x_start+len-1] count bits to the "right"
542 * (i.e. divide by 2**count).
543 * Store the len least significant words of the result at dest.
545 * Assumes: 0 <= count < 32
546 * Same as rshift, but handles count==0 (and has no return value).
548 public static void rshift0 (int[] dest, int[] x, int x_start,
552 rshift(dest, x, x_start, len, count);
554 for (int i = 0; i < len; i++)
555 dest[i] = x[i + x_start];
558 /** Return the long-truncated value of right shifting.
559 * @param x a two's-complement "bignum"
560 * @param len the number of significant words in x
561 * @param count the shift count
562 * @return (long)(x[0..len-1] >> count).
564 public static long rshift_long (int[] x, int len, int count)
566 int wordno = count >> 5;
568 int sign = x[len-1] < 0 ? -1 : 0;
569 int w0 = wordno >= len ? sign : x[wordno];
571 int w1 = wordno >= len ? sign : x[wordno];
575 int w2 = wordno >= len ? sign : x[wordno];
576 w0 = (w0 >>> count) | (w1 << (32-count));
577 w1 = (w1 >>> count) | (w2 << (32-count));
579 return ((long)w1 << 32) | ((long)w0 & 0xffffffffL);
582 /* Shift x[0:len-1] left by count bits, and store the len least
583 * significant words of the result in dest[d_offset:d_offset+len-1].
584 * Return the bits shifted out from the most significant digit.
585 * Assumes 0 < count < 32.
589 public static int lshift (int[] dest, int d_offset,
590 int[] x, int len, int count)
592 int count_2 = 32 - count;
594 int high_word = x[i];
595 int retval = high_word >>> count_2;
600 dest[d_offset+i] = (high_word << count) | (low_word >>> count_2);
601 high_word = low_word;
603 dest[d_offset+i] = high_word << count;
607 /** Return least i such that word & (1<<i). Assumes word!=0. */
609 public static int findLowestBit (int word)
612 while ((word & 0xF) == 0)
627 /** Return least i such that words & (1<<i). Assumes there is such an i. */
629 public static int findLowestBit (int[] words)
631 for (int i = 0; ; i++)
634 return 32 * i + findLowestBit (words[i]);
638 /** Calculate Greatest Common Divisior of x[0:len-1] and y[0:len-1].
639 * Assumes both arguments are non-zero.
640 * Leaves result in x, and returns len of result.
641 * Also destroys y (actually sets it to a copy of the result). */
643 public static int gcd (int[] x, int[] y, int len)
646 // Find sh such that both x and y are divisible by 2**sh.
652 // Must terminate, since x and y are non-zero.
656 int initShiftWords = i;
657 int initShiftBits = findLowestBit (word);
658 // Logically: sh = initShiftWords * 32 + initShiftBits
660 // Temporarily devide both x and y by 2**sh.
661 len -= initShiftWords;
662 MPN.rshift0 (x, x, initShiftWords, len, initShiftBits);
663 MPN.rshift0 (y, y, initShiftWords, len, initShiftBits);
665 int[] odd_arg; /* One of x or y which is odd. */
666 int[] other_arg; /* The other one can be even or odd. */
680 // Shift other_arg until it is odd; this doesn't
681 // affect the gcd, since we divide by 2**k, which does not
683 for (i = 0; other_arg[i] == 0; ) i++;
687 for (j = 0; j < len-i; j++)
688 other_arg[j] = other_arg[j+i];
689 for ( ; j < len; j++)
692 i = findLowestBit(other_arg[0]);
694 MPN.rshift (other_arg, other_arg, 0, len, i);
696 // Now both odd_arg and other_arg are odd.
698 // Subtract the smaller from the larger.
699 // This does not change the result, since gcd(a-b,b)==gcd(a,b).
700 i = MPN.cmp(odd_arg, other_arg, len);
704 { // odd_arg > other_arg
705 MPN.sub_n (odd_arg, odd_arg, other_arg, len);
706 // Now odd_arg is even, so swap with other_arg;
707 int[] tmp = odd_arg; odd_arg = other_arg; other_arg = tmp;
710 { // other_arg > odd_arg
711 MPN.sub_n (other_arg, other_arg, odd_arg, len);
713 while (odd_arg[len-1] == 0 && other_arg[len-1] == 0)
716 if (initShiftWords + initShiftBits > 0)
718 if (initShiftBits > 0)
720 int sh_out = MPN.lshift (x, initShiftWords, x, len, initShiftBits);
722 x[(len++)+initShiftWords] = sh_out;
726 for (i = len; --i >= 0;)
727 x[i+initShiftWords] = x[i];
729 for (i = initShiftWords; --i >= 0; )
731 len += initShiftWords;
736 public static int intLength (int i)
738 return 32 - count_leading_zeros (i < 0 ? ~i : i);
741 /** Calcaulte the Common Lisp "integer-length" function.
742 * Assumes input is canonicalized: len==BigInteger.wordsNeeded(words,len) */
743 public static int intLength (int[] words, int len)
746 return intLength (words[len]) + 32 * len;
750 public static void dprint (BigInteger x)
753 System.err.print(Long.toString((long) x.ival & 0xffffffffL, 16));
755 dprint (System.err, x.words, x.ival);
757 public static void dprint (int[] x) { dprint (System.err, x, x.length); }
758 public static void dprint (int[] x, int len) { dprint (System.err, x, len); }
759 public static void dprint (java.io.PrintStream ps, int[] x, int len)
762 for (int i = 0; i < len; i++)
766 ps.print ("#x" + Long.toString ((long) x[i] & 0xffffffffL, 16));