...

Source file src/math/big/int.go

Documentation: math/big

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

View as plain text