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

View as plain text