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

View as plain text