github.com/q45/go@v0.0.0-20151101211701-a4fb8c13db3f/src/cmd/compile/internal/big/int.go (about)

     1  // Copyright 2009 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  // This file implements signed multi-precision integers.
     6  
     7  package big
     8  
     9  import (
    10  	"fmt"
    11  	"io"
    12  	"math/rand"
    13  	"strings"
    14  )
    15  
    16  // An Int represents a signed multi-precision integer.
    17  // The zero value for an Int represents the value 0.
    18  type Int struct {
    19  	neg bool // sign
    20  	abs nat  // absolute value of the integer
    21  }
    22  
    23  var intOne = &Int{false, natOne}
    24  
    25  // Sign returns:
    26  //
    27  //	-1 if x <  0
    28  //	 0 if x == 0
    29  //	+1 if x >  0
    30  //
    31  func (x *Int) Sign() int {
    32  	if len(x.abs) == 0 {
    33  		return 0
    34  	}
    35  	if x.neg {
    36  		return -1
    37  	}
    38  	return 1
    39  }
    40  
    41  // SetInt64 sets z to x and returns z.
    42  func (z *Int) SetInt64(x int64) *Int {
    43  	neg := false
    44  	if x < 0 {
    45  		neg = true
    46  		x = -x
    47  	}
    48  	z.abs = z.abs.setUint64(uint64(x))
    49  	z.neg = neg
    50  	return z
    51  }
    52  
    53  // SetUint64 sets z to x and returns z.
    54  func (z *Int) SetUint64(x uint64) *Int {
    55  	z.abs = z.abs.setUint64(x)
    56  	z.neg = false
    57  	return z
    58  }
    59  
    60  // NewInt allocates and returns a new Int set to x.
    61  func NewInt(x int64) *Int {
    62  	return new(Int).SetInt64(x)
    63  }
    64  
    65  // Set sets z to x and returns z.
    66  func (z *Int) Set(x *Int) *Int {
    67  	if z != x {
    68  		z.abs = z.abs.set(x.abs)
    69  		z.neg = x.neg
    70  	}
    71  	return z
    72  }
    73  
    74  // Bits provides raw (unchecked but fast) access to x by returning its
    75  // absolute value as a little-endian Word slice. The result and x share
    76  // the same underlying array.
    77  // Bits is intended to support implementation of missing low-level Int
    78  // functionality outside this package; it should be avoided otherwise.
    79  func (x *Int) Bits() []Word {
    80  	return x.abs
    81  }
    82  
    83  // SetBits provides raw (unchecked but fast) access to z by setting its
    84  // value to abs, interpreted as a little-endian Word slice, and returning
    85  // z. The result and abs share the same underlying array.
    86  // SetBits is intended to support implementation of missing low-level Int
    87  // functionality outside this package; it should be avoided otherwise.
    88  func (z *Int) SetBits(abs []Word) *Int {
    89  	z.abs = nat(abs).norm()
    90  	z.neg = false
    91  	return z
    92  }
    93  
    94  // Abs sets z to |x| (the absolute value of x) and returns z.
    95  func (z *Int) Abs(x *Int) *Int {
    96  	z.Set(x)
    97  	z.neg = false
    98  	return z
    99  }
   100  
   101  // Neg sets z to -x and returns z.
   102  func (z *Int) Neg(x *Int) *Int {
   103  	z.Set(x)
   104  	z.neg = len(z.abs) > 0 && !z.neg // 0 has no sign
   105  	return z
   106  }
   107  
   108  // Add sets z to the sum x+y and returns z.
   109  func (z *Int) Add(x, y *Int) *Int {
   110  	neg := x.neg
   111  	if x.neg == y.neg {
   112  		// x + y == x + y
   113  		// (-x) + (-y) == -(x + y)
   114  		z.abs = z.abs.add(x.abs, y.abs)
   115  	} else {
   116  		// x + (-y) == x - y == -(y - x)
   117  		// (-x) + y == y - x == -(x - y)
   118  		if x.abs.cmp(y.abs) >= 0 {
   119  			z.abs = z.abs.sub(x.abs, y.abs)
   120  		} else {
   121  			neg = !neg
   122  			z.abs = z.abs.sub(y.abs, x.abs)
   123  		}
   124  	}
   125  	z.neg = len(z.abs) > 0 && neg // 0 has no sign
   126  	return z
   127  }
   128  
   129  // Sub sets z to the difference x-y and returns z.
   130  func (z *Int) Sub(x, y *Int) *Int {
   131  	neg := x.neg
   132  	if x.neg != y.neg {
   133  		// x - (-y) == x + y
   134  		// (-x) - y == -(x + y)
   135  		z.abs = z.abs.add(x.abs, y.abs)
   136  	} else {
   137  		// x - y == x - y == -(y - x)
   138  		// (-x) - (-y) == y - x == -(x - y)
   139  		if x.abs.cmp(y.abs) >= 0 {
   140  			z.abs = z.abs.sub(x.abs, y.abs)
   141  		} else {
   142  			neg = !neg
   143  			z.abs = z.abs.sub(y.abs, x.abs)
   144  		}
   145  	}
   146  	z.neg = len(z.abs) > 0 && neg // 0 has no sign
   147  	return z
   148  }
   149  
   150  // Mul sets z to the product x*y and returns z.
   151  func (z *Int) Mul(x, y *Int) *Int {
   152  	// x * y == x * y
   153  	// x * (-y) == -(x * y)
   154  	// (-x) * y == -(x * y)
   155  	// (-x) * (-y) == x * y
   156  	z.abs = z.abs.mul(x.abs, y.abs)
   157  	z.neg = len(z.abs) > 0 && x.neg != y.neg // 0 has no sign
   158  	return z
   159  }
   160  
   161  // MulRange sets z to the product of all integers
   162  // in the range [a, b] inclusively and returns z.
   163  // If a > b (empty range), the result is 1.
   164  func (z *Int) MulRange(a, b int64) *Int {
   165  	switch {
   166  	case a > b:
   167  		return z.SetInt64(1) // empty range
   168  	case a <= 0 && b >= 0:
   169  		return z.SetInt64(0) // range includes 0
   170  	}
   171  	// a <= b && (b < 0 || a > 0)
   172  
   173  	neg := false
   174  	if a < 0 {
   175  		neg = (b-a)&1 == 0
   176  		a, b = -b, -a
   177  	}
   178  
   179  	z.abs = z.abs.mulRange(uint64(a), uint64(b))
   180  	z.neg = neg
   181  	return z
   182  }
   183  
   184  // Binomial sets z to the binomial coefficient of (n, k) and returns z.
   185  func (z *Int) Binomial(n, k int64) *Int {
   186  	// reduce the number of multiplications by reducing k
   187  	if n/2 < k && k <= n {
   188  		k = n - k // Binomial(n, k) == Binomial(n, n-k)
   189  	}
   190  	var a, b Int
   191  	a.MulRange(n-k+1, n)
   192  	b.MulRange(1, k)
   193  	return z.Quo(&a, &b)
   194  }
   195  
   196  // Quo sets z to the quotient x/y for y != 0 and returns z.
   197  // If y == 0, a division-by-zero run-time panic occurs.
   198  // Quo implements truncated division (like Go); see QuoRem for more details.
   199  func (z *Int) Quo(x, y *Int) *Int {
   200  	z.abs, _ = z.abs.div(nil, x.abs, y.abs)
   201  	z.neg = len(z.abs) > 0 && x.neg != y.neg // 0 has no sign
   202  	return z
   203  }
   204  
   205  // Rem sets z to the remainder x%y for y != 0 and returns z.
   206  // If y == 0, a division-by-zero run-time panic occurs.
   207  // Rem implements truncated modulus (like Go); see QuoRem for more details.
   208  func (z *Int) Rem(x, y *Int) *Int {
   209  	_, z.abs = nat(nil).div(z.abs, x.abs, y.abs)
   210  	z.neg = len(z.abs) > 0 && x.neg // 0 has no sign
   211  	return z
   212  }
   213  
   214  // QuoRem sets z to the quotient x/y and r to the remainder x%y
   215  // and returns the pair (z, r) for y != 0.
   216  // If y == 0, a division-by-zero run-time panic occurs.
   217  //
   218  // QuoRem implements T-division and modulus (like Go):
   219  //
   220  //	q = x/y      with the result truncated to zero
   221  //	r = x - y*q
   222  //
   223  // (See Daan Leijen, ``Division and Modulus for Computer Scientists''.)
   224  // See DivMod for Euclidean division and modulus (unlike Go).
   225  //
   226  func (z *Int) QuoRem(x, y, r *Int) (*Int, *Int) {
   227  	z.abs, r.abs = z.abs.div(r.abs, x.abs, y.abs)
   228  	z.neg, r.neg = len(z.abs) > 0 && x.neg != y.neg, len(r.abs) > 0 && x.neg // 0 has no sign
   229  	return z, r
   230  }
   231  
   232  // Div sets z to the quotient x/y for y != 0 and returns z.
   233  // If y == 0, a division-by-zero run-time panic occurs.
   234  // Div implements Euclidean division (unlike Go); see DivMod for more details.
   235  func (z *Int) Div(x, y *Int) *Int {
   236  	y_neg := y.neg // z may be an alias for y
   237  	var r Int
   238  	z.QuoRem(x, y, &r)
   239  	if r.neg {
   240  		if y_neg {
   241  			z.Add(z, intOne)
   242  		} else {
   243  			z.Sub(z, intOne)
   244  		}
   245  	}
   246  	return z
   247  }
   248  
   249  // Mod sets z to the modulus x%y for y != 0 and returns z.
   250  // If y == 0, a division-by-zero run-time panic occurs.
   251  // Mod implements Euclidean modulus (unlike Go); see DivMod for more details.
   252  func (z *Int) Mod(x, y *Int) *Int {
   253  	y0 := y // save y
   254  	if z == y || alias(z.abs, y.abs) {
   255  		y0 = new(Int).Set(y)
   256  	}
   257  	var q Int
   258  	q.QuoRem(x, y, z)
   259  	if z.neg {
   260  		if y0.neg {
   261  			z.Sub(z, y0)
   262  		} else {
   263  			z.Add(z, y0)
   264  		}
   265  	}
   266  	return z
   267  }
   268  
   269  // DivMod sets z to the quotient x div y and m to the modulus x mod y
   270  // and returns the pair (z, m) for y != 0.
   271  // If y == 0, a division-by-zero run-time panic occurs.
   272  //
   273  // DivMod implements Euclidean division and modulus (unlike Go):
   274  //
   275  //	q = x div y  such that
   276  //	m = x - y*q  with 0 <= m < |q|
   277  //
   278  // (See Raymond T. Boute, ``The Euclidean definition of the functions
   279  // div and mod''. ACM Transactions on Programming Languages and
   280  // Systems (TOPLAS), 14(2):127-144, New York, NY, USA, 4/1992.
   281  // ACM press.)
   282  // See QuoRem for T-division and modulus (like Go).
   283  //
   284  func (z *Int) DivMod(x, y, m *Int) (*Int, *Int) {
   285  	y0 := y // save y
   286  	if z == y || alias(z.abs, y.abs) {
   287  		y0 = new(Int).Set(y)
   288  	}
   289  	z.QuoRem(x, y, m)
   290  	if m.neg {
   291  		if y0.neg {
   292  			z.Add(z, intOne)
   293  			m.Sub(m, y0)
   294  		} else {
   295  			z.Sub(z, intOne)
   296  			m.Add(m, y0)
   297  		}
   298  	}
   299  	return z, m
   300  }
   301  
   302  // Cmp compares x and y and returns:
   303  //
   304  //   -1 if x <  y
   305  //    0 if x == y
   306  //   +1 if x >  y
   307  //
   308  func (x *Int) Cmp(y *Int) (r int) {
   309  	// x cmp y == x cmp y
   310  	// x cmp (-y) == x
   311  	// (-x) cmp y == y
   312  	// (-x) cmp (-y) == -(x cmp y)
   313  	switch {
   314  	case x.neg == y.neg:
   315  		r = x.abs.cmp(y.abs)
   316  		if x.neg {
   317  			r = -r
   318  		}
   319  	case x.neg:
   320  		r = -1
   321  	default:
   322  		r = 1
   323  	}
   324  	return
   325  }
   326  
   327  // low32 returns the least significant 32 bits of z.
   328  func low32(z nat) uint32 {
   329  	if len(z) == 0 {
   330  		return 0
   331  	}
   332  	return uint32(z[0])
   333  }
   334  
   335  // low64 returns the least significant 64 bits of z.
   336  func low64(z nat) uint64 {
   337  	if len(z) == 0 {
   338  		return 0
   339  	}
   340  	v := uint64(z[0])
   341  	if _W == 32 && len(z) > 1 {
   342  		v |= uint64(z[1]) << 32
   343  	}
   344  	return v
   345  }
   346  
   347  // Int64 returns the int64 representation of x.
   348  // If x cannot be represented in an int64, the result is undefined.
   349  func (x *Int) Int64() int64 {
   350  	v := int64(low64(x.abs))
   351  	if x.neg {
   352  		v = -v
   353  	}
   354  	return v
   355  }
   356  
   357  // Uint64 returns the uint64 representation of x.
   358  // If x cannot be represented in a uint64, the result is undefined.
   359  func (x *Int) Uint64() uint64 {
   360  	return low64(x.abs)
   361  }
   362  
   363  // SetString sets z to the value of s, interpreted in the given base,
   364  // and returns z and a boolean indicating success. If SetString fails,
   365  // the value of z is undefined but the returned value is nil.
   366  //
   367  // The base argument must be 0 or a value between 2 and MaxBase. If the base
   368  // is 0, the string prefix determines the actual conversion base. A prefix of
   369  // ``0x'' or ``0X'' selects base 16; the ``0'' prefix selects base 8, and a
   370  // ``0b'' or ``0B'' prefix selects base 2. Otherwise the selected base is 10.
   371  //
   372  func (z *Int) SetString(s string, base int) (*Int, bool) {
   373  	r := strings.NewReader(s)
   374  	_, _, err := z.scan(r, base)
   375  	if err != nil {
   376  		return nil, false
   377  	}
   378  	_, err = r.ReadByte()
   379  	if err != io.EOF {
   380  		return nil, false
   381  	}
   382  	return z, true // err == io.EOF => scan consumed all of s
   383  }
   384  
   385  // SetBytes interprets buf as the bytes of a big-endian unsigned
   386  // integer, sets z to that value, and returns z.
   387  func (z *Int) SetBytes(buf []byte) *Int {
   388  	z.abs = z.abs.setBytes(buf)
   389  	z.neg = false
   390  	return z
   391  }
   392  
   393  // Bytes returns the absolute value of x as a big-endian byte slice.
   394  func (x *Int) Bytes() []byte {
   395  	buf := make([]byte, len(x.abs)*_S)
   396  	return buf[x.abs.bytes(buf):]
   397  }
   398  
   399  // BitLen returns the length of the absolute value of x in bits.
   400  // The bit length of 0 is 0.
   401  func (x *Int) BitLen() int {
   402  	return x.abs.bitLen()
   403  }
   404  
   405  // Exp sets z = x**y mod |m| (i.e. the sign of m is ignored), and returns z.
   406  // If y <= 0, the result is 1 mod |m|; if m == nil or m == 0, z = x**y.
   407  // See Knuth, volume 2, section 4.6.3.
   408  func (z *Int) Exp(x, y, m *Int) *Int {
   409  	var yWords nat
   410  	if !y.neg {
   411  		yWords = y.abs
   412  	}
   413  	// y >= 0
   414  
   415  	var mWords nat
   416  	if m != nil {
   417  		mWords = m.abs // m.abs may be nil for m == 0
   418  	}
   419  
   420  	z.abs = z.abs.expNN(x.abs, yWords, mWords)
   421  	z.neg = len(z.abs) > 0 && x.neg && len(yWords) > 0 && yWords[0]&1 == 1 // 0 has no sign
   422  	if z.neg && len(mWords) > 0 {
   423  		// make modulus result positive
   424  		z.abs = z.abs.sub(mWords, z.abs) // z == x**y mod |m| && 0 <= z < |m|
   425  		z.neg = false
   426  	}
   427  
   428  	return z
   429  }
   430  
   431  // GCD sets z to the greatest common divisor of a and b, which both must
   432  // be > 0, and returns z.
   433  // If x and y are not nil, GCD sets x and y such that z = a*x + b*y.
   434  // If either a or b is <= 0, GCD sets z = x = y = 0.
   435  func (z *Int) GCD(x, y, a, b *Int) *Int {
   436  	if a.Sign() <= 0 || b.Sign() <= 0 {
   437  		z.SetInt64(0)
   438  		if x != nil {
   439  			x.SetInt64(0)
   440  		}
   441  		if y != nil {
   442  			y.SetInt64(0)
   443  		}
   444  		return z
   445  	}
   446  	if x == nil && y == nil {
   447  		return z.binaryGCD(a, b)
   448  	}
   449  
   450  	A := new(Int).Set(a)
   451  	B := new(Int).Set(b)
   452  
   453  	X := new(Int)
   454  	Y := new(Int).SetInt64(1)
   455  
   456  	lastX := new(Int).SetInt64(1)
   457  	lastY := new(Int)
   458  
   459  	q := new(Int)
   460  	temp := new(Int)
   461  
   462  	for len(B.abs) > 0 {
   463  		r := new(Int)
   464  		q, r = q.QuoRem(A, B, r)
   465  
   466  		A, B = B, r
   467  
   468  		temp.Set(X)
   469  		X.Mul(X, q)
   470  		X.neg = !X.neg
   471  		X.Add(X, lastX)
   472  		lastX.Set(temp)
   473  
   474  		temp.Set(Y)
   475  		Y.Mul(Y, q)
   476  		Y.neg = !Y.neg
   477  		Y.Add(Y, lastY)
   478  		lastY.Set(temp)
   479  	}
   480  
   481  	if x != nil {
   482  		*x = *lastX
   483  	}
   484  
   485  	if y != nil {
   486  		*y = *lastY
   487  	}
   488  
   489  	*z = *A
   490  	return z
   491  }
   492  
   493  // binaryGCD sets z to the greatest common divisor of a and b, which both must
   494  // be > 0, and returns z.
   495  // See Knuth, The Art of Computer Programming, Vol. 2, Section 4.5.2, Algorithm B.
   496  func (z *Int) binaryGCD(a, b *Int) *Int {
   497  	u := z
   498  	v := new(Int)
   499  
   500  	// use one Euclidean iteration to ensure that u and v are approx. the same size
   501  	switch {
   502  	case len(a.abs) > len(b.abs):
   503  		// must set v before u since u may be alias for a or b (was issue #11284)
   504  		v.Rem(a, b)
   505  		u.Set(b)
   506  	case len(a.abs) < len(b.abs):
   507  		v.Rem(b, a)
   508  		u.Set(a)
   509  	default:
   510  		v.Set(b)
   511  		u.Set(a)
   512  	}
   513  	// a, b must not be used anymore (may be aliases with u)
   514  
   515  	// v might be 0 now
   516  	if len(v.abs) == 0 {
   517  		return u
   518  	}
   519  	// u > 0 && v > 0
   520  
   521  	// determine largest k such that u = u' << k, v = v' << k
   522  	k := u.abs.trailingZeroBits()
   523  	if vk := v.abs.trailingZeroBits(); vk < k {
   524  		k = vk
   525  	}
   526  	u.Rsh(u, k)
   527  	v.Rsh(v, k)
   528  
   529  	// determine t (we know that u > 0)
   530  	t := new(Int)
   531  	if u.abs[0]&1 != 0 {
   532  		// u is odd
   533  		t.Neg(v)
   534  	} else {
   535  		t.Set(u)
   536  	}
   537  
   538  	for len(t.abs) > 0 {
   539  		// reduce t
   540  		t.Rsh(t, t.abs.trailingZeroBits())
   541  		if t.neg {
   542  			v, t = t, v
   543  			v.neg = len(v.abs) > 0 && !v.neg // 0 has no sign
   544  		} else {
   545  			u, t = t, u
   546  		}
   547  		t.Sub(u, v)
   548  	}
   549  
   550  	return z.Lsh(u, k)
   551  }
   552  
   553  // ProbablyPrime performs n Miller-Rabin tests to check whether x is prime.
   554  // If it returns true, x is prime with probability 1 - 1/4^n.
   555  // If it returns false, x is not prime. n must be > 0.
   556  func (x *Int) ProbablyPrime(n int) bool {
   557  	if n <= 0 {
   558  		panic("non-positive n for ProbablyPrime")
   559  	}
   560  	return !x.neg && x.abs.probablyPrime(n)
   561  }
   562  
   563  // Rand sets z to a pseudo-random number in [0, n) and returns z.
   564  func (z *Int) Rand(rnd *rand.Rand, n *Int) *Int {
   565  	z.neg = false
   566  	if n.neg == true || len(n.abs) == 0 {
   567  		z.abs = nil
   568  		return z
   569  	}
   570  	z.abs = z.abs.random(rnd, n.abs, n.abs.bitLen())
   571  	return z
   572  }
   573  
   574  // ModInverse sets z to the multiplicative inverse of g in the ring ℤ/nℤ
   575  // and returns z. If g and n are not relatively prime, the result is undefined.
   576  func (z *Int) ModInverse(g, n *Int) *Int {
   577  	var d Int
   578  	d.GCD(z, nil, g, n)
   579  	// x and y are such that g*x + n*y = d. Since g and n are
   580  	// relatively prime, d = 1. Taking that modulo n results in
   581  	// g*x = 1, therefore x is the inverse element.
   582  	if z.neg {
   583  		z.Add(z, n)
   584  	}
   585  	return z
   586  }
   587  
   588  // Jacobi returns the Jacobi symbol (x/y), either +1, -1, or 0.
   589  // The y argument must be an odd integer.
   590  func Jacobi(x, y *Int) int {
   591  	if len(y.abs) == 0 || y.abs[0]&1 == 0 {
   592  		panic(fmt.Sprintf("big: invalid 2nd argument to Int.Jacobi: need odd integer but got %s", y))
   593  	}
   594  
   595  	// We use the formulation described in chapter 2, section 2.4,
   596  	// "The Yacas Book of Algorithms":
   597  	// http://yacas.sourceforge.net/Algo.book.pdf
   598  
   599  	var a, b, c Int
   600  	a.Set(x)
   601  	b.Set(y)
   602  	j := 1
   603  
   604  	if b.neg {
   605  		if a.neg {
   606  			j = -1
   607  		}
   608  		b.neg = false
   609  	}
   610  
   611  	for {
   612  		if b.Cmp(intOne) == 0 {
   613  			return j
   614  		}
   615  		if len(a.abs) == 0 {
   616  			return 0
   617  		}
   618  		a.Mod(&a, &b)
   619  		if len(a.abs) == 0 {
   620  			return 0
   621  		}
   622  		// a > 0
   623  
   624  		// handle factors of 2 in 'a'
   625  		s := a.abs.trailingZeroBits()
   626  		if s&1 != 0 {
   627  			bmod8 := b.abs[0] & 7
   628  			if bmod8 == 3 || bmod8 == 5 {
   629  				j = -j
   630  			}
   631  		}
   632  		c.Rsh(&a, s) // a = 2^s*c
   633  
   634  		// swap numerator and denominator
   635  		if b.abs[0]&3 == 3 && c.abs[0]&3 == 3 {
   636  			j = -j
   637  		}
   638  		a.Set(&b)
   639  		b.Set(&c)
   640  	}
   641  }
   642  
   643  // ModSqrt sets z to a square root of x mod p if such a square root exists, and
   644  // returns z. The modulus p must be an odd prime. If x is not a square mod p,
   645  // ModSqrt leaves z unchanged and returns nil. This function panics if p is
   646  // not an odd integer.
   647  func (z *Int) ModSqrt(x, p *Int) *Int {
   648  	switch Jacobi(x, p) {
   649  	case -1:
   650  		return nil // x is not a square mod p
   651  	case 0:
   652  		return z.SetInt64(0) // sqrt(0) mod p = 0
   653  	case 1:
   654  		break
   655  	}
   656  	if x.neg || x.Cmp(p) >= 0 { // ensure 0 <= x < p
   657  		x = new(Int).Mod(x, p)
   658  	}
   659  
   660  	// Break p-1 into s*2^e such that s is odd.
   661  	var s Int
   662  	s.Sub(p, intOne)
   663  	e := s.abs.trailingZeroBits()
   664  	s.Rsh(&s, e)
   665  
   666  	// find some non-square n
   667  	var n Int
   668  	n.SetInt64(2)
   669  	for Jacobi(&n, p) != -1 {
   670  		n.Add(&n, intOne)
   671  	}
   672  
   673  	// Core of the Tonelli-Shanks algorithm. Follows the description in
   674  	// section 6 of "Square roots from 1; 24, 51, 10 to Dan Shanks" by Ezra
   675  	// Brown:
   676  	// https://www.maa.org/sites/default/files/pdf/upload_library/22/Polya/07468342.di020786.02p0470a.pdf
   677  	var y, b, g, t Int
   678  	y.Add(&s, intOne)
   679  	y.Rsh(&y, 1)
   680  	y.Exp(x, &y, p)  // y = x^((s+1)/2)
   681  	b.Exp(x, &s, p)  // b = x^s
   682  	g.Exp(&n, &s, p) // g = n^s
   683  	r := e
   684  	for {
   685  		// find the least m such that ord_p(b) = 2^m
   686  		var m uint
   687  		t.Set(&b)
   688  		for t.Cmp(intOne) != 0 {
   689  			t.Mul(&t, &t).Mod(&t, p)
   690  			m++
   691  		}
   692  
   693  		if m == 0 {
   694  			return z.Set(&y)
   695  		}
   696  
   697  		t.SetInt64(0).SetBit(&t, int(r-m-1), 1).Exp(&g, &t, p)
   698  		// t = g^(2^(r-m-1)) mod p
   699  		g.Mul(&t, &t).Mod(&g, p) // g = g^(2^(r-m)) mod p
   700  		y.Mul(&y, &t).Mod(&y, p)
   701  		b.Mul(&b, &g).Mod(&b, p)
   702  		r = m
   703  	}
   704  }
   705  
   706  // Lsh sets z = x << n and returns z.
   707  func (z *Int) Lsh(x *Int, n uint) *Int {
   708  	z.abs = z.abs.shl(x.abs, n)
   709  	z.neg = x.neg
   710  	return z
   711  }
   712  
   713  // Rsh sets z = x >> n and returns z.
   714  func (z *Int) Rsh(x *Int, n uint) *Int {
   715  	if x.neg {
   716  		// (-x) >> s == ^(x-1) >> s == ^((x-1) >> s) == -(((x-1) >> s) + 1)
   717  		t := z.abs.sub(x.abs, natOne) // no underflow because |x| > 0
   718  		t = t.shr(t, n)
   719  		z.abs = t.add(t, natOne)
   720  		z.neg = true // z cannot be zero if x is negative
   721  		return z
   722  	}
   723  
   724  	z.abs = z.abs.shr(x.abs, n)
   725  	z.neg = false
   726  	return z
   727  }
   728  
   729  // Bit returns the value of the i'th bit of x. That is, it
   730  // returns (x>>i)&1. The bit index i must be >= 0.
   731  func (x *Int) Bit(i int) uint {
   732  	if i == 0 {
   733  		// optimization for common case: odd/even test of x
   734  		if len(x.abs) > 0 {
   735  			return uint(x.abs[0] & 1) // bit 0 is same for -x
   736  		}
   737  		return 0
   738  	}
   739  	if i < 0 {
   740  		panic("negative bit index")
   741  	}
   742  	if x.neg {
   743  		t := nat(nil).sub(x.abs, natOne)
   744  		return t.bit(uint(i)) ^ 1
   745  	}
   746  
   747  	return x.abs.bit(uint(i))
   748  }
   749  
   750  // SetBit sets z to x, with x's i'th bit set to b (0 or 1).
   751  // That is, if b is 1 SetBit sets z = x | (1 << i);
   752  // if b is 0 SetBit sets z = x &^ (1 << i). If b is not 0 or 1,
   753  // SetBit will panic.
   754  func (z *Int) SetBit(x *Int, i int, b uint) *Int {
   755  	if i < 0 {
   756  		panic("negative bit index")
   757  	}
   758  	if x.neg {
   759  		t := z.abs.sub(x.abs, natOne)
   760  		t = t.setBit(t, uint(i), b^1)
   761  		z.abs = t.add(t, natOne)
   762  		z.neg = len(z.abs) > 0
   763  		return z
   764  	}
   765  	z.abs = z.abs.setBit(x.abs, uint(i), b)
   766  	z.neg = false
   767  	return z
   768  }
   769  
   770  // And sets z = x & y and returns z.
   771  func (z *Int) And(x, y *Int) *Int {
   772  	if x.neg == y.neg {
   773  		if x.neg {
   774  			// (-x) & (-y) == ^(x-1) & ^(y-1) == ^((x-1) | (y-1)) == -(((x-1) | (y-1)) + 1)
   775  			x1 := nat(nil).sub(x.abs, natOne)
   776  			y1 := nat(nil).sub(y.abs, natOne)
   777  			z.abs = z.abs.add(z.abs.or(x1, y1), natOne)
   778  			z.neg = true // z cannot be zero if x and y are negative
   779  			return z
   780  		}
   781  
   782  		// x & y == x & y
   783  		z.abs = z.abs.and(x.abs, y.abs)
   784  		z.neg = false
   785  		return z
   786  	}
   787  
   788  	// x.neg != y.neg
   789  	if x.neg {
   790  		x, y = y, x // & is symmetric
   791  	}
   792  
   793  	// x & (-y) == x & ^(y-1) == x &^ (y-1)
   794  	y1 := nat(nil).sub(y.abs, natOne)
   795  	z.abs = z.abs.andNot(x.abs, y1)
   796  	z.neg = false
   797  	return z
   798  }
   799  
   800  // AndNot sets z = x &^ y and returns z.
   801  func (z *Int) AndNot(x, y *Int) *Int {
   802  	if x.neg == y.neg {
   803  		if x.neg {
   804  			// (-x) &^ (-y) == ^(x-1) &^ ^(y-1) == ^(x-1) & (y-1) == (y-1) &^ (x-1)
   805  			x1 := nat(nil).sub(x.abs, natOne)
   806  			y1 := nat(nil).sub(y.abs, natOne)
   807  			z.abs = z.abs.andNot(y1, x1)
   808  			z.neg = false
   809  			return z
   810  		}
   811  
   812  		// x &^ y == x &^ y
   813  		z.abs = z.abs.andNot(x.abs, y.abs)
   814  		z.neg = false
   815  		return z
   816  	}
   817  
   818  	if x.neg {
   819  		// (-x) &^ y == ^(x-1) &^ y == ^(x-1) & ^y == ^((x-1) | y) == -(((x-1) | y) + 1)
   820  		x1 := nat(nil).sub(x.abs, natOne)
   821  		z.abs = z.abs.add(z.abs.or(x1, y.abs), natOne)
   822  		z.neg = true // z cannot be zero if x is negative and y is positive
   823  		return z
   824  	}
   825  
   826  	// x &^ (-y) == x &^ ^(y-1) == x & (y-1)
   827  	y1 := nat(nil).sub(y.abs, natOne)
   828  	z.abs = z.abs.and(x.abs, y1)
   829  	z.neg = false
   830  	return z
   831  }
   832  
   833  // Or sets z = x | y and returns z.
   834  func (z *Int) Or(x, y *Int) *Int {
   835  	if x.neg == y.neg {
   836  		if x.neg {
   837  			// (-x) | (-y) == ^(x-1) | ^(y-1) == ^((x-1) & (y-1)) == -(((x-1) & (y-1)) + 1)
   838  			x1 := nat(nil).sub(x.abs, natOne)
   839  			y1 := nat(nil).sub(y.abs, natOne)
   840  			z.abs = z.abs.add(z.abs.and(x1, y1), natOne)
   841  			z.neg = true // z cannot be zero if x and y are negative
   842  			return z
   843  		}
   844  
   845  		// x | y == x | y
   846  		z.abs = z.abs.or(x.abs, y.abs)
   847  		z.neg = false
   848  		return z
   849  	}
   850  
   851  	// x.neg != y.neg
   852  	if x.neg {
   853  		x, y = y, x // | is symmetric
   854  	}
   855  
   856  	// x | (-y) == x | ^(y-1) == ^((y-1) &^ x) == -(^((y-1) &^ x) + 1)
   857  	y1 := nat(nil).sub(y.abs, natOne)
   858  	z.abs = z.abs.add(z.abs.andNot(y1, x.abs), natOne)
   859  	z.neg = true // z cannot be zero if one of x or y is negative
   860  	return z
   861  }
   862  
   863  // Xor sets z = x ^ y and returns z.
   864  func (z *Int) Xor(x, y *Int) *Int {
   865  	if x.neg == y.neg {
   866  		if x.neg {
   867  			// (-x) ^ (-y) == ^(x-1) ^ ^(y-1) == (x-1) ^ (y-1)
   868  			x1 := nat(nil).sub(x.abs, natOne)
   869  			y1 := nat(nil).sub(y.abs, natOne)
   870  			z.abs = z.abs.xor(x1, y1)
   871  			z.neg = false
   872  			return z
   873  		}
   874  
   875  		// x ^ y == x ^ y
   876  		z.abs = z.abs.xor(x.abs, y.abs)
   877  		z.neg = false
   878  		return z
   879  	}
   880  
   881  	// x.neg != y.neg
   882  	if x.neg {
   883  		x, y = y, x // ^ is symmetric
   884  	}
   885  
   886  	// x ^ (-y) == x ^ ^(y-1) == ^(x ^ (y-1)) == -((x ^ (y-1)) + 1)
   887  	y1 := nat(nil).sub(y.abs, natOne)
   888  	z.abs = z.abs.add(z.abs.xor(x.abs, y1), natOne)
   889  	z.neg = true // z cannot be zero if only one of x or y is negative
   890  	return z
   891  }
   892  
   893  // Not sets z = ^x and returns z.
   894  func (z *Int) Not(x *Int) *Int {
   895  	if x.neg {
   896  		// ^(-x) == ^(^(x-1)) == x-1
   897  		z.abs = z.abs.sub(x.abs, natOne)
   898  		z.neg = false
   899  		return z
   900  	}
   901  
   902  	// ^x == -x-1 == -(x+1)
   903  	z.abs = z.abs.add(x.abs, natOne)
   904  	z.neg = true // z cannot be zero if x is positive
   905  	return z
   906  }
   907  
   908  // Gob codec version. Permits backward-compatible changes to the encoding.
   909  const intGobVersion byte = 1
   910  
   911  // GobEncode implements the gob.GobEncoder interface.
   912  func (x *Int) GobEncode() ([]byte, error) {
   913  	if x == nil {
   914  		return nil, nil
   915  	}
   916  	buf := make([]byte, 1+len(x.abs)*_S) // extra byte for version and sign bit
   917  	i := x.abs.bytes(buf) - 1            // i >= 0
   918  	b := intGobVersion << 1              // make space for sign bit
   919  	if x.neg {
   920  		b |= 1
   921  	}
   922  	buf[i] = b
   923  	return buf[i:], nil
   924  }
   925  
   926  // GobDecode implements the gob.GobDecoder interface.
   927  func (z *Int) GobDecode(buf []byte) error {
   928  	if len(buf) == 0 {
   929  		// Other side sent a nil or default value.
   930  		*z = Int{}
   931  		return nil
   932  	}
   933  	b := buf[0]
   934  	if b>>1 != intGobVersion {
   935  		return fmt.Errorf("Int.GobDecode: encoding version %d not supported", b>>1)
   936  	}
   937  	z.neg = b&1 != 0
   938  	z.abs = z.abs.setBytes(buf[1:])
   939  	return nil
   940  }
   941  
   942  // MarshalJSON implements the json.Marshaler interface.
   943  func (z *Int) MarshalJSON() ([]byte, error) {
   944  	// TODO(gri): get rid of the []byte/string conversions
   945  	return []byte(z.String()), nil
   946  }
   947  
   948  // UnmarshalJSON implements the json.Unmarshaler interface.
   949  func (z *Int) UnmarshalJSON(text []byte) error {
   950  	// TODO(gri): get rid of the []byte/string conversions
   951  	if _, ok := z.SetString(string(text), 0); !ok {
   952  		return fmt.Errorf("math/big: cannot unmarshal %q into a *big.Int", text)
   953  	}
   954  	return nil
   955  }
   956  
   957  // MarshalText implements the encoding.TextMarshaler interface.
   958  func (z *Int) MarshalText() (text []byte, err error) {
   959  	return []byte(z.String()), nil
   960  }
   961  
   962  // UnmarshalText implements the encoding.TextUnmarshaler interface.
   963  func (z *Int) UnmarshalText(text []byte) error {
   964  	if _, ok := z.SetString(string(text), 0); !ok {
   965  		return fmt.Errorf("math/big: cannot unmarshal %q into a *big.Int", text)
   966  	}
   967  	return nil
   968  }