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

View as plain text