github.com/hlts2/go@v0.0.0-20170904000733-812b34efaed8/src/math/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  	if x == y {
   157  		z.abs = z.abs.sqr(x.abs)
   158  		z.neg = false
   159  		return z
   160  	}
   161  	z.abs = z.abs.mul(x.abs, y.abs)
   162  	z.neg = len(z.abs) > 0 && x.neg != y.neg // 0 has no sign
   163  	return z
   164  }
   165  
   166  // MulRange sets z to the product of all integers
   167  // in the range [a, b] inclusively and returns z.
   168  // If a > b (empty range), the result is 1.
   169  func (z *Int) MulRange(a, b int64) *Int {
   170  	switch {
   171  	case a > b:
   172  		return z.SetInt64(1) // empty range
   173  	case a <= 0 && b >= 0:
   174  		return z.SetInt64(0) // range includes 0
   175  	}
   176  	// a <= b && (b < 0 || a > 0)
   177  
   178  	neg := false
   179  	if a < 0 {
   180  		neg = (b-a)&1 == 0
   181  		a, b = -b, -a
   182  	}
   183  
   184  	z.abs = z.abs.mulRange(uint64(a), uint64(b))
   185  	z.neg = neg
   186  	return z
   187  }
   188  
   189  // Binomial sets z to the binomial coefficient of (n, k) and returns z.
   190  func (z *Int) Binomial(n, k int64) *Int {
   191  	// reduce the number of multiplications by reducing k
   192  	if n/2 < k && k <= n {
   193  		k = n - k // Binomial(n, k) == Binomial(n, n-k)
   194  	}
   195  	var a, b Int
   196  	a.MulRange(n-k+1, n)
   197  	b.MulRange(1, k)
   198  	return z.Quo(&a, &b)
   199  }
   200  
   201  // Quo sets z to the quotient x/y for y != 0 and returns z.
   202  // If y == 0, a division-by-zero run-time panic occurs.
   203  // Quo implements truncated division (like Go); see QuoRem for more details.
   204  func (z *Int) Quo(x, y *Int) *Int {
   205  	z.abs, _ = z.abs.div(nil, x.abs, y.abs)
   206  	z.neg = len(z.abs) > 0 && x.neg != y.neg // 0 has no sign
   207  	return z
   208  }
   209  
   210  // Rem sets z to the remainder x%y for y != 0 and returns z.
   211  // If y == 0, a division-by-zero run-time panic occurs.
   212  // Rem implements truncated modulus (like Go); see QuoRem for more details.
   213  func (z *Int) Rem(x, y *Int) *Int {
   214  	_, z.abs = nat(nil).div(z.abs, x.abs, y.abs)
   215  	z.neg = len(z.abs) > 0 && x.neg // 0 has no sign
   216  	return z
   217  }
   218  
   219  // QuoRem sets z to the quotient x/y and r to the remainder x%y
   220  // and returns the pair (z, r) for y != 0.
   221  // If y == 0, a division-by-zero run-time panic occurs.
   222  //
   223  // QuoRem implements T-division and modulus (like Go):
   224  //
   225  //	q = x/y      with the result truncated to zero
   226  //	r = x - y*q
   227  //
   228  // (See Daan Leijen, ``Division and Modulus for Computer Scientists''.)
   229  // See DivMod for Euclidean division and modulus (unlike Go).
   230  //
   231  func (z *Int) QuoRem(x, y, r *Int) (*Int, *Int) {
   232  	z.abs, r.abs = z.abs.div(r.abs, x.abs, y.abs)
   233  	z.neg, r.neg = len(z.abs) > 0 && x.neg != y.neg, len(r.abs) > 0 && x.neg // 0 has no sign
   234  	return z, r
   235  }
   236  
   237  // Div sets z to the quotient x/y for y != 0 and returns z.
   238  // If y == 0, a division-by-zero run-time panic occurs.
   239  // Div implements Euclidean division (unlike Go); see DivMod for more details.
   240  func (z *Int) Div(x, y *Int) *Int {
   241  	y_neg := y.neg // z may be an alias for y
   242  	var r Int
   243  	z.QuoRem(x, y, &r)
   244  	if r.neg {
   245  		if y_neg {
   246  			z.Add(z, intOne)
   247  		} else {
   248  			z.Sub(z, intOne)
   249  		}
   250  	}
   251  	return z
   252  }
   253  
   254  // Mod sets z to the modulus x%y for y != 0 and returns z.
   255  // If y == 0, a division-by-zero run-time panic occurs.
   256  // Mod implements Euclidean modulus (unlike Go); see DivMod for more details.
   257  func (z *Int) Mod(x, y *Int) *Int {
   258  	y0 := y // save y
   259  	if z == y || alias(z.abs, y.abs) {
   260  		y0 = new(Int).Set(y)
   261  	}
   262  	var q Int
   263  	q.QuoRem(x, y, z)
   264  	if z.neg {
   265  		if y0.neg {
   266  			z.Sub(z, y0)
   267  		} else {
   268  			z.Add(z, y0)
   269  		}
   270  	}
   271  	return z
   272  }
   273  
   274  // DivMod sets z to the quotient x div y and m to the modulus x mod y
   275  // and returns the pair (z, m) for y != 0.
   276  // If y == 0, a division-by-zero run-time panic occurs.
   277  //
   278  // DivMod implements Euclidean division and modulus (unlike Go):
   279  //
   280  //	q = x div y  such that
   281  //	m = x - y*q  with 0 <= m < |y|
   282  //
   283  // (See Raymond T. Boute, ``The Euclidean definition of the functions
   284  // div and mod''. ACM Transactions on Programming Languages and
   285  // Systems (TOPLAS), 14(2):127-144, New York, NY, USA, 4/1992.
   286  // ACM press.)
   287  // See QuoRem for T-division and modulus (like Go).
   288  //
   289  func (z *Int) DivMod(x, y, m *Int) (*Int, *Int) {
   290  	y0 := y // save y
   291  	if z == y || alias(z.abs, y.abs) {
   292  		y0 = new(Int).Set(y)
   293  	}
   294  	z.QuoRem(x, y, m)
   295  	if m.neg {
   296  		if y0.neg {
   297  			z.Add(z, intOne)
   298  			m.Sub(m, y0)
   299  		} else {
   300  			z.Sub(z, intOne)
   301  			m.Add(m, y0)
   302  		}
   303  	}
   304  	return z, m
   305  }
   306  
   307  // Cmp compares x and y and returns:
   308  //
   309  //   -1 if x <  y
   310  //    0 if x == y
   311  //   +1 if x >  y
   312  //
   313  func (x *Int) Cmp(y *Int) (r int) {
   314  	// x cmp y == x cmp y
   315  	// x cmp (-y) == x
   316  	// (-x) cmp y == y
   317  	// (-x) cmp (-y) == -(x cmp y)
   318  	switch {
   319  	case x.neg == y.neg:
   320  		r = x.abs.cmp(y.abs)
   321  		if x.neg {
   322  			r = -r
   323  		}
   324  	case x.neg:
   325  		r = -1
   326  	default:
   327  		r = 1
   328  	}
   329  	return
   330  }
   331  
   332  // low32 returns the least significant 32 bits of x.
   333  func low32(x nat) uint32 {
   334  	if len(x) == 0 {
   335  		return 0
   336  	}
   337  	return uint32(x[0])
   338  }
   339  
   340  // low64 returns the least significant 64 bits of x.
   341  func low64(x nat) uint64 {
   342  	if len(x) == 0 {
   343  		return 0
   344  	}
   345  	v := uint64(x[0])
   346  	if _W == 32 && len(x) > 1 {
   347  		return uint64(x[1])<<32 | v
   348  	}
   349  	return v
   350  }
   351  
   352  // Int64 returns the int64 representation of x.
   353  // If x cannot be represented in an int64, the result is undefined.
   354  func (x *Int) Int64() int64 {
   355  	v := int64(low64(x.abs))
   356  	if x.neg {
   357  		v = -v
   358  	}
   359  	return v
   360  }
   361  
   362  // Uint64 returns the uint64 representation of x.
   363  // If x cannot be represented in a uint64, the result is undefined.
   364  func (x *Int) Uint64() uint64 {
   365  	return low64(x.abs)
   366  }
   367  
   368  // IsInt64 reports whether x can be represented as an int64.
   369  func (x *Int) IsInt64() bool {
   370  	if len(x.abs) <= 64/_W {
   371  		w := int64(low64(x.abs))
   372  		return w >= 0 || x.neg && w == -w
   373  	}
   374  	return false
   375  }
   376  
   377  // IsUint64 reports whether x can be represented as a uint64.
   378  func (x *Int) IsUint64() bool {
   379  	return !x.neg && len(x.abs) <= 64/_W
   380  }
   381  
   382  // SetString sets z to the value of s, interpreted in the given base,
   383  // and returns z and a boolean indicating success. The entire string
   384  // (not just a prefix) must be valid for success. If SetString fails,
   385  // the value of z is undefined but the returned value is nil.
   386  //
   387  // The base argument must be 0 or a value between 2 and MaxBase. If the base
   388  // is 0, the string prefix determines the actual conversion base. A prefix of
   389  // ``0x'' or ``0X'' selects base 16; the ``0'' prefix selects base 8, and a
   390  // ``0b'' or ``0B'' prefix selects base 2. Otherwise the selected base is 10.
   391  //
   392  func (z *Int) SetString(s string, base int) (*Int, bool) {
   393  	r := strings.NewReader(s)
   394  	if _, _, err := z.scan(r, base); err != nil {
   395  		return nil, false
   396  	}
   397  	// entire string must have been consumed
   398  	if _, err := r.ReadByte(); err != io.EOF {
   399  		return nil, false
   400  	}
   401  	return z, true // err == io.EOF => scan consumed all of s
   402  }
   403  
   404  // SetBytes interprets buf as the bytes of a big-endian unsigned
   405  // integer, sets z to that value, and returns z.
   406  func (z *Int) SetBytes(buf []byte) *Int {
   407  	z.abs = z.abs.setBytes(buf)
   408  	z.neg = false
   409  	return z
   410  }
   411  
   412  // Bytes returns the absolute value of x as a big-endian byte slice.
   413  func (x *Int) Bytes() []byte {
   414  	buf := make([]byte, len(x.abs)*_S)
   415  	return buf[x.abs.bytes(buf):]
   416  }
   417  
   418  // BitLen returns the length of the absolute value of x in bits.
   419  // The bit length of 0 is 0.
   420  func (x *Int) BitLen() int {
   421  	return x.abs.bitLen()
   422  }
   423  
   424  // Exp sets z = x**y mod |m| (i.e. the sign of m is ignored), and returns z.
   425  // If y <= 0, the result is 1 mod |m|; if m == nil or m == 0, z = x**y.
   426  //
   427  // Modular exponentation of inputs of a particular size is not a
   428  // cryptographically constant-time operation.
   429  func (z *Int) Exp(x, y, m *Int) *Int {
   430  	// See Knuth, volume 2, section 4.6.3.
   431  	var yWords nat
   432  	if !y.neg {
   433  		yWords = y.abs
   434  	}
   435  	// y >= 0
   436  
   437  	var mWords nat
   438  	if m != nil {
   439  		mWords = m.abs // m.abs may be nil for m == 0
   440  	}
   441  
   442  	z.abs = z.abs.expNN(x.abs, yWords, mWords)
   443  	z.neg = len(z.abs) > 0 && x.neg && len(yWords) > 0 && yWords[0]&1 == 1 // 0 has no sign
   444  	if z.neg && len(mWords) > 0 {
   445  		// make modulus result positive
   446  		z.abs = z.abs.sub(mWords, z.abs) // z == x**y mod |m| && 0 <= z < |m|
   447  		z.neg = false
   448  	}
   449  
   450  	return z
   451  }
   452  
   453  // GCD sets z to the greatest common divisor of a and b, which both must
   454  // be > 0, and returns z.
   455  // If x or y are not nil, GCD sets their value such that z = a*x + b*y.
   456  // If either a or b is <= 0, GCD sets z = x = y = 0.
   457  func (z *Int) GCD(x, y, a, b *Int) *Int {
   458  	if a.Sign() <= 0 || b.Sign() <= 0 {
   459  		z.SetInt64(0)
   460  		if x != nil {
   461  			x.SetInt64(0)
   462  		}
   463  		if y != nil {
   464  			y.SetInt64(0)
   465  		}
   466  		return z
   467  	}
   468  	if x == nil && y == nil {
   469  		return z.binaryGCD(a, b)
   470  	}
   471  
   472  	A := new(Int).Set(a)
   473  	B := new(Int).Set(b)
   474  
   475  	X := new(Int)
   476  	lastX := new(Int).SetInt64(1)
   477  
   478  	q := new(Int)
   479  	temp := new(Int)
   480  
   481  	r := new(Int)
   482  	for len(B.abs) > 0 {
   483  		q, r = q.QuoRem(A, B, r)
   484  
   485  		A, B, r = B, r, A
   486  
   487  		temp.Set(X)
   488  		X.Mul(X, q)
   489  		X.Sub(lastX, X)
   490  		lastX.Set(temp)
   491  	}
   492  
   493  	if x != nil {
   494  		*x = *lastX
   495  	}
   496  
   497  	if y != nil {
   498  		// y = (z - a*x)/b
   499  		y.Mul(a, lastX)
   500  		y.Sub(A, y)
   501  		y.Div(y, b)
   502  	}
   503  
   504  	*z = *A
   505  	return z
   506  }
   507  
   508  // binaryGCD sets z to the greatest common divisor of a and b, which both must
   509  // be > 0, and returns z.
   510  // See Knuth, The Art of Computer Programming, Vol. 2, Section 4.5.2, Algorithm B.
   511  func (z *Int) binaryGCD(a, b *Int) *Int {
   512  	u := z
   513  	v := new(Int)
   514  
   515  	// use one Euclidean iteration to ensure that u and v are approx. the same size
   516  	switch {
   517  	case len(a.abs) > len(b.abs):
   518  		// must set v before u since u may be alias for a or b (was issue #11284)
   519  		v.Rem(a, b)
   520  		u.Set(b)
   521  	case len(a.abs) < len(b.abs):
   522  		v.Rem(b, a)
   523  		u.Set(a)
   524  	default:
   525  		v.Set(b)
   526  		u.Set(a)
   527  	}
   528  	// a, b must not be used anymore (may be aliases with u)
   529  
   530  	// v might be 0 now
   531  	if len(v.abs) == 0 {
   532  		return u
   533  	}
   534  	// u > 0 && v > 0
   535  
   536  	// determine largest k such that u = u' << k, v = v' << k
   537  	k := u.abs.trailingZeroBits()
   538  	if vk := v.abs.trailingZeroBits(); vk < k {
   539  		k = vk
   540  	}
   541  	u.Rsh(u, k)
   542  	v.Rsh(v, k)
   543  
   544  	// determine t (we know that u > 0)
   545  	t := new(Int)
   546  	if u.abs[0]&1 != 0 {
   547  		// u is odd
   548  		t.Neg(v)
   549  	} else {
   550  		t.Set(u)
   551  	}
   552  
   553  	for len(t.abs) > 0 {
   554  		// reduce t
   555  		t.Rsh(t, t.abs.trailingZeroBits())
   556  		if t.neg {
   557  			v, t = t, v
   558  			v.neg = len(v.abs) > 0 && !v.neg // 0 has no sign
   559  		} else {
   560  			u, t = t, u
   561  		}
   562  		t.Sub(u, v)
   563  	}
   564  
   565  	return z.Lsh(u, k)
   566  }
   567  
   568  // Rand sets z to a pseudo-random number in [0, n) and returns z.
   569  func (z *Int) Rand(rnd *rand.Rand, n *Int) *Int {
   570  	z.neg = false
   571  	if n.neg || len(n.abs) == 0 {
   572  		z.abs = nil
   573  		return z
   574  	}
   575  	z.abs = z.abs.random(rnd, n.abs, n.abs.bitLen())
   576  	return z
   577  }
   578  
   579  // ModInverse sets z to the multiplicative inverse of g in the ring ℤ/nℤ
   580  // and returns z. If g and n are not relatively prime, the result is undefined.
   581  func (z *Int) ModInverse(g, n *Int) *Int {
   582  	if g.neg {
   583  		// GCD expects parameters a and b to be > 0.
   584  		var g2 Int
   585  		g = g2.Mod(g, n)
   586  	}
   587  	var d Int
   588  	d.GCD(z, nil, g, n)
   589  	// x and y are such that g*x + n*y = d. Since g and n are
   590  	// relatively prime, d = 1. Taking that modulo n results in
   591  	// g*x = 1, therefore x is the inverse element.
   592  	if z.neg {
   593  		z.Add(z, n)
   594  	}
   595  	return z
   596  }
   597  
   598  // Jacobi returns the Jacobi symbol (x/y), either +1, -1, or 0.
   599  // The y argument must be an odd integer.
   600  func Jacobi(x, y *Int) int {
   601  	if len(y.abs) == 0 || y.abs[0]&1 == 0 {
   602  		panic(fmt.Sprintf("big: invalid 2nd argument to Int.Jacobi: need odd integer but got %s", y))
   603  	}
   604  
   605  	// We use the formulation described in chapter 2, section 2.4,
   606  	// "The Yacas Book of Algorithms":
   607  	// http://yacas.sourceforge.net/Algo.book.pdf
   608  
   609  	var a, b, c Int
   610  	a.Set(x)
   611  	b.Set(y)
   612  	j := 1
   613  
   614  	if b.neg {
   615  		if a.neg {
   616  			j = -1
   617  		}
   618  		b.neg = false
   619  	}
   620  
   621  	for {
   622  		if b.Cmp(intOne) == 0 {
   623  			return j
   624  		}
   625  		if len(a.abs) == 0 {
   626  			return 0
   627  		}
   628  		a.Mod(&a, &b)
   629  		if len(a.abs) == 0 {
   630  			return 0
   631  		}
   632  		// a > 0
   633  
   634  		// handle factors of 2 in 'a'
   635  		s := a.abs.trailingZeroBits()
   636  		if s&1 != 0 {
   637  			bmod8 := b.abs[0] & 7
   638  			if bmod8 == 3 || bmod8 == 5 {
   639  				j = -j
   640  			}
   641  		}
   642  		c.Rsh(&a, s) // a = 2^s*c
   643  
   644  		// swap numerator and denominator
   645  		if b.abs[0]&3 == 3 && c.abs[0]&3 == 3 {
   646  			j = -j
   647  		}
   648  		a.Set(&b)
   649  		b.Set(&c)
   650  	}
   651  }
   652  
   653  // modSqrt3Mod4 uses the identity
   654  //      (a^((p+1)/4))^2  mod p
   655  //   == u^(p+1)          mod p
   656  //   == u^2              mod p
   657  // to calculate the square root of any quadratic residue mod p quickly for 3
   658  // mod 4 primes.
   659  func (z *Int) modSqrt3Mod4Prime(x, p *Int) *Int {
   660  	z.Set(p)         // z = p
   661  	z.Add(z, intOne) // z = p + 1
   662  	z.Rsh(z, 2)      // z = (p + 1) / 4
   663  	z.Exp(x, z, p)   // z = x^z mod p
   664  	return z
   665  }
   666  
   667  // modSqrtTonelliShanks uses the Tonelli-Shanks algorithm to find the square
   668  // root of a quadratic residue modulo any prime.
   669  func (z *Int) modSqrtTonelliShanks(x, p *Int) *Int {
   670  	// Break p-1 into s*2^e such that s is odd.
   671  	var s Int
   672  	s.Sub(p, intOne)
   673  	e := s.abs.trailingZeroBits()
   674  	s.Rsh(&s, e)
   675  
   676  	// find some non-square n
   677  	var n Int
   678  	n.SetInt64(2)
   679  	for Jacobi(&n, p) != -1 {
   680  		n.Add(&n, intOne)
   681  	}
   682  
   683  	// Core of the Tonelli-Shanks algorithm. Follows the description in
   684  	// section 6 of "Square roots from 1; 24, 51, 10 to Dan Shanks" by Ezra
   685  	// Brown:
   686  	// https://www.maa.org/sites/default/files/pdf/upload_library/22/Polya/07468342.di020786.02p0470a.pdf
   687  	var y, b, g, t Int
   688  	y.Add(&s, intOne)
   689  	y.Rsh(&y, 1)
   690  	y.Exp(x, &y, p)  // y = x^((s+1)/2)
   691  	b.Exp(x, &s, p)  // b = x^s
   692  	g.Exp(&n, &s, p) // g = n^s
   693  	r := e
   694  	for {
   695  		// find the least m such that ord_p(b) = 2^m
   696  		var m uint
   697  		t.Set(&b)
   698  		for t.Cmp(intOne) != 0 {
   699  			t.Mul(&t, &t).Mod(&t, p)
   700  			m++
   701  		}
   702  
   703  		if m == 0 {
   704  			return z.Set(&y)
   705  		}
   706  
   707  		t.SetInt64(0).SetBit(&t, int(r-m-1), 1).Exp(&g, &t, p)
   708  		// t = g^(2^(r-m-1)) mod p
   709  		g.Mul(&t, &t).Mod(&g, p) // g = g^(2^(r-m)) mod p
   710  		y.Mul(&y, &t).Mod(&y, p)
   711  		b.Mul(&b, &g).Mod(&b, p)
   712  		r = m
   713  	}
   714  }
   715  
   716  // ModSqrt sets z to a square root of x mod p if such a square root exists, and
   717  // returns z. The modulus p must be an odd prime. If x is not a square mod p,
   718  // ModSqrt leaves z unchanged and returns nil. This function panics if p is
   719  // not an odd integer.
   720  func (z *Int) ModSqrt(x, p *Int) *Int {
   721  	switch Jacobi(x, p) {
   722  	case -1:
   723  		return nil // x is not a square mod p
   724  	case 0:
   725  		return z.SetInt64(0) // sqrt(0) mod p = 0
   726  	case 1:
   727  		break
   728  	}
   729  	if x.neg || x.Cmp(p) >= 0 { // ensure 0 <= x < p
   730  		x = new(Int).Mod(x, p)
   731  	}
   732  
   733  	// Check whether p is 3 mod 4, and if so, use the faster algorithm.
   734  	if len(p.abs) > 0 && p.abs[0]%4 == 3 {
   735  		return z.modSqrt3Mod4Prime(x, p)
   736  	}
   737  	// Otherwise, use Tonelli-Shanks.
   738  	return z.modSqrtTonelliShanks(x, p)
   739  }
   740  
   741  // Lsh sets z = x << n and returns z.
   742  func (z *Int) Lsh(x *Int, n uint) *Int {
   743  	z.abs = z.abs.shl(x.abs, n)
   744  	z.neg = x.neg
   745  	return z
   746  }
   747  
   748  // Rsh sets z = x >> n and returns z.
   749  func (z *Int) Rsh(x *Int, n uint) *Int {
   750  	if x.neg {
   751  		// (-x) >> s == ^(x-1) >> s == ^((x-1) >> s) == -(((x-1) >> s) + 1)
   752  		t := z.abs.sub(x.abs, natOne) // no underflow because |x| > 0
   753  		t = t.shr(t, n)
   754  		z.abs = t.add(t, natOne)
   755  		z.neg = true // z cannot be zero if x is negative
   756  		return z
   757  	}
   758  
   759  	z.abs = z.abs.shr(x.abs, n)
   760  	z.neg = false
   761  	return z
   762  }
   763  
   764  // Bit returns the value of the i'th bit of x. That is, it
   765  // returns (x>>i)&1. The bit index i must be >= 0.
   766  func (x *Int) Bit(i int) uint {
   767  	if i == 0 {
   768  		// optimization for common case: odd/even test of x
   769  		if len(x.abs) > 0 {
   770  			return uint(x.abs[0] & 1) // bit 0 is same for -x
   771  		}
   772  		return 0
   773  	}
   774  	if i < 0 {
   775  		panic("negative bit index")
   776  	}
   777  	if x.neg {
   778  		t := nat(nil).sub(x.abs, natOne)
   779  		return t.bit(uint(i)) ^ 1
   780  	}
   781  
   782  	return x.abs.bit(uint(i))
   783  }
   784  
   785  // SetBit sets z to x, with x's i'th bit set to b (0 or 1).
   786  // That is, if b is 1 SetBit sets z = x | (1 << i);
   787  // if b is 0 SetBit sets z = x &^ (1 << i). If b is not 0 or 1,
   788  // SetBit will panic.
   789  func (z *Int) SetBit(x *Int, i int, b uint) *Int {
   790  	if i < 0 {
   791  		panic("negative bit index")
   792  	}
   793  	if x.neg {
   794  		t := z.abs.sub(x.abs, natOne)
   795  		t = t.setBit(t, uint(i), b^1)
   796  		z.abs = t.add(t, natOne)
   797  		z.neg = len(z.abs) > 0
   798  		return z
   799  	}
   800  	z.abs = z.abs.setBit(x.abs, uint(i), b)
   801  	z.neg = false
   802  	return z
   803  }
   804  
   805  // And sets z = x & y and returns z.
   806  func (z *Int) And(x, y *Int) *Int {
   807  	if x.neg == y.neg {
   808  		if x.neg {
   809  			// (-x) & (-y) == ^(x-1) & ^(y-1) == ^((x-1) | (y-1)) == -(((x-1) | (y-1)) + 1)
   810  			x1 := nat(nil).sub(x.abs, natOne)
   811  			y1 := nat(nil).sub(y.abs, natOne)
   812  			z.abs = z.abs.add(z.abs.or(x1, y1), natOne)
   813  			z.neg = true // z cannot be zero if x and y are negative
   814  			return z
   815  		}
   816  
   817  		// x & y == x & y
   818  		z.abs = z.abs.and(x.abs, y.abs)
   819  		z.neg = false
   820  		return z
   821  	}
   822  
   823  	// x.neg != y.neg
   824  	if x.neg {
   825  		x, y = y, x // & is symmetric
   826  	}
   827  
   828  	// x & (-y) == x & ^(y-1) == x &^ (y-1)
   829  	y1 := nat(nil).sub(y.abs, natOne)
   830  	z.abs = z.abs.andNot(x.abs, y1)
   831  	z.neg = false
   832  	return z
   833  }
   834  
   835  // AndNot sets z = x &^ y and returns z.
   836  func (z *Int) AndNot(x, y *Int) *Int {
   837  	if x.neg == y.neg {
   838  		if x.neg {
   839  			// (-x) &^ (-y) == ^(x-1) &^ ^(y-1) == ^(x-1) & (y-1) == (y-1) &^ (x-1)
   840  			x1 := nat(nil).sub(x.abs, natOne)
   841  			y1 := nat(nil).sub(y.abs, natOne)
   842  			z.abs = z.abs.andNot(y1, x1)
   843  			z.neg = false
   844  			return z
   845  		}
   846  
   847  		// x &^ y == x &^ y
   848  		z.abs = z.abs.andNot(x.abs, y.abs)
   849  		z.neg = false
   850  		return z
   851  	}
   852  
   853  	if x.neg {
   854  		// (-x) &^ y == ^(x-1) &^ y == ^(x-1) & ^y == ^((x-1) | y) == -(((x-1) | y) + 1)
   855  		x1 := nat(nil).sub(x.abs, natOne)
   856  		z.abs = z.abs.add(z.abs.or(x1, y.abs), natOne)
   857  		z.neg = true // z cannot be zero if x is negative and y is positive
   858  		return z
   859  	}
   860  
   861  	// x &^ (-y) == x &^ ^(y-1) == x & (y-1)
   862  	y1 := nat(nil).sub(y.abs, natOne)
   863  	z.abs = z.abs.and(x.abs, y1)
   864  	z.neg = false
   865  	return z
   866  }
   867  
   868  // Or sets z = x | y and returns z.
   869  func (z *Int) Or(x, y *Int) *Int {
   870  	if x.neg == y.neg {
   871  		if x.neg {
   872  			// (-x) | (-y) == ^(x-1) | ^(y-1) == ^((x-1) & (y-1)) == -(((x-1) & (y-1)) + 1)
   873  			x1 := nat(nil).sub(x.abs, natOne)
   874  			y1 := nat(nil).sub(y.abs, natOne)
   875  			z.abs = z.abs.add(z.abs.and(x1, y1), natOne)
   876  			z.neg = true // z cannot be zero if x and y are negative
   877  			return z
   878  		}
   879  
   880  		// x | y == x | y
   881  		z.abs = z.abs.or(x.abs, y.abs)
   882  		z.neg = false
   883  		return z
   884  	}
   885  
   886  	// x.neg != y.neg
   887  	if x.neg {
   888  		x, y = y, x // | is symmetric
   889  	}
   890  
   891  	// x | (-y) == x | ^(y-1) == ^((y-1) &^ x) == -(^((y-1) &^ x) + 1)
   892  	y1 := nat(nil).sub(y.abs, natOne)
   893  	z.abs = z.abs.add(z.abs.andNot(y1, x.abs), natOne)
   894  	z.neg = true // z cannot be zero if one of x or y is negative
   895  	return z
   896  }
   897  
   898  // Xor sets z = x ^ y and returns z.
   899  func (z *Int) Xor(x, y *Int) *Int {
   900  	if x.neg == y.neg {
   901  		if x.neg {
   902  			// (-x) ^ (-y) == ^(x-1) ^ ^(y-1) == (x-1) ^ (y-1)
   903  			x1 := nat(nil).sub(x.abs, natOne)
   904  			y1 := nat(nil).sub(y.abs, natOne)
   905  			z.abs = z.abs.xor(x1, y1)
   906  			z.neg = false
   907  			return z
   908  		}
   909  
   910  		// x ^ y == x ^ y
   911  		z.abs = z.abs.xor(x.abs, y.abs)
   912  		z.neg = false
   913  		return z
   914  	}
   915  
   916  	// x.neg != y.neg
   917  	if x.neg {
   918  		x, y = y, x // ^ is symmetric
   919  	}
   920  
   921  	// x ^ (-y) == x ^ ^(y-1) == ^(x ^ (y-1)) == -((x ^ (y-1)) + 1)
   922  	y1 := nat(nil).sub(y.abs, natOne)
   923  	z.abs = z.abs.add(z.abs.xor(x.abs, y1), natOne)
   924  	z.neg = true // z cannot be zero if only one of x or y is negative
   925  	return z
   926  }
   927  
   928  // Not sets z = ^x and returns z.
   929  func (z *Int) Not(x *Int) *Int {
   930  	if x.neg {
   931  		// ^(-x) == ^(^(x-1)) == x-1
   932  		z.abs = z.abs.sub(x.abs, natOne)
   933  		z.neg = false
   934  		return z
   935  	}
   936  
   937  	// ^x == -x-1 == -(x+1)
   938  	z.abs = z.abs.add(x.abs, natOne)
   939  	z.neg = true // z cannot be zero if x is positive
   940  	return z
   941  }
   942  
   943  // Sqrt sets z to ⌊√x⌋, the largest integer such that z² ≤ x, and returns z.
   944  // It panics if x is negative.
   945  func (z *Int) Sqrt(x *Int) *Int {
   946  	if x.neg {
   947  		panic("square root of negative number")
   948  	}
   949  	z.neg = false
   950  	z.abs = z.abs.sqrt(x.abs)
   951  	return z
   952  }