Source file src/math/big/int.go

     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  //
    19  // Operations always take pointer arguments (*Int) rather
    20  // than Int values, and each unique Int value requires
    21  // its own unique *Int pointer. To "copy" an Int value,
    22  // an existing (or newly allocated) Int must be set to
    23  // a new value using the Int.Set method; shallow copies
    24  // of Ints are not supported and may lead to errors.
    25  type Int struct {
    26  	neg bool // sign
    27  	abs nat  // absolute value of the integer
    28  }
    29  
    30  var intOne = &Int{false, natOne}
    31  
    32  // Sign returns:
    33  //
    34  //	-1 if x <  0
    35  //	 0 if x == 0
    36  //	+1 if x >  0
    37  func (x *Int) Sign() int {
    38  	// This function is used in cryptographic operations. It must not leak
    39  	// anything but the Int's sign and bit size through side-channels. Any
    40  	// changes must be reviewed by a security expert.
    41  	if len(x.abs) == 0 {
    42  		return 0
    43  	}
    44  	if x.neg {
    45  		return -1
    46  	}
    47  	return 1
    48  }
    49  
    50  // SetInt64 sets z to x and returns z.
    51  func (z *Int) SetInt64(x int64) *Int {
    52  	neg := false
    53  	if x < 0 {
    54  		neg = true
    55  		x = -x
    56  	}
    57  	z.abs = z.abs.setUint64(uint64(x))
    58  	z.neg = neg
    59  	return z
    60  }
    61  
    62  // SetUint64 sets z to x and returns z.
    63  func (z *Int) SetUint64(x uint64) *Int {
    64  	z.abs = z.abs.setUint64(x)
    65  	z.neg = false
    66  	return z
    67  }
    68  
    69  // NewInt allocates and returns a new Int set to x.
    70  func NewInt(x int64) *Int {
    71  	// This code is arranged to be inlineable and produce
    72  	// zero allocations when inlined. See issue 29951.
    73  	u := uint64(x)
    74  	if x < 0 {
    75  		u = -u
    76  	}
    77  	var abs []Word
    78  	if x == 0 {
    79  	} else if _W == 32 && u>>32 != 0 {
    80  		abs = []Word{Word(u), Word(u >> 32)}
    81  	} else {
    82  		abs = []Word{Word(u)}
    83  	}
    84  	return &Int{neg: x < 0, abs: abs}
    85  }
    86  
    87  // Set sets z to x and returns z.
    88  func (z *Int) Set(x *Int) *Int {
    89  	if z != x {
    90  		z.abs = z.abs.set(x.abs)
    91  		z.neg = x.neg
    92  	}
    93  	return z
    94  }
    95  
    96  // Bits provides raw (unchecked but fast) access to x by returning its
    97  // absolute value as a little-endian Word slice. The result and x share
    98  // the same underlying array.
    99  // Bits is intended to support implementation of missing low-level Int
   100  // functionality outside this package; it should be avoided otherwise.
   101  func (x *Int) Bits() []Word {
   102  	// This function is used in cryptographic operations. It must not leak
   103  	// anything but the Int's sign and bit size through side-channels. Any
   104  	// changes must be reviewed by a security expert.
   105  	return x.abs
   106  }
   107  
   108  // SetBits provides raw (unchecked but fast) access to z by setting its
   109  // value to abs, interpreted as a little-endian Word slice, and returning
   110  // z. The result and abs share the same underlying array.
   111  // SetBits is intended to support implementation of missing low-level Int
   112  // functionality outside this package; it should be avoided otherwise.
   113  func (z *Int) SetBits(abs []Word) *Int {
   114  	z.abs = nat(abs).norm()
   115  	z.neg = false
   116  	return z
   117  }
   118  
   119  // Abs sets z to |x| (the absolute value of x) and returns z.
   120  func (z *Int) Abs(x *Int) *Int {
   121  	z.Set(x)
   122  	z.neg = false
   123  	return z
   124  }
   125  
   126  // Neg sets z to -x and returns z.
   127  func (z *Int) Neg(x *Int) *Int {
   128  	z.Set(x)
   129  	z.neg = len(z.abs) > 0 && !z.neg // 0 has no sign
   130  	return z
   131  }
   132  
   133  // Add sets z to the sum x+y and returns z.
   134  func (z *Int) Add(x, y *Int) *Int {
   135  	neg := x.neg
   136  	if x.neg == y.neg {
   137  		// x + y == x + y
   138  		// (-x) + (-y) == -(x + y)
   139  		z.abs = z.abs.add(x.abs, y.abs)
   140  	} else {
   141  		// x + (-y) == x - y == -(y - x)
   142  		// (-x) + y == y - x == -(x - y)
   143  		if x.abs.cmp(y.abs) >= 0 {
   144  			z.abs = z.abs.sub(x.abs, y.abs)
   145  		} else {
   146  			neg = !neg
   147  			z.abs = z.abs.sub(y.abs, x.abs)
   148  		}
   149  	}
   150  	z.neg = len(z.abs) > 0 && neg // 0 has no sign
   151  	return z
   152  }
   153  
   154  // Sub sets z to the difference x-y and returns z.
   155  func (z *Int) Sub(x, y *Int) *Int {
   156  	neg := x.neg
   157  	if x.neg != y.neg {
   158  		// x - (-y) == x + y
   159  		// (-x) - y == -(x + y)
   160  		z.abs = z.abs.add(x.abs, y.abs)
   161  	} else {
   162  		// x - y == x - y == -(y - x)
   163  		// (-x) - (-y) == y - x == -(x - y)
   164  		if x.abs.cmp(y.abs) >= 0 {
   165  			z.abs = z.abs.sub(x.abs, y.abs)
   166  		} else {
   167  			neg = !neg
   168  			z.abs = z.abs.sub(y.abs, x.abs)
   169  		}
   170  	}
   171  	z.neg = len(z.abs) > 0 && neg // 0 has no sign
   172  	return z
   173  }
   174  
   175  // Mul sets z to the product x*y and returns z.
   176  func (z *Int) Mul(x, y *Int) *Int {
   177  	// x * y == x * y
   178  	// x * (-y) == -(x * y)
   179  	// (-x) * y == -(x * y)
   180  	// (-x) * (-y) == x * y
   181  	if x == y {
   182  		z.abs = z.abs.sqr(x.abs)
   183  		z.neg = false
   184  		return z
   185  	}
   186  	z.abs = z.abs.mul(x.abs, y.abs)
   187  	z.neg = len(z.abs) > 0 && x.neg != y.neg // 0 has no sign
   188  	return z
   189  }
   190  
   191  // MulRange sets z to the product of all integers
   192  // in the range [a, b] inclusively and returns z.
   193  // If a > b (empty range), the result is 1.
   194  func (z *Int) MulRange(a, b int64) *Int {
   195  	switch {
   196  	case a > b:
   197  		return z.SetInt64(1) // empty range
   198  	case a <= 0 && b >= 0:
   199  		return z.SetInt64(0) // range includes 0
   200  	}
   201  	// a <= b && (b < 0 || a > 0)
   202  
   203  	neg := false
   204  	if a < 0 {
   205  		neg = (b-a)&1 == 0
   206  		a, b = -b, -a
   207  	}
   208  
   209  	z.abs = z.abs.mulRange(uint64(a), uint64(b))
   210  	z.neg = neg
   211  	return z
   212  }
   213  
   214  // Binomial sets z to the binomial coefficient C(n, k) and returns z.
   215  func (z *Int) Binomial(n, k int64) *Int {
   216  	if k > n {
   217  		return z.SetInt64(0)
   218  	}
   219  	// reduce the number of multiplications by reducing k
   220  	if k > n-k {
   221  		k = n - k // C(n, k) == C(n, n-k)
   222  	}
   223  	// C(n, k) == n * (n-1) * ... * (n-k+1) / k * (k-1) * ... * 1
   224  	//         == n * (n-1) * ... * (n-k+1) / 1 * (1+1) * ... * k
   225  	//
   226  	// Using the multiplicative formula produces smaller values
   227  	// at each step, requiring fewer allocations and computations:
   228  	//
   229  	// z = 1
   230  	// for i := 0; i < k; i = i+1 {
   231  	//     z *= n-i
   232  	//     z /= i+1
   233  	// }
   234  	//
   235  	// finally to avoid computing i+1 twice per loop:
   236  	//
   237  	// z = 1
   238  	// i := 0
   239  	// for i < k {
   240  	//     z *= n-i
   241  	//     i++
   242  	//     z /= i
   243  	// }
   244  	var N, K, i, t Int
   245  	N.SetInt64(n)
   246  	K.SetInt64(k)
   247  	z.Set(intOne)
   248  	for i.Cmp(&K) < 0 {
   249  		z.Mul(z, t.Sub(&N, &i))
   250  		i.Add(&i, intOne)
   251  		z.Quo(z, &i)
   252  	}
   253  	return z
   254  }
   255  
   256  // Quo sets z to the quotient x/y for y != 0 and returns z.
   257  // If y == 0, a division-by-zero run-time panic occurs.
   258  // Quo implements truncated division (like Go); see QuoRem for more details.
   259  func (z *Int) Quo(x, y *Int) *Int {
   260  	z.abs, _ = z.abs.div(nil, x.abs, y.abs)
   261  	z.neg = len(z.abs) > 0 && x.neg != y.neg // 0 has no sign
   262  	return z
   263  }
   264  
   265  // Rem sets z to the remainder x%y for y != 0 and returns z.
   266  // If y == 0, a division-by-zero run-time panic occurs.
   267  // Rem implements truncated modulus (like Go); see QuoRem for more details.
   268  func (z *Int) Rem(x, y *Int) *Int {
   269  	_, z.abs = nat(nil).div(z.abs, x.abs, y.abs)
   270  	z.neg = len(z.abs) > 0 && x.neg // 0 has no sign
   271  	return z
   272  }
   273  
   274  // QuoRem sets z to the quotient x/y and r to the remainder x%y
   275  // and returns the pair (z, r) for y != 0.
   276  // If y == 0, a division-by-zero run-time panic occurs.
   277  //
   278  // QuoRem implements T-division and modulus (like Go):
   279  //
   280  //	q = x/y      with the result truncated to zero
   281  //	r = x - y*q
   282  //
   283  // (See Daan Leijen, “Division and Modulus for Computer Scientists”.)
   284  // See DivMod for Euclidean division and modulus (unlike Go).
   285  func (z *Int) QuoRem(x, y, r *Int) (*Int, *Int) {
   286  	z.abs, r.abs = z.abs.div(r.abs, x.abs, y.abs)
   287  	z.neg, r.neg = len(z.abs) > 0 && x.neg != y.neg, len(r.abs) > 0 && x.neg // 0 has no sign
   288  	return z, r
   289  }
   290  
   291  // Div sets z to the quotient x/y for y != 0 and returns z.
   292  // If y == 0, a division-by-zero run-time panic occurs.
   293  // Div implements Euclidean division (unlike Go); see DivMod for more details.
   294  func (z *Int) Div(x, y *Int) *Int {
   295  	y_neg := y.neg // z may be an alias for y
   296  	var r Int
   297  	z.QuoRem(x, y, &r)
   298  	if r.neg {
   299  		if y_neg {
   300  			z.Add(z, intOne)
   301  		} else {
   302  			z.Sub(z, intOne)
   303  		}
   304  	}
   305  	return z
   306  }
   307  
   308  // Mod sets z to the modulus x%y for y != 0 and returns z.
   309  // If y == 0, a division-by-zero run-time panic occurs.
   310  // Mod implements Euclidean modulus (unlike Go); see DivMod for more details.
   311  func (z *Int) Mod(x, y *Int) *Int {
   312  	y0 := y // save y
   313  	if z == y || alias(z.abs, y.abs) {
   314  		y0 = new(Int).Set(y)
   315  	}
   316  	var q Int
   317  	q.QuoRem(x, y, z)
   318  	if z.neg {
   319  		if y0.neg {
   320  			z.Sub(z, y0)
   321  		} else {
   322  			z.Add(z, y0)
   323  		}
   324  	}
   325  	return z
   326  }
   327  
   328  // DivMod sets z to the quotient x div y and m to the modulus x mod y
   329  // and returns the pair (z, m) for y != 0.
   330  // If y == 0, a division-by-zero run-time panic occurs.
   331  //
   332  // DivMod implements Euclidean division and modulus (unlike Go):
   333  //
   334  //	q = x div y  such that
   335  //	m = x - y*q  with 0 <= m < |y|
   336  //
   337  // (See Raymond T. Boute, “The Euclidean definition of the functions
   338  // div and mod”. ACM Transactions on Programming Languages and
   339  // Systems (TOPLAS), 14(2):127-144, New York, NY, USA, 4/1992.
   340  // ACM press.)
   341  // See QuoRem for T-division and modulus (like Go).
   342  func (z *Int) DivMod(x, y, m *Int) (*Int, *Int) {
   343  	y0 := y // save y
   344  	if z == y || alias(z.abs, y.abs) {
   345  		y0 = new(Int).Set(y)
   346  	}
   347  	z.QuoRem(x, y, m)
   348  	if m.neg {
   349  		if y0.neg {
   350  			z.Add(z, intOne)
   351  			m.Sub(m, y0)
   352  		} else {
   353  			z.Sub(z, intOne)
   354  			m.Add(m, y0)
   355  		}
   356  	}
   357  	return z, m
   358  }
   359  
   360  // Cmp compares x and y and returns:
   361  //
   362  //	-1 if x <  y
   363  //	 0 if x == y
   364  //	+1 if x >  y
   365  func (x *Int) Cmp(y *Int) (r int) {
   366  	// x cmp y == x cmp y
   367  	// x cmp (-y) == x
   368  	// (-x) cmp y == y
   369  	// (-x) cmp (-y) == -(x cmp y)
   370  	switch {
   371  	case x == y:
   372  		// nothing to do
   373  	case x.neg == y.neg:
   374  		r = x.abs.cmp(y.abs)
   375  		if x.neg {
   376  			r = -r
   377  		}
   378  	case x.neg:
   379  		r = -1
   380  	default:
   381  		r = 1
   382  	}
   383  	return
   384  }
   385  
   386  // CmpAbs compares the absolute values of x and y and returns:
   387  //
   388  //	-1 if |x| <  |y|
   389  //	 0 if |x| == |y|
   390  //	+1 if |x| >  |y|
   391  func (x *Int) CmpAbs(y *Int) int {
   392  	return x.abs.cmp(y.abs)
   393  }
   394  
   395  // low32 returns the least significant 32 bits of x.
   396  func low32(x nat) uint32 {
   397  	if len(x) == 0 {
   398  		return 0
   399  	}
   400  	return uint32(x[0])
   401  }
   402  
   403  // low64 returns the least significant 64 bits of x.
   404  func low64(x nat) uint64 {
   405  	if len(x) == 0 {
   406  		return 0
   407  	}
   408  	v := uint64(x[0])
   409  	if _W == 32 && len(x) > 1 {
   410  		return uint64(x[1])<<32 | v
   411  	}
   412  	return v
   413  }
   414  
   415  // Int64 returns the int64 representation of x.
   416  // If x cannot be represented in an int64, the result is undefined.
   417  func (x *Int) Int64() int64 {
   418  	v := int64(low64(x.abs))
   419  	if x.neg {
   420  		v = -v
   421  	}
   422  	return v
   423  }
   424  
   425  // Uint64 returns the uint64 representation of x.
   426  // If x cannot be represented in a uint64, the result is undefined.
   427  func (x *Int) Uint64() uint64 {
   428  	return low64(x.abs)
   429  }
   430  
   431  // IsInt64 reports whether x can be represented as an int64.
   432  func (x *Int) IsInt64() bool {
   433  	if len(x.abs) <= 64/_W {
   434  		w := int64(low64(x.abs))
   435  		return w >= 0 || x.neg && w == -w
   436  	}
   437  	return false
   438  }
   439  
   440  // IsUint64 reports whether x can be represented as a uint64.
   441  func (x *Int) IsUint64() bool {
   442  	return !x.neg && len(x.abs) <= 64/_W
   443  }
   444  
   445  // SetString sets z to the value of s, interpreted in the given base,
   446  // and returns z and a boolean indicating success. The entire string
   447  // (not just a prefix) must be valid for success. If SetString fails,
   448  // the value of z is undefined but the returned value is nil.
   449  //
   450  // The base argument must be 0 or a value between 2 and MaxBase.
   451  // For base 0, the number prefix determines the actual base: A prefix of
   452  // “0b” or “0B” selects base 2, “0”, “0o” or “0O” selects base 8,
   453  // and “0x” or “0X” selects base 16. Otherwise, the selected base is 10
   454  // and no prefix is accepted.
   455  //
   456  // For bases <= 36, lower and upper case letters are considered the same:
   457  // The letters 'a' to 'z' and 'A' to 'Z' represent digit values 10 to 35.
   458  // For bases > 36, the upper case letters 'A' to 'Z' represent the digit
   459  // values 36 to 61.
   460  //
   461  // For base 0, an underscore character “_” may appear between a base
   462  // prefix and an adjacent digit, and between successive digits; such
   463  // underscores do not change the value of the number.
   464  // Incorrect placement of underscores is reported as an error if there
   465  // are no other errors. If base != 0, underscores are not recognized
   466  // and act like any other character that is not a valid digit.
   467  func (z *Int) SetString(s string, base int) (*Int, bool) {
   468  	return z.setFromScanner(strings.NewReader(s), base)
   469  }
   470  
   471  // setFromScanner implements SetString given an io.ByteScanner.
   472  // For documentation see comments of SetString.
   473  func (z *Int) setFromScanner(r io.ByteScanner, base int) (*Int, bool) {
   474  	if _, _, err := z.scan(r, base); err != nil {
   475  		return nil, false
   476  	}
   477  	// entire content must have been consumed
   478  	if _, err := r.ReadByte(); err != io.EOF {
   479  		return nil, false
   480  	}
   481  	return z, true // err == io.EOF => scan consumed all content of r
   482  }
   483  
   484  // SetBytes interprets buf as the bytes of a big-endian unsigned
   485  // integer, sets z to that value, and returns z.
   486  func (z *Int) SetBytes(buf []byte) *Int {
   487  	z.abs = z.abs.setBytes(buf)
   488  	z.neg = false
   489  	return z
   490  }
   491  
   492  // Bytes returns the absolute value of x as a big-endian byte slice.
   493  //
   494  // To use a fixed length slice, or a preallocated one, use FillBytes.
   495  func (x *Int) Bytes() []byte {
   496  	// This function is used in cryptographic operations. It must not leak
   497  	// anything but the Int's sign and bit size through side-channels. Any
   498  	// changes must be reviewed by a security expert.
   499  	buf := make([]byte, len(x.abs)*_S)
   500  	return buf[x.abs.bytes(buf):]
   501  }
   502  
   503  // FillBytes sets buf to the absolute value of x, storing it as a zero-extended
   504  // big-endian byte slice, and returns buf.
   505  //
   506  // If the absolute value of x doesn't fit in buf, FillBytes will panic.
   507  func (x *Int) FillBytes(buf []byte) []byte {
   508  	// Clear whole buffer. (This gets optimized into a memclr.)
   509  	for i := range buf {
   510  		buf[i] = 0
   511  	}
   512  	x.abs.bytes(buf)
   513  	return buf
   514  }
   515  
   516  // BitLen returns the length of the absolute value of x in bits.
   517  // The bit length of 0 is 0.
   518  func (x *Int) BitLen() int {
   519  	// This function is used in cryptographic operations. It must not leak
   520  	// anything but the Int's sign and bit size through side-channels. Any
   521  	// changes must be reviewed by a security expert.
   522  	return x.abs.bitLen()
   523  }
   524  
   525  // TrailingZeroBits returns the number of consecutive least significant zero
   526  // bits of |x|.
   527  func (x *Int) TrailingZeroBits() uint {
   528  	return x.abs.trailingZeroBits()
   529  }
   530  
   531  // Exp sets z = x**y mod |m| (i.e. the sign of m is ignored), and returns z.
   532  // If m == nil or m == 0, z = x**y unless y <= 0 then z = 1. If m != 0, y < 0,
   533  // and x and m are not relatively prime, z is unchanged and nil is returned.
   534  //
   535  // Modular exponentiation of inputs of a particular size is not a
   536  // cryptographically constant-time operation.
   537  func (z *Int) Exp(x, y, m *Int) *Int {
   538  	return z.exp(x, y, m, false)
   539  }
   540  
   541  func (z *Int) expSlow(x, y, m *Int) *Int {
   542  	return z.exp(x, y, m, true)
   543  }
   544  
   545  func (z *Int) exp(x, y, m *Int, slow bool) *Int {
   546  	// See Knuth, volume 2, section 4.6.3.
   547  	xWords := x.abs
   548  	if y.neg {
   549  		if m == nil || len(m.abs) == 0 {
   550  			return z.SetInt64(1)
   551  		}
   552  		// for y < 0: x**y mod m == (x**(-1))**|y| mod m
   553  		inverse := new(Int).ModInverse(x, m)
   554  		if inverse == nil {
   555  			return nil
   556  		}
   557  		xWords = inverse.abs
   558  	}
   559  	yWords := y.abs
   560  
   561  	var mWords nat
   562  	if m != nil {
   563  		if z == m || alias(z.abs, m.abs) {
   564  			m = new(Int).Set(m)
   565  		}
   566  		mWords = m.abs // m.abs may be nil for m == 0
   567  	}
   568  
   569  	z.abs = z.abs.expNN(xWords, yWords, mWords, slow)
   570  	z.neg = len(z.abs) > 0 && x.neg && len(yWords) > 0 && yWords[0]&1 == 1 // 0 has no sign
   571  	if z.neg && len(mWords) > 0 {
   572  		// make modulus result positive
   573  		z.abs = z.abs.sub(mWords, z.abs) // z == x**y mod |m| && 0 <= z < |m|
   574  		z.neg = false
   575  	}
   576  
   577  	return z
   578  }
   579  
   580  // GCD sets z to the greatest common divisor of a and b and returns z.
   581  // If x or y are not nil, GCD sets their value such that z = a*x + b*y.
   582  //
   583  // a and b may be positive, zero or negative. (Before Go 1.14 both had
   584  // to be > 0.) Regardless of the signs of a and b, z is always >= 0.
   585  //
   586  // If a == b == 0, GCD sets z = x = y = 0.
   587  //
   588  // If a == 0 and b != 0, GCD sets z = |b|, x = 0, y = sign(b) * 1.
   589  //
   590  // If a != 0 and b == 0, GCD sets z = |a|, x = sign(a) * 1, y = 0.
   591  func (z *Int) GCD(x, y, a, b *Int) *Int {
   592  	if len(a.abs) == 0 || len(b.abs) == 0 {
   593  		lenA, lenB, negA, negB := len(a.abs), len(b.abs), a.neg, b.neg
   594  		if lenA == 0 {
   595  			z.Set(b)
   596  		} else {
   597  			z.Set(a)
   598  		}
   599  		z.neg = false
   600  		if x != nil {
   601  			if lenA == 0 {
   602  				x.SetUint64(0)
   603  			} else {
   604  				x.SetUint64(1)
   605  				x.neg = negA
   606  			}
   607  		}
   608  		if y != nil {
   609  			if lenB == 0 {
   610  				y.SetUint64(0)
   611  			} else {
   612  				y.SetUint64(1)
   613  				y.neg = negB
   614  			}
   615  		}
   616  		return z
   617  	}
   618  
   619  	return z.lehmerGCD(x, y, a, b)
   620  }
   621  
   622  // lehmerSimulate attempts to simulate several Euclidean update steps
   623  // using the leading digits of A and B.  It returns u0, u1, v0, v1
   624  // such that A and B can be updated as:
   625  //
   626  //	A = u0*A + v0*B
   627  //	B = u1*A + v1*B
   628  //
   629  // Requirements: A >= B and len(B.abs) >= 2
   630  // Since we are calculating with full words to avoid overflow,
   631  // we use 'even' to track the sign of the cosequences.
   632  // For even iterations: u0, v1 >= 0 && u1, v0 <= 0
   633  // For odd  iterations: u0, v1 <= 0 && u1, v0 >= 0
   634  func lehmerSimulate(A, B *Int) (u0, u1, v0, v1 Word, even bool) {
   635  	// initialize the digits
   636  	var a1, a2, u2, v2 Word
   637  
   638  	m := len(B.abs) // m >= 2
   639  	n := len(A.abs) // n >= m >= 2
   640  
   641  	// extract the top Word of bits from A and B
   642  	h := nlz(A.abs[n-1])
   643  	a1 = A.abs[n-1]<<h | A.abs[n-2]>>(_W-h)
   644  	// B may have implicit zero words in the high bits if the lengths differ
   645  	switch {
   646  	case n == m:
   647  		a2 = B.abs[n-1]<<h | B.abs[n-2]>>(_W-h)
   648  	case n == m+1:
   649  		a2 = B.abs[n-2] >> (_W - h)
   650  	default:
   651  		a2 = 0
   652  	}
   653  
   654  	// Since we are calculating with full words to avoid overflow,
   655  	// we use 'even' to track the sign of the cosequences.
   656  	// For even iterations: u0, v1 >= 0 && u1, v0 <= 0
   657  	// For odd  iterations: u0, v1 <= 0 && u1, v0 >= 0
   658  	// The first iteration starts with k=1 (odd).
   659  	even = false
   660  	// variables to track the cosequences
   661  	u0, u1, u2 = 0, 1, 0
   662  	v0, v1, v2 = 0, 0, 1
   663  
   664  	// Calculate the quotient and cosequences using Collins' stopping condition.
   665  	// Note that overflow of a Word is not possible when computing the remainder
   666  	// sequence and cosequences since the cosequence size is bounded by the input size.
   667  	// See section 4.2 of Jebelean for details.
   668  	for a2 >= v2 && a1-a2 >= v1+v2 {
   669  		q, r := a1/a2, a1%a2
   670  		a1, a2 = a2, r
   671  		u0, u1, u2 = u1, u2, u1+q*u2
   672  		v0, v1, v2 = v1, v2, v1+q*v2
   673  		even = !even
   674  	}
   675  	return
   676  }
   677  
   678  // lehmerUpdate updates the inputs A and B such that:
   679  //
   680  //	A = u0*A + v0*B
   681  //	B = u1*A + v1*B
   682  //
   683  // where the signs of u0, u1, v0, v1 are given by even
   684  // For even == true: u0, v1 >= 0 && u1, v0 <= 0
   685  // For even == false: u0, v1 <= 0 && u1, v0 >= 0
   686  // q, r, s, t are temporary variables to avoid allocations in the multiplication.
   687  func lehmerUpdate(A, B, q, r, s, t *Int, u0, u1, v0, v1 Word, even bool) {
   688  
   689  	t.abs = t.abs.setWord(u0)
   690  	s.abs = s.abs.setWord(v0)
   691  	t.neg = !even
   692  	s.neg = even
   693  
   694  	t.Mul(A, t)
   695  	s.Mul(B, s)
   696  
   697  	r.abs = r.abs.setWord(u1)
   698  	q.abs = q.abs.setWord(v1)
   699  	r.neg = even
   700  	q.neg = !even
   701  
   702  	r.Mul(A, r)
   703  	q.Mul(B, q)
   704  
   705  	A.Add(t, s)
   706  	B.Add(r, q)
   707  }
   708  
   709  // euclidUpdate performs a single step of the Euclidean GCD algorithm
   710  // if extended is true, it also updates the cosequence Ua, Ub.
   711  func euclidUpdate(A, B, Ua, Ub, q, r, s, t *Int, extended bool) {
   712  	q, r = q.QuoRem(A, B, r)
   713  
   714  	*A, *B, *r = *B, *r, *A
   715  
   716  	if extended {
   717  		// Ua, Ub = Ub, Ua - q*Ub
   718  		t.Set(Ub)
   719  		s.Mul(Ub, q)
   720  		Ub.Sub(Ua, s)
   721  		Ua.Set(t)
   722  	}
   723  }
   724  
   725  // lehmerGCD sets z to the greatest common divisor of a and b,
   726  // which both must be != 0, and returns z.
   727  // If x or y are not nil, their values are set such that z = a*x + b*y.
   728  // See Knuth, The Art of Computer Programming, Vol. 2, Section 4.5.2, Algorithm L.
   729  // This implementation uses the improved condition by Collins requiring only one
   730  // quotient and avoiding the possibility of single Word overflow.
   731  // See Jebelean, "Improving the multiprecision Euclidean algorithm",
   732  // Design and Implementation of Symbolic Computation Systems, pp 45-58.
   733  // The cosequences are updated according to Algorithm 10.45 from
   734  // Cohen et al. "Handbook of Elliptic and Hyperelliptic Curve Cryptography" pp 192.
   735  func (z *Int) lehmerGCD(x, y, a, b *Int) *Int {
   736  	var A, B, Ua, Ub *Int
   737  
   738  	A = new(Int).Abs(a)
   739  	B = new(Int).Abs(b)
   740  
   741  	extended := x != nil || y != nil
   742  
   743  	if extended {
   744  		// Ua (Ub) tracks how many times input a has been accumulated into A (B).
   745  		Ua = new(Int).SetInt64(1)
   746  		Ub = new(Int)
   747  	}
   748  
   749  	// temp variables for multiprecision update
   750  	q := new(Int)
   751  	r := new(Int)
   752  	s := new(Int)
   753  	t := new(Int)
   754  
   755  	// ensure A >= B
   756  	if A.abs.cmp(B.abs) < 0 {
   757  		A, B = B, A
   758  		Ub, Ua = Ua, Ub
   759  	}
   760  
   761  	// loop invariant A >= B
   762  	for len(B.abs) > 1 {
   763  		// Attempt to calculate in single-precision using leading words of A and B.
   764  		u0, u1, v0, v1, even := lehmerSimulate(A, B)
   765  
   766  		// multiprecision Step
   767  		if v0 != 0 {
   768  			// Simulate the effect of the single-precision steps using the cosequences.
   769  			// A = u0*A + v0*B
   770  			// B = u1*A + v1*B
   771  			lehmerUpdate(A, B, q, r, s, t, u0, u1, v0, v1, even)
   772  
   773  			if extended {
   774  				// Ua = u0*Ua + v0*Ub
   775  				// Ub = u1*Ua + v1*Ub
   776  				lehmerUpdate(Ua, Ub, q, r, s, t, u0, u1, v0, v1, even)
   777  			}
   778  
   779  		} else {
   780  			// Single-digit calculations failed to simulate any quotients.
   781  			// Do a standard Euclidean step.
   782  			euclidUpdate(A, B, Ua, Ub, q, r, s, t, extended)
   783  		}
   784  	}
   785  
   786  	if len(B.abs) > 0 {
   787  		// extended Euclidean algorithm base case if B is a single Word
   788  		if len(A.abs) > 1 {
   789  			// A is longer than a single Word, so one update is needed.
   790  			euclidUpdate(A, B, Ua, Ub, q, r, s, t, extended)
   791  		}
   792  		if len(B.abs) > 0 {
   793  			// A and B are both a single Word.
   794  			aWord, bWord := A.abs[0], B.abs[0]
   795  			if extended {
   796  				var ua, ub, va, vb Word
   797  				ua, ub = 1, 0
   798  				va, vb = 0, 1
   799  				even := true
   800  				for bWord != 0 {
   801  					q, r := aWord/bWord, aWord%bWord
   802  					aWord, bWord = bWord, r
   803  					ua, ub = ub, ua+q*ub
   804  					va, vb = vb, va+q*vb
   805  					even = !even
   806  				}
   807  
   808  				t.abs = t.abs.setWord(ua)
   809  				s.abs = s.abs.setWord(va)
   810  				t.neg = !even
   811  				s.neg = even
   812  
   813  				t.Mul(Ua, t)
   814  				s.Mul(Ub, s)
   815  
   816  				Ua.Add(t, s)
   817  			} else {
   818  				for bWord != 0 {
   819  					aWord, bWord = bWord, aWord%bWord
   820  				}
   821  			}
   822  			A.abs[0] = aWord
   823  		}
   824  	}
   825  	negA := a.neg
   826  	if y != nil {
   827  		// avoid aliasing b needed in the division below
   828  		if y == b {
   829  			B.Set(b)
   830  		} else {
   831  			B = b
   832  		}
   833  		// y = (z - a*x)/b
   834  		y.Mul(a, Ua) // y can safely alias a
   835  		if negA {
   836  			y.neg = !y.neg
   837  		}
   838  		y.Sub(A, y)
   839  		y.Div(y, B)
   840  	}
   841  
   842  	if x != nil {
   843  		*x = *Ua
   844  		if negA {
   845  			x.neg = !x.neg
   846  		}
   847  	}
   848  
   849  	*z = *A
   850  
   851  	return z
   852  }
   853  
   854  // Rand sets z to a pseudo-random number in [0, n) and returns z.
   855  //
   856  // As this uses the math/rand package, it must not be used for
   857  // security-sensitive work. Use crypto/rand.Int instead.
   858  func (z *Int) Rand(rnd *rand.Rand, n *Int) *Int {
   859  	// z.neg is not modified before the if check, because z and n might alias.
   860  	if n.neg || len(n.abs) == 0 {
   861  		z.neg = false
   862  		z.abs = nil
   863  		return z
   864  	}
   865  	z.neg = false
   866  	z.abs = z.abs.random(rnd, n.abs, n.abs.bitLen())
   867  	return z
   868  }
   869  
   870  // ModInverse sets z to the multiplicative inverse of g in the ring ℤ/nℤ
   871  // and returns z. If g and n are not relatively prime, g has no multiplicative
   872  // inverse in the ring ℤ/nℤ.  In this case, z is unchanged and the return value
   873  // is nil. If n == 0, a division-by-zero run-time panic occurs.
   874  func (z *Int) ModInverse(g, n *Int) *Int {
   875  	// GCD expects parameters a and b to be > 0.
   876  	if n.neg {
   877  		var n2 Int
   878  		n = n2.Neg(n)
   879  	}
   880  	if g.neg {
   881  		var g2 Int
   882  		g = g2.Mod(g, n)
   883  	}
   884  	var d, x Int
   885  	d.GCD(&x, nil, g, n)
   886  
   887  	// if and only if d==1, g and n are relatively prime
   888  	if d.Cmp(intOne) != 0 {
   889  		return nil
   890  	}
   891  
   892  	// x and y are such that g*x + n*y = 1, therefore x is the inverse element,
   893  	// but it may be negative, so convert to the range 0 <= z < |n|
   894  	if x.neg {
   895  		z.Add(&x, n)
   896  	} else {
   897  		z.Set(&x)
   898  	}
   899  	return z
   900  }
   901  
   902  func (z nat) modInverse(g, n nat) nat {
   903  	// TODO(rsc): ModInverse should be implemented in terms of this function.
   904  	return (&Int{abs: z}).ModInverse(&Int{abs: g}, &Int{abs: n}).abs
   905  }
   906  
   907  // Jacobi returns the Jacobi symbol (x/y), either +1, -1, or 0.
   908  // The y argument must be an odd integer.
   909  func Jacobi(x, y *Int) int {
   910  	if len(y.abs) == 0 || y.abs[0]&1 == 0 {
   911  		panic(fmt.Sprintf("big: invalid 2nd argument to Int.Jacobi: need odd integer but got %s", y.String()))
   912  	}
   913  
   914  	// We use the formulation described in chapter 2, section 2.4,
   915  	// "The Yacas Book of Algorithms":
   916  	// http://yacas.sourceforge.net/Algo.book.pdf
   917  
   918  	var a, b, c Int
   919  	a.Set(x)
   920  	b.Set(y)
   921  	j := 1
   922  
   923  	if b.neg {
   924  		if a.neg {
   925  			j = -1
   926  		}
   927  		b.neg = false
   928  	}
   929  
   930  	for {
   931  		if b.Cmp(intOne) == 0 {
   932  			return j
   933  		}
   934  		if len(a.abs) == 0 {
   935  			return 0
   936  		}
   937  		a.Mod(&a, &b)
   938  		if len(a.abs) == 0 {
   939  			return 0
   940  		}
   941  		// a > 0
   942  
   943  		// handle factors of 2 in 'a'
   944  		s := a.abs.trailingZeroBits()
   945  		if s&1 != 0 {
   946  			bmod8 := b.abs[0] & 7
   947  			if bmod8 == 3 || bmod8 == 5 {
   948  				j = -j
   949  			}
   950  		}
   951  		c.Rsh(&a, s) // a = 2^s*c
   952  
   953  		// swap numerator and denominator
   954  		if b.abs[0]&3 == 3 && c.abs[0]&3 == 3 {
   955  			j = -j
   956  		}
   957  		a.Set(&b)
   958  		b.Set(&c)
   959  	}
   960  }
   961  
   962  // modSqrt3Mod4 uses the identity
   963  //
   964  //	   (a^((p+1)/4))^2  mod p
   965  //	== u^(p+1)          mod p
   966  //	== u^2              mod p
   967  //
   968  // to calculate the square root of any quadratic residue mod p quickly for 3
   969  // mod 4 primes.
   970  func (z *Int) modSqrt3Mod4Prime(x, p *Int) *Int {
   971  	e := new(Int).Add(p, intOne) // e = p + 1
   972  	e.Rsh(e, 2)                  // e = (p + 1) / 4
   973  	z.Exp(x, e, p)               // z = x^e mod p
   974  	return z
   975  }
   976  
   977  // modSqrt5Mod8 uses Atkin's observation that 2 is not a square mod p
   978  //
   979  //	alpha ==  (2*a)^((p-5)/8)    mod p
   980  //	beta  ==  2*a*alpha^2        mod p  is a square root of -1
   981  //	b     ==  a*alpha*(beta-1)   mod p  is a square root of a
   982  //
   983  // to calculate the square root of any quadratic residue mod p quickly for 5
   984  // mod 8 primes.
   985  func (z *Int) modSqrt5Mod8Prime(x, p *Int) *Int {
   986  	// p == 5 mod 8 implies p = e*8 + 5
   987  	// e is the quotient and 5 the remainder on division by 8
   988  	e := new(Int).Rsh(p, 3)  // e = (p - 5) / 8
   989  	tx := new(Int).Lsh(x, 1) // tx = 2*x
   990  	alpha := new(Int).Exp(tx, e, p)
   991  	beta := new(Int).Mul(alpha, alpha)
   992  	beta.Mod(beta, p)
   993  	beta.Mul(beta, tx)
   994  	beta.Mod(beta, p)
   995  	beta.Sub(beta, intOne)
   996  	beta.Mul(beta, x)
   997  	beta.Mod(beta, p)
   998  	beta.Mul(beta, alpha)
   999  	z.Mod(beta, p)
  1000  	return z
  1001  }
  1002  
  1003  // modSqrtTonelliShanks uses the Tonelli-Shanks algorithm to find the square
  1004  // root of a quadratic residue modulo any prime.
  1005  func (z *Int) modSqrtTonelliShanks(x, p *Int) *Int {
  1006  	// Break p-1 into s*2^e such that s is odd.
  1007  	var s Int
  1008  	s.Sub(p, intOne)
  1009  	e := s.abs.trailingZeroBits()
  1010  	s.Rsh(&s, e)
  1011  
  1012  	// find some non-square n
  1013  	var n Int
  1014  	n.SetInt64(2)
  1015  	for Jacobi(&n, p) != -1 {
  1016  		n.Add(&n, intOne)
  1017  	}
  1018  
  1019  	// Core of the Tonelli-Shanks algorithm. Follows the description in
  1020  	// section 6 of "Square roots from 1; 24, 51, 10 to Dan Shanks" by Ezra
  1021  	// Brown:
  1022  	// https://www.maa.org/sites/default/files/pdf/upload_library/22/Polya/07468342.di020786.02p0470a.pdf
  1023  	var y, b, g, t Int
  1024  	y.Add(&s, intOne)
  1025  	y.Rsh(&y, 1)
  1026  	y.Exp(x, &y, p)  // y = x^((s+1)/2)
  1027  	b.Exp(x, &s, p)  // b = x^s
  1028  	g.Exp(&n, &s, p) // g = n^s
  1029  	r := e
  1030  	for {
  1031  		// find the least m such that ord_p(b) = 2^m
  1032  		var m uint
  1033  		t.Set(&b)
  1034  		for t.Cmp(intOne) != 0 {
  1035  			t.Mul(&t, &t).Mod(&t, p)
  1036  			m++
  1037  		}
  1038  
  1039  		if m == 0 {
  1040  			return z.Set(&y)
  1041  		}
  1042  
  1043  		t.SetInt64(0).SetBit(&t, int(r-m-1), 1).Exp(&g, &t, p)
  1044  		// t = g^(2^(r-m-1)) mod p
  1045  		g.Mul(&t, &t).Mod(&g, p) // g = g^(2^(r-m)) mod p
  1046  		y.Mul(&y, &t).Mod(&y, p)
  1047  		b.Mul(&b, &g).Mod(&b, p)
  1048  		r = m
  1049  	}
  1050  }
  1051  
  1052  // ModSqrt sets z to a square root of x mod p if such a square root exists, and
  1053  // returns z. The modulus p must be an odd prime. If x is not a square mod p,
  1054  // ModSqrt leaves z unchanged and returns nil. This function panics if p is
  1055  // not an odd integer, its behavior is undefined if p is odd but not prime.
  1056  func (z *Int) ModSqrt(x, p *Int) *Int {
  1057  	switch Jacobi(x, p) {
  1058  	case -1:
  1059  		return nil // x is not a square mod p
  1060  	case 0:
  1061  		return z.SetInt64(0) // sqrt(0) mod p = 0
  1062  	case 1:
  1063  		break
  1064  	}
  1065  	if x.neg || x.Cmp(p) >= 0 { // ensure 0 <= x < p
  1066  		x = new(Int).Mod(x, p)
  1067  	}
  1068  
  1069  	switch {
  1070  	case p.abs[0]%4 == 3:
  1071  		// Check whether p is 3 mod 4, and if so, use the faster algorithm.
  1072  		return z.modSqrt3Mod4Prime(x, p)
  1073  	case p.abs[0]%8 == 5:
  1074  		// Check whether p is 5 mod 8, use Atkin's algorithm.
  1075  		return z.modSqrt5Mod8Prime(x, p)
  1076  	default:
  1077  		// Otherwise, use Tonelli-Shanks.
  1078  		return z.modSqrtTonelliShanks(x, p)
  1079  	}
  1080  }
  1081  
  1082  // Lsh sets z = x << n and returns z.
  1083  func (z *Int) Lsh(x *Int, n uint) *Int {
  1084  	z.abs = z.abs.shl(x.abs, n)
  1085  	z.neg = x.neg
  1086  	return z
  1087  }
  1088  
  1089  // Rsh sets z = x >> n and returns z.
  1090  func (z *Int) Rsh(x *Int, n uint) *Int {
  1091  	if x.neg {
  1092  		// (-x) >> s == ^(x-1) >> s == ^((x-1) >> s) == -(((x-1) >> s) + 1)
  1093  		t := z.abs.sub(x.abs, natOne) // no underflow because |x| > 0
  1094  		t = t.shr(t, n)
  1095  		z.abs = t.add(t, natOne)
  1096  		z.neg = true // z cannot be zero if x is negative
  1097  		return z
  1098  	}
  1099  
  1100  	z.abs = z.abs.shr(x.abs, n)
  1101  	z.neg = false
  1102  	return z
  1103  }
  1104  
  1105  // Bit returns the value of the i'th bit of x. That is, it
  1106  // returns (x>>i)&1. The bit index i must be >= 0.
  1107  func (x *Int) Bit(i int) uint {
  1108  	if i == 0 {
  1109  		// optimization for common case: odd/even test of x
  1110  		if len(x.abs) > 0 {
  1111  			return uint(x.abs[0] & 1) // bit 0 is same for -x
  1112  		}
  1113  		return 0
  1114  	}
  1115  	if i < 0 {
  1116  		panic("negative bit index")
  1117  	}
  1118  	if x.neg {
  1119  		t := nat(nil).sub(x.abs, natOne)
  1120  		return t.bit(uint(i)) ^ 1
  1121  	}
  1122  
  1123  	return x.abs.bit(uint(i))
  1124  }
  1125  
  1126  // SetBit sets z to x, with x's i'th bit set to b (0 or 1).
  1127  // That is, if b is 1 SetBit sets z = x | (1 << i);
  1128  // if b is 0 SetBit sets z = x &^ (1 << i). If b is not 0 or 1,
  1129  // SetBit will panic.
  1130  func (z *Int) SetBit(x *Int, i int, b uint) *Int {
  1131  	if i < 0 {
  1132  		panic("negative bit index")
  1133  	}
  1134  	if x.neg {
  1135  		t := z.abs.sub(x.abs, natOne)
  1136  		t = t.setBit(t, uint(i), b^1)
  1137  		z.abs = t.add(t, natOne)
  1138  		z.neg = len(z.abs) > 0
  1139  		return z
  1140  	}
  1141  	z.abs = z.abs.setBit(x.abs, uint(i), b)
  1142  	z.neg = false
  1143  	return z
  1144  }
  1145  
  1146  // And sets z = x & y and returns z.
  1147  func (z *Int) And(x, y *Int) *Int {
  1148  	if x.neg == y.neg {
  1149  		if x.neg {
  1150  			// (-x) & (-y) == ^(x-1) & ^(y-1) == ^((x-1) | (y-1)) == -(((x-1) | (y-1)) + 1)
  1151  			x1 := nat(nil).sub(x.abs, natOne)
  1152  			y1 := nat(nil).sub(y.abs, natOne)
  1153  			z.abs = z.abs.add(z.abs.or(x1, y1), natOne)
  1154  			z.neg = true // z cannot be zero if x and y are negative
  1155  			return z
  1156  		}
  1157  
  1158  		// x & y == x & y
  1159  		z.abs = z.abs.and(x.abs, y.abs)
  1160  		z.neg = false
  1161  		return z
  1162  	}
  1163  
  1164  	// x.neg != y.neg
  1165  	if x.neg {
  1166  		x, y = y, x // & is symmetric
  1167  	}
  1168  
  1169  	// x & (-y) == x & ^(y-1) == x &^ (y-1)
  1170  	y1 := nat(nil).sub(y.abs, natOne)
  1171  	z.abs = z.abs.andNot(x.abs, y1)
  1172  	z.neg = false
  1173  	return z
  1174  }
  1175  
  1176  // AndNot sets z = x &^ y and returns z.
  1177  func (z *Int) AndNot(x, y *Int) *Int {
  1178  	if x.neg == y.neg {
  1179  		if x.neg {
  1180  			// (-x) &^ (-y) == ^(x-1) &^ ^(y-1) == ^(x-1) & (y-1) == (y-1) &^ (x-1)
  1181  			x1 := nat(nil).sub(x.abs, natOne)
  1182  			y1 := nat(nil).sub(y.abs, natOne)
  1183  			z.abs = z.abs.andNot(y1, x1)
  1184  			z.neg = false
  1185  			return z
  1186  		}
  1187  
  1188  		// x &^ y == x &^ y
  1189  		z.abs = z.abs.andNot(x.abs, y.abs)
  1190  		z.neg = false
  1191  		return z
  1192  	}
  1193  
  1194  	if x.neg {
  1195  		// (-x) &^ y == ^(x-1) &^ y == ^(x-1) & ^y == ^((x-1) | y) == -(((x-1) | y) + 1)
  1196  		x1 := nat(nil).sub(x.abs, natOne)
  1197  		z.abs = z.abs.add(z.abs.or(x1, y.abs), natOne)
  1198  		z.neg = true // z cannot be zero if x is negative and y is positive
  1199  		return z
  1200  	}
  1201  
  1202  	// x &^ (-y) == x &^ ^(y-1) == x & (y-1)
  1203  	y1 := nat(nil).sub(y.abs, natOne)
  1204  	z.abs = z.abs.and(x.abs, y1)
  1205  	z.neg = false
  1206  	return z
  1207  }
  1208  
  1209  // Or sets z = x | y and returns z.
  1210  func (z *Int) Or(x, y *Int) *Int {
  1211  	if x.neg == y.neg {
  1212  		if x.neg {
  1213  			// (-x) | (-y) == ^(x-1) | ^(y-1) == ^((x-1) & (y-1)) == -(((x-1) & (y-1)) + 1)
  1214  			x1 := nat(nil).sub(x.abs, natOne)
  1215  			y1 := nat(nil).sub(y.abs, natOne)
  1216  			z.abs = z.abs.add(z.abs.and(x1, y1), natOne)
  1217  			z.neg = true // z cannot be zero if x and y are negative
  1218  			return z
  1219  		}
  1220  
  1221  		// x | y == x | y
  1222  		z.abs = z.abs.or(x.abs, y.abs)
  1223  		z.neg = false
  1224  		return z
  1225  	}
  1226  
  1227  	// x.neg != y.neg
  1228  	if x.neg {
  1229  		x, y = y, x // | is symmetric
  1230  	}
  1231  
  1232  	// x | (-y) == x | ^(y-1) == ^((y-1) &^ x) == -(^((y-1) &^ x) + 1)
  1233  	y1 := nat(nil).sub(y.abs, natOne)
  1234  	z.abs = z.abs.add(z.abs.andNot(y1, x.abs), natOne)
  1235  	z.neg = true // z cannot be zero if one of x or y is negative
  1236  	return z
  1237  }
  1238  
  1239  // Xor sets z = x ^ y and returns z.
  1240  func (z *Int) Xor(x, y *Int) *Int {
  1241  	if x.neg == y.neg {
  1242  		if x.neg {
  1243  			// (-x) ^ (-y) == ^(x-1) ^ ^(y-1) == (x-1) ^ (y-1)
  1244  			x1 := nat(nil).sub(x.abs, natOne)
  1245  			y1 := nat(nil).sub(y.abs, natOne)
  1246  			z.abs = z.abs.xor(x1, y1)
  1247  			z.neg = false
  1248  			return z
  1249  		}
  1250  
  1251  		// x ^ y == x ^ y
  1252  		z.abs = z.abs.xor(x.abs, y.abs)
  1253  		z.neg = false
  1254  		return z
  1255  	}
  1256  
  1257  	// x.neg != y.neg
  1258  	if x.neg {
  1259  		x, y = y, x // ^ is symmetric
  1260  	}
  1261  
  1262  	// x ^ (-y) == x ^ ^(y-1) == ^(x ^ (y-1)) == -((x ^ (y-1)) + 1)
  1263  	y1 := nat(nil).sub(y.abs, natOne)
  1264  	z.abs = z.abs.add(z.abs.xor(x.abs, y1), natOne)
  1265  	z.neg = true // z cannot be zero if only one of x or y is negative
  1266  	return z
  1267  }
  1268  
  1269  // Not sets z = ^x and returns z.
  1270  func (z *Int) Not(x *Int) *Int {
  1271  	if x.neg {
  1272  		// ^(-x) == ^(^(x-1)) == x-1
  1273  		z.abs = z.abs.sub(x.abs, natOne)
  1274  		z.neg = false
  1275  		return z
  1276  	}
  1277  
  1278  	// ^x == -x-1 == -(x+1)
  1279  	z.abs = z.abs.add(x.abs, natOne)
  1280  	z.neg = true // z cannot be zero if x is positive
  1281  	return z
  1282  }
  1283  
  1284  // Sqrt sets z to ⌊√x⌋, the largest integer such that z² ≤ x, and returns z.
  1285  // It panics if x is negative.
  1286  func (z *Int) Sqrt(x *Int) *Int {
  1287  	if x.neg {
  1288  		panic("square root of negative number")
  1289  	}
  1290  	z.neg = false
  1291  	z.abs = z.abs.sqrt(x.abs)
  1292  	return z
  1293  }
  1294  

View as plain text