github.com/FenixAra/go@v0.0.0-20170127160404-96ea0918e670/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  	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 < |y|
   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. The entire string
   365  // (not just a prefix) must be valid for success. If SetString fails,
   366  // the value of z is undefined but the returned value is nil.
   367  //
   368  // The base argument must be 0 or a value between 2 and MaxBase. If the base
   369  // is 0, the string prefix determines the actual conversion base. A prefix of
   370  // ``0x'' or ``0X'' selects base 16; the ``0'' prefix selects base 8, and a
   371  // ``0b'' or ``0B'' prefix selects base 2. Otherwise the selected base is 10.
   372  //
   373  func (z *Int) SetString(s string, base int) (*Int, bool) {
   374  	r := strings.NewReader(s)
   375  	if _, _, err := z.scan(r, base); err != nil {
   376  		return nil, false
   377  	}
   378  	// entire string must have been consumed
   379  	if _, err := r.ReadByte(); 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  //
   408  // Modular exponentation of inputs of a particular size is not a
   409  // cryptographically constant-time operation.
   410  func (z *Int) Exp(x, y, m *Int) *Int {
   411  	// See Knuth, volume 2, section 4.6.3.
   412  	var yWords nat
   413  	if !y.neg {
   414  		yWords = y.abs
   415  	}
   416  	// y >= 0
   417  
   418  	var mWords nat
   419  	if m != nil {
   420  		mWords = m.abs // m.abs may be nil for m == 0
   421  	}
   422  
   423  	z.abs = z.abs.expNN(x.abs, yWords, mWords)
   424  	z.neg = len(z.abs) > 0 && x.neg && len(yWords) > 0 && yWords[0]&1 == 1 // 0 has no sign
   425  	if z.neg && len(mWords) > 0 {
   426  		// make modulus result positive
   427  		z.abs = z.abs.sub(mWords, z.abs) // z == x**y mod |m| && 0 <= z < |m|
   428  		z.neg = false
   429  	}
   430  
   431  	return z
   432  }
   433  
   434  // GCD sets z to the greatest common divisor of a and b, which both must
   435  // be > 0, and returns z.
   436  // If x and y are not nil, GCD sets x and y such that z = a*x + b*y.
   437  // If either a or b is <= 0, GCD sets z = x = y = 0.
   438  func (z *Int) GCD(x, y, a, b *Int) *Int {
   439  	if a.Sign() <= 0 || b.Sign() <= 0 {
   440  		z.SetInt64(0)
   441  		if x != nil {
   442  			x.SetInt64(0)
   443  		}
   444  		if y != nil {
   445  			y.SetInt64(0)
   446  		}
   447  		return z
   448  	}
   449  	if x == nil && y == nil {
   450  		return z.binaryGCD(a, b)
   451  	}
   452  
   453  	A := new(Int).Set(a)
   454  	B := new(Int).Set(b)
   455  
   456  	X := new(Int)
   457  	Y := new(Int).SetInt64(1)
   458  
   459  	lastX := new(Int).SetInt64(1)
   460  	lastY := new(Int)
   461  
   462  	q := new(Int)
   463  	temp := new(Int)
   464  
   465  	r := new(Int)
   466  	for len(B.abs) > 0 {
   467  		q, r = q.QuoRem(A, B, r)
   468  
   469  		A, B, r = B, r, A
   470  
   471  		temp.Set(X)
   472  		X.Mul(X, q)
   473  		X.neg = !X.neg
   474  		X.Add(X, lastX)
   475  		lastX.Set(temp)
   476  
   477  		temp.Set(Y)
   478  		Y.Mul(Y, q)
   479  		Y.neg = !Y.neg
   480  		Y.Add(Y, lastY)
   481  		lastY.Set(temp)
   482  	}
   483  
   484  	if x != nil {
   485  		*x = *lastX
   486  	}
   487  
   488  	if y != nil {
   489  		*y = *lastY
   490  	}
   491  
   492  	*z = *A
   493  	return z
   494  }
   495  
   496  // binaryGCD sets z to the greatest common divisor of a and b, which both must
   497  // be > 0, and returns z.
   498  // See Knuth, The Art of Computer Programming, Vol. 2, Section 4.5.2, Algorithm B.
   499  func (z *Int) binaryGCD(a, b *Int) *Int {
   500  	u := z
   501  	v := new(Int)
   502  
   503  	// use one Euclidean iteration to ensure that u and v are approx. the same size
   504  	switch {
   505  	case len(a.abs) > len(b.abs):
   506  		// must set v before u since u may be alias for a or b (was issue #11284)
   507  		v.Rem(a, b)
   508  		u.Set(b)
   509  	case len(a.abs) < len(b.abs):
   510  		v.Rem(b, a)
   511  		u.Set(a)
   512  	default:
   513  		v.Set(b)
   514  		u.Set(a)
   515  	}
   516  	// a, b must not be used anymore (may be aliases with u)
   517  
   518  	// v might be 0 now
   519  	if len(v.abs) == 0 {
   520  		return u
   521  	}
   522  	// u > 0 && v > 0
   523  
   524  	// determine largest k such that u = u' << k, v = v' << k
   525  	k := u.abs.trailingZeroBits()
   526  	if vk := v.abs.trailingZeroBits(); vk < k {
   527  		k = vk
   528  	}
   529  	u.Rsh(u, k)
   530  	v.Rsh(v, k)
   531  
   532  	// determine t (we know that u > 0)
   533  	t := new(Int)
   534  	if u.abs[0]&1 != 0 {
   535  		// u is odd
   536  		t.Neg(v)
   537  	} else {
   538  		t.Set(u)
   539  	}
   540  
   541  	for len(t.abs) > 0 {
   542  		// reduce t
   543  		t.Rsh(t, t.abs.trailingZeroBits())
   544  		if t.neg {
   545  			v, t = t, v
   546  			v.neg = len(v.abs) > 0 && !v.neg // 0 has no sign
   547  		} else {
   548  			u, t = t, u
   549  		}
   550  		t.Sub(u, v)
   551  	}
   552  
   553  	return z.Lsh(u, k)
   554  }
   555  
   556  // Rand sets z to a pseudo-random number in [0, n) and returns z.
   557  func (z *Int) Rand(rnd *rand.Rand, n *Int) *Int {
   558  	z.neg = false
   559  	if n.neg == true || len(n.abs) == 0 {
   560  		z.abs = nil
   561  		return z
   562  	}
   563  	z.abs = z.abs.random(rnd, n.abs, n.abs.bitLen())
   564  	return z
   565  }
   566  
   567  // ModInverse sets z to the multiplicative inverse of g in the ring ℤ/nℤ
   568  // and returns z. If g and n are not relatively prime, the result is undefined.
   569  func (z *Int) ModInverse(g, n *Int) *Int {
   570  	if g.neg {
   571  		// GCD expects parameters a and b to be > 0.
   572  		var g2 Int
   573  		g = g2.Mod(g, n)
   574  	}
   575  	var d Int
   576  	d.GCD(z, nil, g, n)
   577  	// x and y are such that g*x + n*y = d. Since g and n are
   578  	// relatively prime, d = 1. Taking that modulo n results in
   579  	// g*x = 1, therefore x is the inverse element.
   580  	if z.neg {
   581  		z.Add(z, n)
   582  	}
   583  	return z
   584  }
   585  
   586  // Jacobi returns the Jacobi symbol (x/y), either +1, -1, or 0.
   587  // The y argument must be an odd integer.
   588  func Jacobi(x, y *Int) int {
   589  	if len(y.abs) == 0 || y.abs[0]&1 == 0 {
   590  		panic(fmt.Sprintf("big: invalid 2nd argument to Int.Jacobi: need odd integer but got %s", y))
   591  	}
   592  
   593  	// We use the formulation described in chapter 2, section 2.4,
   594  	// "The Yacas Book of Algorithms":
   595  	// http://yacas.sourceforge.net/Algo.book.pdf
   596  
   597  	var a, b, c Int
   598  	a.Set(x)
   599  	b.Set(y)
   600  	j := 1
   601  
   602  	if b.neg {
   603  		if a.neg {
   604  			j = -1
   605  		}
   606  		b.neg = false
   607  	}
   608  
   609  	for {
   610  		if b.Cmp(intOne) == 0 {
   611  			return j
   612  		}
   613  		if len(a.abs) == 0 {
   614  			return 0
   615  		}
   616  		a.Mod(&a, &b)
   617  		if len(a.abs) == 0 {
   618  			return 0
   619  		}
   620  		// a > 0
   621  
   622  		// handle factors of 2 in 'a'
   623  		s := a.abs.trailingZeroBits()
   624  		if s&1 != 0 {
   625  			bmod8 := b.abs[0] & 7
   626  			if bmod8 == 3 || bmod8 == 5 {
   627  				j = -j
   628  			}
   629  		}
   630  		c.Rsh(&a, s) // a = 2^s*c
   631  
   632  		// swap numerator and denominator
   633  		if b.abs[0]&3 == 3 && c.abs[0]&3 == 3 {
   634  			j = -j
   635  		}
   636  		a.Set(&b)
   637  		b.Set(&c)
   638  	}
   639  }
   640  
   641  // modSqrt3Mod4 uses the identity
   642  //      (a^((p+1)/4))^2  mod p
   643  //   == u^(p+1)          mod p
   644  //   == u^2              mod p
   645  // to calculate the square root of any quadratic residue mod p quickly for 3
   646  // mod 4 primes.
   647  func (z *Int) modSqrt3Mod4Prime(x, p *Int) *Int {
   648  	z.Set(p)         // z = p
   649  	z.Add(z, intOne) // z = p + 1
   650  	z.Rsh(z, 2)      // z = (p + 1) / 4
   651  	z.Exp(x, z, p)   // z = x^z mod p
   652  	return z
   653  }
   654  
   655  // modSqrtTonelliShanks uses the Tonelli-Shanks algorithm to find the square
   656  // root of a quadratic residue modulo any prime.
   657  func (z *Int) modSqrtTonelliShanks(x, p *Int) *Int {
   658  	// Break p-1 into s*2^e such that s is odd.
   659  	var s Int
   660  	s.Sub(p, intOne)
   661  	e := s.abs.trailingZeroBits()
   662  	s.Rsh(&s, e)
   663  
   664  	// find some non-square n
   665  	var n Int
   666  	n.SetInt64(2)
   667  	for Jacobi(&n, p) != -1 {
   668  		n.Add(&n, intOne)
   669  	}
   670  
   671  	// Core of the Tonelli-Shanks algorithm. Follows the description in
   672  	// section 6 of "Square roots from 1; 24, 51, 10 to Dan Shanks" by Ezra
   673  	// Brown:
   674  	// https://www.maa.org/sites/default/files/pdf/upload_library/22/Polya/07468342.di020786.02p0470a.pdf
   675  	var y, b, g, t Int
   676  	y.Add(&s, intOne)
   677  	y.Rsh(&y, 1)
   678  	y.Exp(x, &y, p)  // y = x^((s+1)/2)
   679  	b.Exp(x, &s, p)  // b = x^s
   680  	g.Exp(&n, &s, p) // g = n^s
   681  	r := e
   682  	for {
   683  		// find the least m such that ord_p(b) = 2^m
   684  		var m uint
   685  		t.Set(&b)
   686  		for t.Cmp(intOne) != 0 {
   687  			t.Mul(&t, &t).Mod(&t, p)
   688  			m++
   689  		}
   690  
   691  		if m == 0 {
   692  			return z.Set(&y)
   693  		}
   694  
   695  		t.SetInt64(0).SetBit(&t, int(r-m-1), 1).Exp(&g, &t, p)
   696  		// t = g^(2^(r-m-1)) mod p
   697  		g.Mul(&t, &t).Mod(&g, p) // g = g^(2^(r-m)) mod p
   698  		y.Mul(&y, &t).Mod(&y, p)
   699  		b.Mul(&b, &g).Mod(&b, p)
   700  		r = m
   701  	}
   702  }
   703  
   704  // ModSqrt sets z to a square root of x mod p if such a square root exists, and
   705  // returns z. The modulus p must be an odd prime. If x is not a square mod p,
   706  // ModSqrt leaves z unchanged and returns nil. This function panics if p is
   707  // not an odd integer.
   708  func (z *Int) ModSqrt(x, p *Int) *Int {
   709  	switch Jacobi(x, p) {
   710  	case -1:
   711  		return nil // x is not a square mod p
   712  	case 0:
   713  		return z.SetInt64(0) // sqrt(0) mod p = 0
   714  	case 1:
   715  		break
   716  	}
   717  	if x.neg || x.Cmp(p) >= 0 { // ensure 0 <= x < p
   718  		x = new(Int).Mod(x, p)
   719  	}
   720  
   721  	// Check whether p is 3 mod 4, and if so, use the faster algorithm.
   722  	if len(p.abs) > 0 && p.abs[0]%4 == 3 {
   723  		return z.modSqrt3Mod4Prime(x, p)
   724  	}
   725  	// Otherwise, use Tonelli-Shanks.
   726  	return z.modSqrtTonelliShanks(x, p)
   727  }
   728  
   729  // Lsh sets z = x << n and returns z.
   730  func (z *Int) Lsh(x *Int, n uint) *Int {
   731  	z.abs = z.abs.shl(x.abs, n)
   732  	z.neg = x.neg
   733  	return z
   734  }
   735  
   736  // Rsh sets z = x >> n and returns z.
   737  func (z *Int) Rsh(x *Int, n uint) *Int {
   738  	if x.neg {
   739  		// (-x) >> s == ^(x-1) >> s == ^((x-1) >> s) == -(((x-1) >> s) + 1)
   740  		t := z.abs.sub(x.abs, natOne) // no underflow because |x| > 0
   741  		t = t.shr(t, n)
   742  		z.abs = t.add(t, natOne)
   743  		z.neg = true // z cannot be zero if x is negative
   744  		return z
   745  	}
   746  
   747  	z.abs = z.abs.shr(x.abs, n)
   748  	z.neg = false
   749  	return z
   750  }
   751  
   752  // Bit returns the value of the i'th bit of x. That is, it
   753  // returns (x>>i)&1. The bit index i must be >= 0.
   754  func (x *Int) Bit(i int) uint {
   755  	if i == 0 {
   756  		// optimization for common case: odd/even test of x
   757  		if len(x.abs) > 0 {
   758  			return uint(x.abs[0] & 1) // bit 0 is same for -x
   759  		}
   760  		return 0
   761  	}
   762  	if i < 0 {
   763  		panic("negative bit index")
   764  	}
   765  	if x.neg {
   766  		t := nat(nil).sub(x.abs, natOne)
   767  		return t.bit(uint(i)) ^ 1
   768  	}
   769  
   770  	return x.abs.bit(uint(i))
   771  }
   772  
   773  // SetBit sets z to x, with x's i'th bit set to b (0 or 1).
   774  // That is, if b is 1 SetBit sets z = x | (1 << i);
   775  // if b is 0 SetBit sets z = x &^ (1 << i). If b is not 0 or 1,
   776  // SetBit will panic.
   777  func (z *Int) SetBit(x *Int, i int, b uint) *Int {
   778  	if i < 0 {
   779  		panic("negative bit index")
   780  	}
   781  	if x.neg {
   782  		t := z.abs.sub(x.abs, natOne)
   783  		t = t.setBit(t, uint(i), b^1)
   784  		z.abs = t.add(t, natOne)
   785  		z.neg = len(z.abs) > 0
   786  		return z
   787  	}
   788  	z.abs = z.abs.setBit(x.abs, uint(i), b)
   789  	z.neg = false
   790  	return z
   791  }
   792  
   793  // And sets z = x & y and returns z.
   794  func (z *Int) And(x, y *Int) *Int {
   795  	if x.neg == y.neg {
   796  		if x.neg {
   797  			// (-x) & (-y) == ^(x-1) & ^(y-1) == ^((x-1) | (y-1)) == -(((x-1) | (y-1)) + 1)
   798  			x1 := nat(nil).sub(x.abs, natOne)
   799  			y1 := nat(nil).sub(y.abs, natOne)
   800  			z.abs = z.abs.add(z.abs.or(x1, y1), natOne)
   801  			z.neg = true // z cannot be zero if x and y are negative
   802  			return z
   803  		}
   804  
   805  		// x & y == x & y
   806  		z.abs = z.abs.and(x.abs, y.abs)
   807  		z.neg = false
   808  		return z
   809  	}
   810  
   811  	// x.neg != y.neg
   812  	if x.neg {
   813  		x, y = y, x // & is symmetric
   814  	}
   815  
   816  	// x & (-y) == x & ^(y-1) == x &^ (y-1)
   817  	y1 := nat(nil).sub(y.abs, natOne)
   818  	z.abs = z.abs.andNot(x.abs, y1)
   819  	z.neg = false
   820  	return z
   821  }
   822  
   823  // AndNot sets z = x &^ y and returns z.
   824  func (z *Int) AndNot(x, y *Int) *Int {
   825  	if x.neg == y.neg {
   826  		if x.neg {
   827  			// (-x) &^ (-y) == ^(x-1) &^ ^(y-1) == ^(x-1) & (y-1) == (y-1) &^ (x-1)
   828  			x1 := nat(nil).sub(x.abs, natOne)
   829  			y1 := nat(nil).sub(y.abs, natOne)
   830  			z.abs = z.abs.andNot(y1, x1)
   831  			z.neg = false
   832  			return z
   833  		}
   834  
   835  		// x &^ y == x &^ y
   836  		z.abs = z.abs.andNot(x.abs, y.abs)
   837  		z.neg = false
   838  		return z
   839  	}
   840  
   841  	if x.neg {
   842  		// (-x) &^ y == ^(x-1) &^ y == ^(x-1) & ^y == ^((x-1) | y) == -(((x-1) | y) + 1)
   843  		x1 := nat(nil).sub(x.abs, natOne)
   844  		z.abs = z.abs.add(z.abs.or(x1, y.abs), natOne)
   845  		z.neg = true // z cannot be zero if x is negative and y is positive
   846  		return z
   847  	}
   848  
   849  	// x &^ (-y) == x &^ ^(y-1) == x & (y-1)
   850  	y1 := nat(nil).sub(y.abs, natOne)
   851  	z.abs = z.abs.and(x.abs, y1)
   852  	z.neg = false
   853  	return z
   854  }
   855  
   856  // Or sets z = x | y and returns z.
   857  func (z *Int) Or(x, y *Int) *Int {
   858  	if x.neg == y.neg {
   859  		if x.neg {
   860  			// (-x) | (-y) == ^(x-1) | ^(y-1) == ^((x-1) & (y-1)) == -(((x-1) & (y-1)) + 1)
   861  			x1 := nat(nil).sub(x.abs, natOne)
   862  			y1 := nat(nil).sub(y.abs, natOne)
   863  			z.abs = z.abs.add(z.abs.and(x1, y1), natOne)
   864  			z.neg = true // z cannot be zero if x and y are negative
   865  			return z
   866  		}
   867  
   868  		// x | y == x | y
   869  		z.abs = z.abs.or(x.abs, y.abs)
   870  		z.neg = false
   871  		return z
   872  	}
   873  
   874  	// x.neg != y.neg
   875  	if x.neg {
   876  		x, y = y, x // | is symmetric
   877  	}
   878  
   879  	// x | (-y) == x | ^(y-1) == ^((y-1) &^ x) == -(^((y-1) &^ x) + 1)
   880  	y1 := nat(nil).sub(y.abs, natOne)
   881  	z.abs = z.abs.add(z.abs.andNot(y1, x.abs), natOne)
   882  	z.neg = true // z cannot be zero if one of x or y is negative
   883  	return z
   884  }
   885  
   886  // Xor sets z = x ^ y and returns z.
   887  func (z *Int) Xor(x, y *Int) *Int {
   888  	if x.neg == y.neg {
   889  		if x.neg {
   890  			// (-x) ^ (-y) == ^(x-1) ^ ^(y-1) == (x-1) ^ (y-1)
   891  			x1 := nat(nil).sub(x.abs, natOne)
   892  			y1 := nat(nil).sub(y.abs, natOne)
   893  			z.abs = z.abs.xor(x1, y1)
   894  			z.neg = false
   895  			return z
   896  		}
   897  
   898  		// x ^ y == x ^ y
   899  		z.abs = z.abs.xor(x.abs, y.abs)
   900  		z.neg = false
   901  		return z
   902  	}
   903  
   904  	// x.neg != y.neg
   905  	if x.neg {
   906  		x, y = y, x // ^ is symmetric
   907  	}
   908  
   909  	// x ^ (-y) == x ^ ^(y-1) == ^(x ^ (y-1)) == -((x ^ (y-1)) + 1)
   910  	y1 := nat(nil).sub(y.abs, natOne)
   911  	z.abs = z.abs.add(z.abs.xor(x.abs, y1), natOne)
   912  	z.neg = true // z cannot be zero if only one of x or y is negative
   913  	return z
   914  }
   915  
   916  // Not sets z = ^x and returns z.
   917  func (z *Int) Not(x *Int) *Int {
   918  	if x.neg {
   919  		// ^(-x) == ^(^(x-1)) == x-1
   920  		z.abs = z.abs.sub(x.abs, natOne)
   921  		z.neg = false
   922  		return z
   923  	}
   924  
   925  	// ^x == -x-1 == -(x+1)
   926  	z.abs = z.abs.add(x.abs, natOne)
   927  	z.neg = true // z cannot be zero if x is positive
   928  	return z
   929  }
   930  
   931  // Sqrt sets z to ⌊√x⌋, the largest integer such that z² ≤ x, and returns z.
   932  // It panics if x is negative.
   933  func (z *Int) Sqrt(x *Int) *Int {
   934  	if x.neg {
   935  		panic("square root of negative number")
   936  	}
   937  	z.neg = false
   938  	z.abs = z.abs.sqrt(x.abs)
   939  	return z
   940  }