github.com/panjjo/go@v0.0.0-20161104043856-d62b31386338/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  // 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  	r := new(Int)
   463  	for len(B.abs) > 0 {
   464  		q, r = q.QuoRem(A, B, r)
   465  
   466  		A, B, r = B, r, A
   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  // Rand sets z to a pseudo-random number in [0, n) and returns z.
   554  func (z *Int) Rand(rnd *rand.Rand, n *Int) *Int {
   555  	z.neg = false
   556  	if n.neg == true || len(n.abs) == 0 {
   557  		z.abs = nil
   558  		return z
   559  	}
   560  	z.abs = z.abs.random(rnd, n.abs, n.abs.bitLen())
   561  	return z
   562  }
   563  
   564  // ModInverse sets z to the multiplicative inverse of g in the ring ℤ/nℤ
   565  // and returns z. If g and n are not relatively prime, the result is undefined.
   566  func (z *Int) ModInverse(g, n *Int) *Int {
   567  	if g.neg {
   568  		// GCD expects parameters a and b to be > 0.
   569  		var g2 Int
   570  		g = g2.Mod(g, n)
   571  	}
   572  	var d Int
   573  	d.GCD(z, nil, g, n)
   574  	// x and y are such that g*x + n*y = d. Since g and n are
   575  	// relatively prime, d = 1. Taking that modulo n results in
   576  	// g*x = 1, therefore x is the inverse element.
   577  	if z.neg {
   578  		z.Add(z, n)
   579  	}
   580  	return z
   581  }
   582  
   583  // Jacobi returns the Jacobi symbol (x/y), either +1, -1, or 0.
   584  // The y argument must be an odd integer.
   585  func Jacobi(x, y *Int) int {
   586  	if len(y.abs) == 0 || y.abs[0]&1 == 0 {
   587  		panic(fmt.Sprintf("big: invalid 2nd argument to Int.Jacobi: need odd integer but got %s", y))
   588  	}
   589  
   590  	// We use the formulation described in chapter 2, section 2.4,
   591  	// "The Yacas Book of Algorithms":
   592  	// http://yacas.sourceforge.net/Algo.book.pdf
   593  
   594  	var a, b, c Int
   595  	a.Set(x)
   596  	b.Set(y)
   597  	j := 1
   598  
   599  	if b.neg {
   600  		if a.neg {
   601  			j = -1
   602  		}
   603  		b.neg = false
   604  	}
   605  
   606  	for {
   607  		if b.Cmp(intOne) == 0 {
   608  			return j
   609  		}
   610  		if len(a.abs) == 0 {
   611  			return 0
   612  		}
   613  		a.Mod(&a, &b)
   614  		if len(a.abs) == 0 {
   615  			return 0
   616  		}
   617  		// a > 0
   618  
   619  		// handle factors of 2 in 'a'
   620  		s := a.abs.trailingZeroBits()
   621  		if s&1 != 0 {
   622  			bmod8 := b.abs[0] & 7
   623  			if bmod8 == 3 || bmod8 == 5 {
   624  				j = -j
   625  			}
   626  		}
   627  		c.Rsh(&a, s) // a = 2^s*c
   628  
   629  		// swap numerator and denominator
   630  		if b.abs[0]&3 == 3 && c.abs[0]&3 == 3 {
   631  			j = -j
   632  		}
   633  		a.Set(&b)
   634  		b.Set(&c)
   635  	}
   636  }
   637  
   638  // modSqrt3Mod4 uses the identity
   639  //      (a^((p+1)/4))^2  mod p
   640  //   == u^(p+1)          mod p
   641  //   == u^2              mod p
   642  // to calculate the square root of any quadratic residue mod p quickly for 3
   643  // mod 4 primes.
   644  func (z *Int) modSqrt3Mod4Prime(x, p *Int) *Int {
   645  	z.Set(p)         // z = p
   646  	z.Add(z, intOne) // z = p + 1
   647  	z.Rsh(z, 2)      // z = (p + 1) / 4
   648  	z.Exp(x, z, p)   // z = x^z mod p
   649  	return z
   650  }
   651  
   652  // modSqrtTonelliShanks uses the Tonelli-Shanks algorithm to find the square
   653  // root of a quadratic residue modulo any prime.
   654  func (z *Int) modSqrtTonelliShanks(x, p *Int) *Int {
   655  	// Break p-1 into s*2^e such that s is odd.
   656  	var s Int
   657  	s.Sub(p, intOne)
   658  	e := s.abs.trailingZeroBits()
   659  	s.Rsh(&s, e)
   660  
   661  	// find some non-square n
   662  	var n Int
   663  	n.SetInt64(2)
   664  	for Jacobi(&n, p) != -1 {
   665  		n.Add(&n, intOne)
   666  	}
   667  
   668  	// Core of the Tonelli-Shanks algorithm. Follows the description in
   669  	// section 6 of "Square roots from 1; 24, 51, 10 to Dan Shanks" by Ezra
   670  	// Brown:
   671  	// https://www.maa.org/sites/default/files/pdf/upload_library/22/Polya/07468342.di020786.02p0470a.pdf
   672  	var y, b, g, t Int
   673  	y.Add(&s, intOne)
   674  	y.Rsh(&y, 1)
   675  	y.Exp(x, &y, p)  // y = x^((s+1)/2)
   676  	b.Exp(x, &s, p)  // b = x^s
   677  	g.Exp(&n, &s, p) // g = n^s
   678  	r := e
   679  	for {
   680  		// find the least m such that ord_p(b) = 2^m
   681  		var m uint
   682  		t.Set(&b)
   683  		for t.Cmp(intOne) != 0 {
   684  			t.Mul(&t, &t).Mod(&t, p)
   685  			m++
   686  		}
   687  
   688  		if m == 0 {
   689  			return z.Set(&y)
   690  		}
   691  
   692  		t.SetInt64(0).SetBit(&t, int(r-m-1), 1).Exp(&g, &t, p)
   693  		// t = g^(2^(r-m-1)) mod p
   694  		g.Mul(&t, &t).Mod(&g, p) // g = g^(2^(r-m)) mod p
   695  		y.Mul(&y, &t).Mod(&y, p)
   696  		b.Mul(&b, &g).Mod(&b, p)
   697  		r = m
   698  	}
   699  }
   700  
   701  // ModSqrt sets z to a square root of x mod p if such a square root exists, and
   702  // returns z. The modulus p must be an odd prime. If x is not a square mod p,
   703  // ModSqrt leaves z unchanged and returns nil. This function panics if p is
   704  // not an odd integer.
   705  func (z *Int) ModSqrt(x, p *Int) *Int {
   706  	switch Jacobi(x, p) {
   707  	case -1:
   708  		return nil // x is not a square mod p
   709  	case 0:
   710  		return z.SetInt64(0) // sqrt(0) mod p = 0
   711  	case 1:
   712  		break
   713  	}
   714  	if x.neg || x.Cmp(p) >= 0 { // ensure 0 <= x < p
   715  		x = new(Int).Mod(x, p)
   716  	}
   717  
   718  	// Check whether p is 3 mod 4, and if so, use the faster algorithm.
   719  	if len(p.abs) > 0 && p.abs[0]%4 == 3 {
   720  		return z.modSqrt3Mod4Prime(x, p)
   721  	}
   722  	// Otherwise, use Tonelli-Shanks.
   723  	return z.modSqrtTonelliShanks(x, p)
   724  }
   725  
   726  // Lsh sets z = x << n and returns z.
   727  func (z *Int) Lsh(x *Int, n uint) *Int {
   728  	z.abs = z.abs.shl(x.abs, n)
   729  	z.neg = x.neg
   730  	return z
   731  }
   732  
   733  // Rsh sets z = x >> n and returns z.
   734  func (z *Int) Rsh(x *Int, n uint) *Int {
   735  	if x.neg {
   736  		// (-x) >> s == ^(x-1) >> s == ^((x-1) >> s) == -(((x-1) >> s) + 1)
   737  		t := z.abs.sub(x.abs, natOne) // no underflow because |x| > 0
   738  		t = t.shr(t, n)
   739  		z.abs = t.add(t, natOne)
   740  		z.neg = true // z cannot be zero if x is negative
   741  		return z
   742  	}
   743  
   744  	z.abs = z.abs.shr(x.abs, n)
   745  	z.neg = false
   746  	return z
   747  }
   748  
   749  // Bit returns the value of the i'th bit of x. That is, it
   750  // returns (x>>i)&1. The bit index i must be >= 0.
   751  func (x *Int) Bit(i int) uint {
   752  	if i == 0 {
   753  		// optimization for common case: odd/even test of x
   754  		if len(x.abs) > 0 {
   755  			return uint(x.abs[0] & 1) // bit 0 is same for -x
   756  		}
   757  		return 0
   758  	}
   759  	if i < 0 {
   760  		panic("negative bit index")
   761  	}
   762  	if x.neg {
   763  		t := nat(nil).sub(x.abs, natOne)
   764  		return t.bit(uint(i)) ^ 1
   765  	}
   766  
   767  	return x.abs.bit(uint(i))
   768  }
   769  
   770  // SetBit sets z to x, with x's i'th bit set to b (0 or 1).
   771  // That is, if b is 1 SetBit sets z = x | (1 << i);
   772  // if b is 0 SetBit sets z = x &^ (1 << i). If b is not 0 or 1,
   773  // SetBit will panic.
   774  func (z *Int) SetBit(x *Int, i int, b uint) *Int {
   775  	if i < 0 {
   776  		panic("negative bit index")
   777  	}
   778  	if x.neg {
   779  		t := z.abs.sub(x.abs, natOne)
   780  		t = t.setBit(t, uint(i), b^1)
   781  		z.abs = t.add(t, natOne)
   782  		z.neg = len(z.abs) > 0
   783  		return z
   784  	}
   785  	z.abs = z.abs.setBit(x.abs, uint(i), b)
   786  	z.neg = false
   787  	return z
   788  }
   789  
   790  // And sets z = x & y and returns z.
   791  func (z *Int) And(x, y *Int) *Int {
   792  	if x.neg == y.neg {
   793  		if x.neg {
   794  			// (-x) & (-y) == ^(x-1) & ^(y-1) == ^((x-1) | (y-1)) == -(((x-1) | (y-1)) + 1)
   795  			x1 := nat(nil).sub(x.abs, natOne)
   796  			y1 := nat(nil).sub(y.abs, natOne)
   797  			z.abs = z.abs.add(z.abs.or(x1, y1), natOne)
   798  			z.neg = true // z cannot be zero if x and y are negative
   799  			return z
   800  		}
   801  
   802  		// x & y == x & y
   803  		z.abs = z.abs.and(x.abs, y.abs)
   804  		z.neg = false
   805  		return z
   806  	}
   807  
   808  	// x.neg != y.neg
   809  	if x.neg {
   810  		x, y = y, x // & is symmetric
   811  	}
   812  
   813  	// x & (-y) == x & ^(y-1) == x &^ (y-1)
   814  	y1 := nat(nil).sub(y.abs, natOne)
   815  	z.abs = z.abs.andNot(x.abs, y1)
   816  	z.neg = false
   817  	return z
   818  }
   819  
   820  // AndNot sets z = x &^ y and returns z.
   821  func (z *Int) AndNot(x, y *Int) *Int {
   822  	if x.neg == y.neg {
   823  		if x.neg {
   824  			// (-x) &^ (-y) == ^(x-1) &^ ^(y-1) == ^(x-1) & (y-1) == (y-1) &^ (x-1)
   825  			x1 := nat(nil).sub(x.abs, natOne)
   826  			y1 := nat(nil).sub(y.abs, natOne)
   827  			z.abs = z.abs.andNot(y1, x1)
   828  			z.neg = false
   829  			return z
   830  		}
   831  
   832  		// x &^ y == x &^ y
   833  		z.abs = z.abs.andNot(x.abs, y.abs)
   834  		z.neg = false
   835  		return z
   836  	}
   837  
   838  	if x.neg {
   839  		// (-x) &^ y == ^(x-1) &^ y == ^(x-1) & ^y == ^((x-1) | y) == -(((x-1) | y) + 1)
   840  		x1 := nat(nil).sub(x.abs, natOne)
   841  		z.abs = z.abs.add(z.abs.or(x1, y.abs), natOne)
   842  		z.neg = true // z cannot be zero if x is negative and y is positive
   843  		return z
   844  	}
   845  
   846  	// x &^ (-y) == x &^ ^(y-1) == x & (y-1)
   847  	y1 := nat(nil).sub(y.abs, natOne)
   848  	z.abs = z.abs.and(x.abs, y1)
   849  	z.neg = false
   850  	return z
   851  }
   852  
   853  // Or sets z = x | y and returns z.
   854  func (z *Int) Or(x, y *Int) *Int {
   855  	if x.neg == y.neg {
   856  		if x.neg {
   857  			// (-x) | (-y) == ^(x-1) | ^(y-1) == ^((x-1) & (y-1)) == -(((x-1) & (y-1)) + 1)
   858  			x1 := nat(nil).sub(x.abs, natOne)
   859  			y1 := nat(nil).sub(y.abs, natOne)
   860  			z.abs = z.abs.add(z.abs.and(x1, y1), natOne)
   861  			z.neg = true // z cannot be zero if x and y are negative
   862  			return z
   863  		}
   864  
   865  		// x | y == x | y
   866  		z.abs = z.abs.or(x.abs, y.abs)
   867  		z.neg = false
   868  		return z
   869  	}
   870  
   871  	// x.neg != y.neg
   872  	if x.neg {
   873  		x, y = y, x // | is symmetric
   874  	}
   875  
   876  	// x | (-y) == x | ^(y-1) == ^((y-1) &^ x) == -(^((y-1) &^ x) + 1)
   877  	y1 := nat(nil).sub(y.abs, natOne)
   878  	z.abs = z.abs.add(z.abs.andNot(y1, x.abs), natOne)
   879  	z.neg = true // z cannot be zero if one of x or y is negative
   880  	return z
   881  }
   882  
   883  // Xor sets z = x ^ y and returns z.
   884  func (z *Int) Xor(x, y *Int) *Int {
   885  	if x.neg == y.neg {
   886  		if x.neg {
   887  			// (-x) ^ (-y) == ^(x-1) ^ ^(y-1) == (x-1) ^ (y-1)
   888  			x1 := nat(nil).sub(x.abs, natOne)
   889  			y1 := nat(nil).sub(y.abs, natOne)
   890  			z.abs = z.abs.xor(x1, y1)
   891  			z.neg = false
   892  			return z
   893  		}
   894  
   895  		// x ^ y == x ^ y
   896  		z.abs = z.abs.xor(x.abs, y.abs)
   897  		z.neg = false
   898  		return z
   899  	}
   900  
   901  	// x.neg != y.neg
   902  	if x.neg {
   903  		x, y = y, x // ^ is symmetric
   904  	}
   905  
   906  	// x ^ (-y) == x ^ ^(y-1) == ^(x ^ (y-1)) == -((x ^ (y-1)) + 1)
   907  	y1 := nat(nil).sub(y.abs, natOne)
   908  	z.abs = z.abs.add(z.abs.xor(x.abs, y1), natOne)
   909  	z.neg = true // z cannot be zero if only one of x or y is negative
   910  	return z
   911  }
   912  
   913  // Not sets z = ^x and returns z.
   914  func (z *Int) Not(x *Int) *Int {
   915  	if x.neg {
   916  		// ^(-x) == ^(^(x-1)) == x-1
   917  		z.abs = z.abs.sub(x.abs, natOne)
   918  		z.neg = false
   919  		return z
   920  	}
   921  
   922  	// ^x == -x-1 == -(x+1)
   923  	z.abs = z.abs.add(x.abs, natOne)
   924  	z.neg = true // z cannot be zero if x is positive
   925  	return z
   926  }
   927  
   928  // Sqrt sets z to ⌊√x⌋, the largest integer such that z² ≤ x, and returns z.
   929  // It panics if x is negative.
   930  func (z *Int) Sqrt(x *Int) *Int {
   931  	if x.neg {
   932  		panic("square root of negative number")
   933  	}
   934  	z.neg = false
   935  	z.abs = z.abs.sqrt(x.abs)
   936  	return z
   937  }