github.com/rsc/go@v0.0.0-20150416155037-e040fd465409/src/math/big/int.go (about)

     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  type Int struct {
    19  	neg bool // sign
    20  	abs nat  // absolute value of the integer
    21  }
    22  
    23  var intOne = &Int{false, natOne}
    24  
    25  // Sign returns:
    26  //
    27  //	-1 if x <  0
    28  //	 0 if x == 0
    29  //	+1 if x >  0
    30  //
    31  func (x *Int) Sign() int {
    32  	if len(x.abs) == 0 {
    33  		return 0
    34  	}
    35  	if x.neg {
    36  		return -1
    37  	}
    38  	return 1
    39  }
    40  
    41  // SetInt64 sets z to x and returns z.
    42  func (z *Int) SetInt64(x int64) *Int {
    43  	neg := false
    44  	if x < 0 {
    45  		neg = true
    46  		x = -x
    47  	}
    48  	z.abs = z.abs.setUint64(uint64(x))
    49  	z.neg = neg
    50  	return z
    51  }
    52  
    53  // SetUint64 sets z to x and returns z.
    54  func (z *Int) SetUint64(x uint64) *Int {
    55  	z.abs = z.abs.setUint64(x)
    56  	z.neg = false
    57  	return z
    58  }
    59  
    60  // NewInt allocates and returns a new Int set to x.
    61  func NewInt(x int64) *Int {
    62  	return new(Int).SetInt64(x)
    63  }
    64  
    65  // Set sets z to x and returns z.
    66  func (z *Int) Set(x *Int) *Int {
    67  	if z != x {
    68  		z.abs = z.abs.set(x.abs)
    69  		z.neg = x.neg
    70  	}
    71  	return z
    72  }
    73  
    74  // Bits provides raw (unchecked but fast) access to x by returning its
    75  // absolute value as a little-endian Word slice. The result and x share
    76  // the same underlying array.
    77  // Bits is intended to support implementation of missing low-level Int
    78  // functionality outside this package; it should be avoided otherwise.
    79  func (x *Int) Bits() []Word {
    80  	return x.abs
    81  }
    82  
    83  // SetBits provides raw (unchecked but fast) access to z by setting its
    84  // value to abs, interpreted as a little-endian Word slice, and returning
    85  // z. The result and abs share the same underlying array.
    86  // SetBits is intended to support implementation of missing low-level Int
    87  // functionality outside this package; it should be avoided otherwise.
    88  func (z *Int) SetBits(abs []Word) *Int {
    89  	z.abs = nat(abs).norm()
    90  	z.neg = false
    91  	return z
    92  }
    93  
    94  // Abs sets z to |x| (the absolute value of x) and returns z.
    95  func (z *Int) Abs(x *Int) *Int {
    96  	z.Set(x)
    97  	z.neg = false
    98  	return z
    99  }
   100  
   101  // Neg sets z to -x and returns z.
   102  func (z *Int) Neg(x *Int) *Int {
   103  	z.Set(x)
   104  	z.neg = len(z.abs) > 0 && !z.neg // 0 has no sign
   105  	return z
   106  }
   107  
   108  // Add sets z to the sum x+y and returns z.
   109  func (z *Int) Add(x, y *Int) *Int {
   110  	neg := x.neg
   111  	if x.neg == y.neg {
   112  		// x + y == x + y
   113  		// (-x) + (-y) == -(x + y)
   114  		z.abs = z.abs.add(x.abs, y.abs)
   115  	} else {
   116  		// x + (-y) == x - y == -(y - x)
   117  		// (-x) + y == y - x == -(x - y)
   118  		if x.abs.cmp(y.abs) >= 0 {
   119  			z.abs = z.abs.sub(x.abs, y.abs)
   120  		} else {
   121  			neg = !neg
   122  			z.abs = z.abs.sub(y.abs, x.abs)
   123  		}
   124  	}
   125  	z.neg = len(z.abs) > 0 && neg // 0 has no sign
   126  	return z
   127  }
   128  
   129  // Sub sets z to the difference x-y and returns z.
   130  func (z *Int) Sub(x, y *Int) *Int {
   131  	neg := x.neg
   132  	if x.neg != y.neg {
   133  		// x - (-y) == x + y
   134  		// (-x) - y == -(x + y)
   135  		z.abs = z.abs.add(x.abs, y.abs)
   136  	} else {
   137  		// x - y == x - y == -(y - x)
   138  		// (-x) - (-y) == y - x == -(x - y)
   139  		if x.abs.cmp(y.abs) >= 0 {
   140  			z.abs = z.abs.sub(x.abs, y.abs)
   141  		} else {
   142  			neg = !neg
   143  			z.abs = z.abs.sub(y.abs, x.abs)
   144  		}
   145  	}
   146  	z.neg = len(z.abs) > 0 && neg // 0 has no sign
   147  	return z
   148  }
   149  
   150  // Mul sets z to the product x*y and returns z.
   151  func (z *Int) Mul(x, y *Int) *Int {
   152  	// x * y == x * y
   153  	// x * (-y) == -(x * y)
   154  	// (-x) * y == -(x * y)
   155  	// (-x) * (-y) == x * y
   156  	z.abs = z.abs.mul(x.abs, y.abs)
   157  	z.neg = len(z.abs) > 0 && x.neg != y.neg // 0 has no sign
   158  	return z
   159  }
   160  
   161  // MulRange sets z to the product of all integers
   162  // in the range [a, b] inclusively and returns z.
   163  // If a > b (empty range), the result is 1.
   164  func (z *Int) MulRange(a, b int64) *Int {
   165  	switch {
   166  	case a > b:
   167  		return z.SetInt64(1) // empty range
   168  	case a <= 0 && b >= 0:
   169  		return z.SetInt64(0) // range includes 0
   170  	}
   171  	// a <= b && (b < 0 || a > 0)
   172  
   173  	neg := false
   174  	if a < 0 {
   175  		neg = (b-a)&1 == 0
   176  		a, b = -b, -a
   177  	}
   178  
   179  	z.abs = z.abs.mulRange(uint64(a), uint64(b))
   180  	z.neg = neg
   181  	return z
   182  }
   183  
   184  // Binomial sets z to the binomial coefficient of (n, k) and returns z.
   185  func (z *Int) Binomial(n, k int64) *Int {
   186  	// reduce the number of multiplications by reducing k
   187  	if n/2 < k && k <= n {
   188  		k = n - k // Binomial(n, k) == Binomial(n, n-k)
   189  	}
   190  	var a, b Int
   191  	a.MulRange(n-k+1, n)
   192  	b.MulRange(1, k)
   193  	return z.Quo(&a, &b)
   194  }
   195  
   196  // Quo sets z to the quotient x/y for y != 0 and returns z.
   197  // If y == 0, a division-by-zero run-time panic occurs.
   198  // Quo implements truncated division (like Go); see QuoRem for more details.
   199  func (z *Int) Quo(x, y *Int) *Int {
   200  	z.abs, _ = z.abs.div(nil, x.abs, y.abs)
   201  	z.neg = len(z.abs) > 0 && x.neg != y.neg // 0 has no sign
   202  	return z
   203  }
   204  
   205  // Rem sets z to the remainder x%y for y != 0 and returns z.
   206  // If y == 0, a division-by-zero run-time panic occurs.
   207  // Rem implements truncated modulus (like Go); see QuoRem for more details.
   208  func (z *Int) Rem(x, y *Int) *Int {
   209  	_, z.abs = nat(nil).div(z.abs, x.abs, y.abs)
   210  	z.neg = len(z.abs) > 0 && x.neg // 0 has no sign
   211  	return z
   212  }
   213  
   214  // QuoRem sets z to the quotient x/y and r to the remainder x%y
   215  // and returns the pair (z, r) for y != 0.
   216  // If y == 0, a division-by-zero run-time panic occurs.
   217  //
   218  // QuoRem implements T-division and modulus (like Go):
   219  //
   220  //	q = x/y      with the result truncated to zero
   221  //	r = x - y*q
   222  //
   223  // (See Daan Leijen, ``Division and Modulus for Computer Scientists''.)
   224  // See DivMod for Euclidean division and modulus (unlike Go).
   225  //
   226  func (z *Int) QuoRem(x, y, r *Int) (*Int, *Int) {
   227  	z.abs, r.abs = z.abs.div(r.abs, x.abs, y.abs)
   228  	z.neg, r.neg = len(z.abs) > 0 && x.neg != y.neg, len(r.abs) > 0 && x.neg // 0 has no sign
   229  	return z, r
   230  }
   231  
   232  // Div sets z to the quotient x/y for y != 0 and returns z.
   233  // If y == 0, a division-by-zero run-time panic occurs.
   234  // Div implements Euclidean division (unlike Go); see DivMod for more details.
   235  func (z *Int) Div(x, y *Int) *Int {
   236  	y_neg := y.neg // z may be an alias for y
   237  	var r Int
   238  	z.QuoRem(x, y, &r)
   239  	if r.neg {
   240  		if y_neg {
   241  			z.Add(z, intOne)
   242  		} else {
   243  			z.Sub(z, intOne)
   244  		}
   245  	}
   246  	return z
   247  }
   248  
   249  // Mod sets z to the modulus x%y for y != 0 and returns z.
   250  // If y == 0, a division-by-zero run-time panic occurs.
   251  // Mod implements Euclidean modulus (unlike Go); see DivMod for more details.
   252  func (z *Int) Mod(x, y *Int) *Int {
   253  	y0 := y // save y
   254  	if z == y || alias(z.abs, y.abs) {
   255  		y0 = new(Int).Set(y)
   256  	}
   257  	var q Int
   258  	q.QuoRem(x, y, z)
   259  	if z.neg {
   260  		if y0.neg {
   261  			z.Sub(z, y0)
   262  		} else {
   263  			z.Add(z, y0)
   264  		}
   265  	}
   266  	return z
   267  }
   268  
   269  // DivMod sets z to the quotient x div y and m to the modulus x mod y
   270  // and returns the pair (z, m) for y != 0.
   271  // If y == 0, a division-by-zero run-time panic occurs.
   272  //
   273  // DivMod implements Euclidean division and modulus (unlike Go):
   274  //
   275  //	q = x div y  such that
   276  //	m = x - y*q  with 0 <= m < |q|
   277  //
   278  // (See Raymond T. Boute, ``The Euclidean definition of the functions
   279  // div and mod''. ACM Transactions on Programming Languages and
   280  // Systems (TOPLAS), 14(2):127-144, New York, NY, USA, 4/1992.
   281  // ACM press.)
   282  // See QuoRem for T-division and modulus (like Go).
   283  //
   284  func (z *Int) DivMod(x, y, m *Int) (*Int, *Int) {
   285  	y0 := y // save y
   286  	if z == y || alias(z.abs, y.abs) {
   287  		y0 = new(Int).Set(y)
   288  	}
   289  	z.QuoRem(x, y, m)
   290  	if m.neg {
   291  		if y0.neg {
   292  			z.Add(z, intOne)
   293  			m.Sub(m, y0)
   294  		} else {
   295  			z.Sub(z, intOne)
   296  			m.Add(m, y0)
   297  		}
   298  	}
   299  	return z, m
   300  }
   301  
   302  // Cmp compares x and y and returns:
   303  //
   304  //   -1 if x <  y
   305  //    0 if x == y
   306  //   +1 if x >  y
   307  //
   308  func (x *Int) Cmp(y *Int) (r int) {
   309  	// x cmp y == x cmp y
   310  	// x cmp (-y) == x
   311  	// (-x) cmp y == y
   312  	// (-x) cmp (-y) == -(x cmp y)
   313  	switch {
   314  	case x.neg == y.neg:
   315  		r = x.abs.cmp(y.abs)
   316  		if x.neg {
   317  			r = -r
   318  		}
   319  	case x.neg:
   320  		r = -1
   321  	default:
   322  		r = 1
   323  	}
   324  	return
   325  }
   326  
   327  // low32 returns the least significant 32 bits of z.
   328  func low32(z nat) uint32 {
   329  	if len(z) == 0 {
   330  		return 0
   331  	}
   332  	return uint32(z[0])
   333  }
   334  
   335  // low64 returns the least significant 64 bits of z.
   336  func low64(z nat) uint64 {
   337  	if len(z) == 0 {
   338  		return 0
   339  	}
   340  	v := uint64(z[0])
   341  	if _W == 32 && len(z) > 1 {
   342  		v |= uint64(z[1]) << 32
   343  	}
   344  	return v
   345  }
   346  
   347  // Int64 returns the int64 representation of x.
   348  // If x cannot be represented in an int64, the result is undefined.
   349  func (x *Int) Int64() int64 {
   350  	v := int64(low64(x.abs))
   351  	if x.neg {
   352  		v = -v
   353  	}
   354  	return v
   355  }
   356  
   357  // Uint64 returns the uint64 representation of x.
   358  // If x cannot be represented in a uint64, the result is undefined.
   359  func (x *Int) Uint64() uint64 {
   360  	return low64(x.abs)
   361  }
   362  
   363  // SetString sets z to the value of s, interpreted in the given base,
   364  // and returns z and a boolean indicating success. If SetString fails,
   365  // the value of z is undefined but the returned value is nil.
   366  //
   367  // The base argument must be 0 or a value between 2 and MaxBase. If the base
   368  // is 0, the string prefix determines the actual conversion base. A prefix of
   369  // ``0x'' or ``0X'' selects base 16; the ``0'' prefix selects base 8, and a
   370  // ``0b'' or ``0B'' prefix selects base 2. Otherwise the selected base is 10.
   371  //
   372  func (z *Int) SetString(s string, base int) (*Int, bool) {
   373  	r := strings.NewReader(s)
   374  	_, _, err := z.scan(r, base)
   375  	if err != nil {
   376  		return nil, false
   377  	}
   378  	_, err = r.ReadByte()
   379  	if err != io.EOF {
   380  		return nil, false
   381  	}
   382  	return z, true // err == io.EOF => scan consumed all of s
   383  }
   384  
   385  // SetBytes interprets buf as the bytes of a big-endian unsigned
   386  // integer, sets z to that value, and returns z.
   387  func (z *Int) SetBytes(buf []byte) *Int {
   388  	z.abs = z.abs.setBytes(buf)
   389  	z.neg = false
   390  	return z
   391  }
   392  
   393  // Bytes returns the absolute value of x as a big-endian byte slice.
   394  func (x *Int) Bytes() []byte {
   395  	buf := make([]byte, len(x.abs)*_S)
   396  	return buf[x.abs.bytes(buf):]
   397  }
   398  
   399  // BitLen returns the length of the absolute value of x in bits.
   400  // The bit length of 0 is 0.
   401  func (x *Int) BitLen() int {
   402  	return x.abs.bitLen()
   403  }
   404  
   405  // Exp sets z = x**y mod |m| (i.e. the sign of m is ignored), and returns z.
   406  // If y <= 0, the result is 1 mod |m|; if m == nil or m == 0, z = x**y.
   407  // See Knuth, volume 2, section 4.6.3.
   408  func (z *Int) Exp(x, y, m *Int) *Int {
   409  	var yWords nat
   410  	if !y.neg {
   411  		yWords = y.abs
   412  	}
   413  	// y >= 0
   414  
   415  	var mWords nat
   416  	if m != nil {
   417  		mWords = m.abs // m.abs may be nil for m == 0
   418  	}
   419  
   420  	z.abs = z.abs.expNN(x.abs, yWords, mWords)
   421  	z.neg = len(z.abs) > 0 && x.neg && len(yWords) > 0 && yWords[0]&1 == 1 // 0 has no sign
   422  	if z.neg && len(mWords) > 0 {
   423  		// make modulus result positive
   424  		z.abs = z.abs.sub(mWords, z.abs) // z == x**y mod |m| && 0 <= z < |m|
   425  		z.neg = false
   426  	}
   427  
   428  	return z
   429  }
   430  
   431  // GCD sets z to the greatest common divisor of a and b, which both must
   432  // be > 0, and returns z.
   433  // If x and y are not nil, GCD sets x and y such that z = a*x + b*y.
   434  // If either a or b is <= 0, GCD sets z = x = y = 0.
   435  func (z *Int) GCD(x, y, a, b *Int) *Int {
   436  	if a.Sign() <= 0 || b.Sign() <= 0 {
   437  		z.SetInt64(0)
   438  		if x != nil {
   439  			x.SetInt64(0)
   440  		}
   441  		if y != nil {
   442  			y.SetInt64(0)
   443  		}
   444  		return z
   445  	}
   446  	if x == nil && y == nil {
   447  		return z.binaryGCD(a, b)
   448  	}
   449  
   450  	A := new(Int).Set(a)
   451  	B := new(Int).Set(b)
   452  
   453  	X := new(Int)
   454  	Y := new(Int).SetInt64(1)
   455  
   456  	lastX := new(Int).SetInt64(1)
   457  	lastY := new(Int)
   458  
   459  	q := new(Int)
   460  	temp := new(Int)
   461  
   462  	for len(B.abs) > 0 {
   463  		r := new(Int)
   464  		q, r = q.QuoRem(A, B, r)
   465  
   466  		A, B = B, r
   467  
   468  		temp.Set(X)
   469  		X.Mul(X, q)
   470  		X.neg = !X.neg
   471  		X.Add(X, lastX)
   472  		lastX.Set(temp)
   473  
   474  		temp.Set(Y)
   475  		Y.Mul(Y, q)
   476  		Y.neg = !Y.neg
   477  		Y.Add(Y, lastY)
   478  		lastY.Set(temp)
   479  	}
   480  
   481  	if x != nil {
   482  		*x = *lastX
   483  	}
   484  
   485  	if y != nil {
   486  		*y = *lastY
   487  	}
   488  
   489  	*z = *A
   490  	return z
   491  }
   492  
   493  // binaryGCD sets z to the greatest common divisor of a and b, which both must
   494  // be > 0, and returns z.
   495  // See Knuth, The Art of Computer Programming, Vol. 2, Section 4.5.2, Algorithm B.
   496  func (z *Int) binaryGCD(a, b *Int) *Int {
   497  	u := z
   498  	v := new(Int)
   499  
   500  	// use one Euclidean iteration to ensure that u and v are approx. the same size
   501  	switch {
   502  	case len(a.abs) > len(b.abs):
   503  		u.Set(b)
   504  		v.Rem(a, b)
   505  	case len(a.abs) < len(b.abs):
   506  		u.Set(a)
   507  		v.Rem(b, a)
   508  	default:
   509  		u.Set(a)
   510  		v.Set(b)
   511  	}
   512  
   513  	// v might be 0 now
   514  	if len(v.abs) == 0 {
   515  		return u
   516  	}
   517  	// u > 0 && v > 0
   518  
   519  	// determine largest k such that u = u' << k, v = v' << k
   520  	k := u.abs.trailingZeroBits()
   521  	if vk := v.abs.trailingZeroBits(); vk < k {
   522  		k = vk
   523  	}
   524  	u.Rsh(u, k)
   525  	v.Rsh(v, k)
   526  
   527  	// determine t (we know that u > 0)
   528  	t := new(Int)
   529  	if u.abs[0]&1 != 0 {
   530  		// u is odd
   531  		t.Neg(v)
   532  	} else {
   533  		t.Set(u)
   534  	}
   535  
   536  	for len(t.abs) > 0 {
   537  		// reduce t
   538  		t.Rsh(t, t.abs.trailingZeroBits())
   539  		if t.neg {
   540  			v, t = t, v
   541  			v.neg = len(v.abs) > 0 && !v.neg // 0 has no sign
   542  		} else {
   543  			u, t = t, u
   544  		}
   545  		t.Sub(u, v)
   546  	}
   547  
   548  	return z.Lsh(u, k)
   549  }
   550  
   551  // ProbablyPrime performs n Miller-Rabin tests to check whether x is prime.
   552  // If it returns true, x is prime with probability 1 - 1/4^n.
   553  // If it returns false, x is not prime. n must be > 0.
   554  func (x *Int) ProbablyPrime(n int) bool {
   555  	if n <= 0 {
   556  		panic("non-positive n for ProbablyPrime")
   557  	}
   558  	return !x.neg && x.abs.probablyPrime(n)
   559  }
   560  
   561  // Rand sets z to a pseudo-random number in [0, n) and returns z.
   562  func (z *Int) Rand(rnd *rand.Rand, n *Int) *Int {
   563  	z.neg = false
   564  	if n.neg == true || len(n.abs) == 0 {
   565  		z.abs = nil
   566  		return z
   567  	}
   568  	z.abs = z.abs.random(rnd, n.abs, n.abs.bitLen())
   569  	return z
   570  }
   571  
   572  // ModInverse sets z to the multiplicative inverse of g in the ring ℤ/nℤ
   573  // and returns z. If g and n are not relatively prime, the result is undefined.
   574  func (z *Int) ModInverse(g, n *Int) *Int {
   575  	var d Int
   576  	d.GCD(z, nil, g, n)
   577  	// x and y are such that g*x + n*y = d. Since g and n are
   578  	// relatively prime, d = 1. Taking that modulo n results in
   579  	// g*x = 1, therefore x is the inverse element.
   580  	if z.neg {
   581  		z.Add(z, n)
   582  	}
   583  	return z
   584  }
   585  
   586  // Lsh sets z = x << n and returns z.
   587  func (z *Int) Lsh(x *Int, n uint) *Int {
   588  	z.abs = z.abs.shl(x.abs, n)
   589  	z.neg = x.neg
   590  	return z
   591  }
   592  
   593  // Rsh sets z = x >> n and returns z.
   594  func (z *Int) Rsh(x *Int, n uint) *Int {
   595  	if x.neg {
   596  		// (-x) >> s == ^(x-1) >> s == ^((x-1) >> s) == -(((x-1) >> s) + 1)
   597  		t := z.abs.sub(x.abs, natOne) // no underflow because |x| > 0
   598  		t = t.shr(t, n)
   599  		z.abs = t.add(t, natOne)
   600  		z.neg = true // z cannot be zero if x is negative
   601  		return z
   602  	}
   603  
   604  	z.abs = z.abs.shr(x.abs, n)
   605  	z.neg = false
   606  	return z
   607  }
   608  
   609  // Bit returns the value of the i'th bit of x. That is, it
   610  // returns (x>>i)&1. The bit index i must be >= 0.
   611  func (x *Int) Bit(i int) uint {
   612  	if i == 0 {
   613  		// optimization for common case: odd/even test of x
   614  		if len(x.abs) > 0 {
   615  			return uint(x.abs[0] & 1) // bit 0 is same for -x
   616  		}
   617  		return 0
   618  	}
   619  	if i < 0 {
   620  		panic("negative bit index")
   621  	}
   622  	if x.neg {
   623  		t := nat(nil).sub(x.abs, natOne)
   624  		return t.bit(uint(i)) ^ 1
   625  	}
   626  
   627  	return x.abs.bit(uint(i))
   628  }
   629  
   630  // SetBit sets z to x, with x's i'th bit set to b (0 or 1).
   631  // That is, if b is 1 SetBit sets z = x | (1 << i);
   632  // if b is 0 SetBit sets z = x &^ (1 << i). If b is not 0 or 1,
   633  // SetBit will panic.
   634  func (z *Int) SetBit(x *Int, i int, b uint) *Int {
   635  	if i < 0 {
   636  		panic("negative bit index")
   637  	}
   638  	if x.neg {
   639  		t := z.abs.sub(x.abs, natOne)
   640  		t = t.setBit(t, uint(i), b^1)
   641  		z.abs = t.add(t, natOne)
   642  		z.neg = len(z.abs) > 0
   643  		return z
   644  	}
   645  	z.abs = z.abs.setBit(x.abs, uint(i), b)
   646  	z.neg = false
   647  	return z
   648  }
   649  
   650  // And sets z = x & y and returns z.
   651  func (z *Int) And(x, y *Int) *Int {
   652  	if x.neg == y.neg {
   653  		if x.neg {
   654  			// (-x) & (-y) == ^(x-1) & ^(y-1) == ^((x-1) | (y-1)) == -(((x-1) | (y-1)) + 1)
   655  			x1 := nat(nil).sub(x.abs, natOne)
   656  			y1 := nat(nil).sub(y.abs, natOne)
   657  			z.abs = z.abs.add(z.abs.or(x1, y1), natOne)
   658  			z.neg = true // z cannot be zero if x and y are negative
   659  			return z
   660  		}
   661  
   662  		// x & y == x & y
   663  		z.abs = z.abs.and(x.abs, y.abs)
   664  		z.neg = false
   665  		return z
   666  	}
   667  
   668  	// x.neg != y.neg
   669  	if x.neg {
   670  		x, y = y, x // & is symmetric
   671  	}
   672  
   673  	// x & (-y) == x & ^(y-1) == x &^ (y-1)
   674  	y1 := nat(nil).sub(y.abs, natOne)
   675  	z.abs = z.abs.andNot(x.abs, y1)
   676  	z.neg = false
   677  	return z
   678  }
   679  
   680  // AndNot sets z = x &^ y and returns z.
   681  func (z *Int) AndNot(x, y *Int) *Int {
   682  	if x.neg == y.neg {
   683  		if x.neg {
   684  			// (-x) &^ (-y) == ^(x-1) &^ ^(y-1) == ^(x-1) & (y-1) == (y-1) &^ (x-1)
   685  			x1 := nat(nil).sub(x.abs, natOne)
   686  			y1 := nat(nil).sub(y.abs, natOne)
   687  			z.abs = z.abs.andNot(y1, x1)
   688  			z.neg = false
   689  			return z
   690  		}
   691  
   692  		// x &^ y == x &^ y
   693  		z.abs = z.abs.andNot(x.abs, y.abs)
   694  		z.neg = false
   695  		return z
   696  	}
   697  
   698  	if x.neg {
   699  		// (-x) &^ y == ^(x-1) &^ y == ^(x-1) & ^y == ^((x-1) | y) == -(((x-1) | y) + 1)
   700  		x1 := nat(nil).sub(x.abs, natOne)
   701  		z.abs = z.abs.add(z.abs.or(x1, y.abs), natOne)
   702  		z.neg = true // z cannot be zero if x is negative and y is positive
   703  		return z
   704  	}
   705  
   706  	// x &^ (-y) == x &^ ^(y-1) == x & (y-1)
   707  	y1 := nat(nil).sub(y.abs, natOne)
   708  	z.abs = z.abs.and(x.abs, y1)
   709  	z.neg = false
   710  	return z
   711  }
   712  
   713  // Or sets z = x | y and returns z.
   714  func (z *Int) Or(x, y *Int) *Int {
   715  	if x.neg == y.neg {
   716  		if x.neg {
   717  			// (-x) | (-y) == ^(x-1) | ^(y-1) == ^((x-1) & (y-1)) == -(((x-1) & (y-1)) + 1)
   718  			x1 := nat(nil).sub(x.abs, natOne)
   719  			y1 := nat(nil).sub(y.abs, natOne)
   720  			z.abs = z.abs.add(z.abs.and(x1, y1), natOne)
   721  			z.neg = true // z cannot be zero if x and y are negative
   722  			return z
   723  		}
   724  
   725  		// x | y == x | y
   726  		z.abs = z.abs.or(x.abs, y.abs)
   727  		z.neg = false
   728  		return z
   729  	}
   730  
   731  	// x.neg != y.neg
   732  	if x.neg {
   733  		x, y = y, x // | is symmetric
   734  	}
   735  
   736  	// x | (-y) == x | ^(y-1) == ^((y-1) &^ x) == -(^((y-1) &^ x) + 1)
   737  	y1 := nat(nil).sub(y.abs, natOne)
   738  	z.abs = z.abs.add(z.abs.andNot(y1, x.abs), natOne)
   739  	z.neg = true // z cannot be zero if one of x or y is negative
   740  	return z
   741  }
   742  
   743  // Xor sets z = x ^ y and returns z.
   744  func (z *Int) Xor(x, y *Int) *Int {
   745  	if x.neg == y.neg {
   746  		if x.neg {
   747  			// (-x) ^ (-y) == ^(x-1) ^ ^(y-1) == (x-1) ^ (y-1)
   748  			x1 := nat(nil).sub(x.abs, natOne)
   749  			y1 := nat(nil).sub(y.abs, natOne)
   750  			z.abs = z.abs.xor(x1, y1)
   751  			z.neg = false
   752  			return z
   753  		}
   754  
   755  		// x ^ y == x ^ y
   756  		z.abs = z.abs.xor(x.abs, y.abs)
   757  		z.neg = false
   758  		return z
   759  	}
   760  
   761  	// x.neg != y.neg
   762  	if x.neg {
   763  		x, y = y, x // ^ is symmetric
   764  	}
   765  
   766  	// x ^ (-y) == x ^ ^(y-1) == ^(x ^ (y-1)) == -((x ^ (y-1)) + 1)
   767  	y1 := nat(nil).sub(y.abs, natOne)
   768  	z.abs = z.abs.add(z.abs.xor(x.abs, y1), natOne)
   769  	z.neg = true // z cannot be zero if only one of x or y is negative
   770  	return z
   771  }
   772  
   773  // Not sets z = ^x and returns z.
   774  func (z *Int) Not(x *Int) *Int {
   775  	if x.neg {
   776  		// ^(-x) == ^(^(x-1)) == x-1
   777  		z.abs = z.abs.sub(x.abs, natOne)
   778  		z.neg = false
   779  		return z
   780  	}
   781  
   782  	// ^x == -x-1 == -(x+1)
   783  	z.abs = z.abs.add(x.abs, natOne)
   784  	z.neg = true // z cannot be zero if x is positive
   785  	return z
   786  }
   787  
   788  // Gob codec version. Permits backward-compatible changes to the encoding.
   789  const intGobVersion byte = 1
   790  
   791  // GobEncode implements the gob.GobEncoder interface.
   792  func (x *Int) GobEncode() ([]byte, error) {
   793  	if x == nil {
   794  		return nil, nil
   795  	}
   796  	buf := make([]byte, 1+len(x.abs)*_S) // extra byte for version and sign bit
   797  	i := x.abs.bytes(buf) - 1            // i >= 0
   798  	b := intGobVersion << 1              // make space for sign bit
   799  	if x.neg {
   800  		b |= 1
   801  	}
   802  	buf[i] = b
   803  	return buf[i:], nil
   804  }
   805  
   806  // GobDecode implements the gob.GobDecoder interface.
   807  func (z *Int) GobDecode(buf []byte) error {
   808  	if len(buf) == 0 {
   809  		// Other side sent a nil or default value.
   810  		*z = Int{}
   811  		return nil
   812  	}
   813  	b := buf[0]
   814  	if b>>1 != intGobVersion {
   815  		return fmt.Errorf("Int.GobDecode: encoding version %d not supported", b>>1)
   816  	}
   817  	z.neg = b&1 != 0
   818  	z.abs = z.abs.setBytes(buf[1:])
   819  	return nil
   820  }
   821  
   822  // MarshalJSON implements the json.Marshaler interface.
   823  func (z *Int) MarshalJSON() ([]byte, error) {
   824  	// TODO(gri): get rid of the []byte/string conversions
   825  	return []byte(z.String()), nil
   826  }
   827  
   828  // UnmarshalJSON implements the json.Unmarshaler interface.
   829  func (z *Int) UnmarshalJSON(text []byte) error {
   830  	// TODO(gri): get rid of the []byte/string conversions
   831  	if _, ok := z.SetString(string(text), 0); !ok {
   832  		return fmt.Errorf("math/big: cannot unmarshal %q into a *big.Int", text)
   833  	}
   834  	return nil
   835  }
   836  
   837  // MarshalText implements the encoding.TextMarshaler interface.
   838  func (z *Int) MarshalText() (text []byte, err error) {
   839  	return []byte(z.String()), nil
   840  }
   841  
   842  // UnmarshalText implements the encoding.TextUnmarshaler interface.
   843  func (z *Int) UnmarshalText(text []byte) error {
   844  	if _, ok := z.SetString(string(text), 0); !ok {
   845  		return fmt.Errorf("math/big: cannot unmarshal %q into a *big.Int", text)
   846  	}
   847  	return nil
   848  }