Source file src/math/big/int.go

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

View as plain text