...
Run Format

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	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 < |y|
   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		r := new(Int)
   463		for len(B.abs) > 0 {
   464			q, r = q.QuoRem(A, B, r)
   465	
   466			A, B, r = B, r, A
   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			// must set v before u since u may be alias for a or b (was issue #11284)
   504			v.Rem(a, b)
   505			u.Set(b)
   506		case len(a.abs) < len(b.abs):
   507			v.Rem(b, a)
   508			u.Set(a)
   509		default:
   510			v.Set(b)
   511			u.Set(a)
   512		}
   513		// a, b must not be used anymore (may be aliases with u)
   514	
   515		// v might be 0 now
   516		if len(v.abs) == 0 {
   517			return u
   518		}
   519		// u > 0 && v > 0
   520	
   521		// determine largest k such that u = u' << k, v = v' << k
   522		k := u.abs.trailingZeroBits()
   523		if vk := v.abs.trailingZeroBits(); vk < k {
   524			k = vk
   525		}
   526		u.Rsh(u, k)
   527		v.Rsh(v, k)
   528	
   529		// determine t (we know that u > 0)
   530		t := new(Int)
   531		if u.abs[0]&1 != 0 {
   532			// u is odd
   533			t.Neg(v)
   534		} else {
   535			t.Set(u)
   536		}
   537	
   538		for len(t.abs) > 0 {
   539			// reduce t
   540			t.Rsh(t, t.abs.trailingZeroBits())
   541			if t.neg {
   542				v, t = t, v
   543				v.neg = len(v.abs) > 0 && !v.neg // 0 has no sign
   544			} else {
   545				u, t = t, u
   546			}
   547			t.Sub(u, v)
   548		}
   549	
   550		return z.Lsh(u, k)
   551	}
   552	
   553	// ProbablyPrime performs n Miller-Rabin tests to check whether x is prime.
   554	// If x is prime, it returns true.
   555	// If x is not prime, it returns false with probability at least 1 - ¼ⁿ.
   556	//
   557	// It is not suitable for judging primes that an adversary may have crafted
   558	// to fool this test.
   559	func (x *Int) ProbablyPrime(n int) bool {
   560		if n <= 0 {
   561			panic("non-positive n for ProbablyPrime")
   562		}
   563		return !x.neg && x.abs.probablyPrime(n)
   564	}
   565	
   566	// Rand sets z to a pseudo-random number in [0, n) and returns z.
   567	func (z *Int) Rand(rnd *rand.Rand, n *Int) *Int {
   568		z.neg = false
   569		if n.neg == true || len(n.abs) == 0 {
   570			z.abs = nil
   571			return z
   572		}
   573		z.abs = z.abs.random(rnd, n.abs, n.abs.bitLen())
   574		return z
   575	}
   576	
   577	// ModInverse sets z to the multiplicative inverse of g in the ring ℤ/nℤ
   578	// and returns z. If g and n are not relatively prime, the result is undefined.
   579	func (z *Int) ModInverse(g, n *Int) *Int {
   580		var d Int
   581		d.GCD(z, nil, g, n)
   582		// x and y are such that g*x + n*y = d. Since g and n are
   583		// relatively prime, d = 1. Taking that modulo n results in
   584		// g*x = 1, therefore x is the inverse element.
   585		if z.neg {
   586			z.Add(z, n)
   587		}
   588		return z
   589	}
   590	
   591	// Jacobi returns the Jacobi symbol (x/y), either +1, -1, or 0.
   592	// The y argument must be an odd integer.
   593	func Jacobi(x, y *Int) int {
   594		if len(y.abs) == 0 || y.abs[0]&1 == 0 {
   595			panic(fmt.Sprintf("big: invalid 2nd argument to Int.Jacobi: need odd integer but got %s", y))
   596		}
   597	
   598		// We use the formulation described in chapter 2, section 2.4,
   599		// "The Yacas Book of Algorithms":
   600		// http://yacas.sourceforge.net/Algo.book.pdf
   601	
   602		var a, b, c Int
   603		a.Set(x)
   604		b.Set(y)
   605		j := 1
   606	
   607		if b.neg {
   608			if a.neg {
   609				j = -1
   610			}
   611			b.neg = false
   612		}
   613	
   614		for {
   615			if b.Cmp(intOne) == 0 {
   616				return j
   617			}
   618			if len(a.abs) == 0 {
   619				return 0
   620			}
   621			a.Mod(&a, &b)
   622			if len(a.abs) == 0 {
   623				return 0
   624			}
   625			// a > 0
   626	
   627			// handle factors of 2 in 'a'
   628			s := a.abs.trailingZeroBits()
   629			if s&1 != 0 {
   630				bmod8 := b.abs[0] & 7
   631				if bmod8 == 3 || bmod8 == 5 {
   632					j = -j
   633				}
   634			}
   635			c.Rsh(&a, s) // a = 2^s*c
   636	
   637			// swap numerator and denominator
   638			if b.abs[0]&3 == 3 && c.abs[0]&3 == 3 {
   639				j = -j
   640			}
   641			a.Set(&b)
   642			b.Set(&c)
   643		}
   644	}
   645	
   646	// modSqrt3Mod4 uses the identity
   647	//      (a^((p+1)/4))^2  mod p
   648	//   == u^(p+1)          mod p
   649	//   == u^2              mod p
   650	// to calculate the square root of any quadratic residue mod p quickly for 3
   651	// mod 4 primes.
   652	func (z *Int) modSqrt3Mod4Prime(x, p *Int) *Int {
   653		z.Set(p)         // z = p
   654		z.Add(z, intOne) // z = p + 1
   655		z.Rsh(z, 2)      // z = (p + 1) / 4
   656		z.Exp(x, z, p)   // z = x^z mod p
   657		return z
   658	}
   659	
   660	// modSqrtTonelliShanks uses the Tonelli-Shanks algorithm to find the square
   661	// root of a quadratic residue modulo any prime.
   662	func (z *Int) modSqrtTonelliShanks(x, p *Int) *Int {
   663		// Break p-1 into s*2^e such that s is odd.
   664		var s Int
   665		s.Sub(p, intOne)
   666		e := s.abs.trailingZeroBits()
   667		s.Rsh(&s, e)
   668	
   669		// find some non-square n
   670		var n Int
   671		n.SetInt64(2)
   672		for Jacobi(&n, p) != -1 {
   673			n.Add(&n, intOne)
   674		}
   675	
   676		// Core of the Tonelli-Shanks algorithm. Follows the description in
   677		// section 6 of "Square roots from 1; 24, 51, 10 to Dan Shanks" by Ezra
   678		// Brown:
   679		// https://www.maa.org/sites/default/files/pdf/upload_library/22/Polya/07468342.di020786.02p0470a.pdf
   680		var y, b, g, t Int
   681		y.Add(&s, intOne)
   682		y.Rsh(&y, 1)
   683		y.Exp(x, &y, p)  // y = x^((s+1)/2)
   684		b.Exp(x, &s, p)  // b = x^s
   685		g.Exp(&n, &s, p) // g = n^s
   686		r := e
   687		for {
   688			// find the least m such that ord_p(b) = 2^m
   689			var m uint
   690			t.Set(&b)
   691			for t.Cmp(intOne) != 0 {
   692				t.Mul(&t, &t).Mod(&t, p)
   693				m++
   694			}
   695	
   696			if m == 0 {
   697				return z.Set(&y)
   698			}
   699	
   700			t.SetInt64(0).SetBit(&t, int(r-m-1), 1).Exp(&g, &t, p)
   701			// t = g^(2^(r-m-1)) mod p
   702			g.Mul(&t, &t).Mod(&g, p) // g = g^(2^(r-m)) mod p
   703			y.Mul(&y, &t).Mod(&y, p)
   704			b.Mul(&b, &g).Mod(&b, p)
   705			r = m
   706		}
   707	}
   708	
   709	// ModSqrt sets z to a square root of x mod p if such a square root exists, and
   710	// returns z. The modulus p must be an odd prime. If x is not a square mod p,
   711	// ModSqrt leaves z unchanged and returns nil. This function panics if p is
   712	// not an odd integer.
   713	func (z *Int) ModSqrt(x, p *Int) *Int {
   714		switch Jacobi(x, p) {
   715		case -1:
   716			return nil // x is not a square mod p
   717		case 0:
   718			return z.SetInt64(0) // sqrt(0) mod p = 0
   719		case 1:
   720			break
   721		}
   722		if x.neg || x.Cmp(p) >= 0 { // ensure 0 <= x < p
   723			x = new(Int).Mod(x, p)
   724		}
   725	
   726		// Check whether p is 3 mod 4, and if so, use the faster algorithm.
   727		if len(p.abs) > 0 && p.abs[0]%4 == 3 {
   728			return z.modSqrt3Mod4Prime(x, p)
   729		}
   730		// Otherwise, use Tonelli-Shanks.
   731		return z.modSqrtTonelliShanks(x, p)
   732	}
   733	
   734	// Lsh sets z = x << n and returns z.
   735	func (z *Int) Lsh(x *Int, n uint) *Int {
   736		z.abs = z.abs.shl(x.abs, n)
   737		z.neg = x.neg
   738		return z
   739	}
   740	
   741	// Rsh sets z = x >> n and returns z.
   742	func (z *Int) Rsh(x *Int, n uint) *Int {
   743		if x.neg {
   744			// (-x) >> s == ^(x-1) >> s == ^((x-1) >> s) == -(((x-1) >> s) + 1)
   745			t := z.abs.sub(x.abs, natOne) // no underflow because |x| > 0
   746			t = t.shr(t, n)
   747			z.abs = t.add(t, natOne)
   748			z.neg = true // z cannot be zero if x is negative
   749			return z
   750		}
   751	
   752		z.abs = z.abs.shr(x.abs, n)
   753		z.neg = false
   754		return z
   755	}
   756	
   757	// Bit returns the value of the i'th bit of x. That is, it
   758	// returns (x>>i)&1. The bit index i must be >= 0.
   759	func (x *Int) Bit(i int) uint {
   760		if i == 0 {
   761			// optimization for common case: odd/even test of x
   762			if len(x.abs) > 0 {
   763				return uint(x.abs[0] & 1) // bit 0 is same for -x
   764			}
   765			return 0
   766		}
   767		if i < 0 {
   768			panic("negative bit index")
   769		}
   770		if x.neg {
   771			t := nat(nil).sub(x.abs, natOne)
   772			return t.bit(uint(i)) ^ 1
   773		}
   774	
   775		return x.abs.bit(uint(i))
   776	}
   777	
   778	// SetBit sets z to x, with x's i'th bit set to b (0 or 1).
   779	// That is, if b is 1 SetBit sets z = x | (1 << i);
   780	// if b is 0 SetBit sets z = x &^ (1 << i). If b is not 0 or 1,
   781	// SetBit will panic.
   782	func (z *Int) SetBit(x *Int, i int, b uint) *Int {
   783		if i < 0 {
   784			panic("negative bit index")
   785		}
   786		if x.neg {
   787			t := z.abs.sub(x.abs, natOne)
   788			t = t.setBit(t, uint(i), b^1)
   789			z.abs = t.add(t, natOne)
   790			z.neg = len(z.abs) > 0
   791			return z
   792		}
   793		z.abs = z.abs.setBit(x.abs, uint(i), b)
   794		z.neg = false
   795		return z
   796	}
   797	
   798	// And sets z = x & y and returns z.
   799	func (z *Int) And(x, y *Int) *Int {
   800		if x.neg == y.neg {
   801			if x.neg {
   802				// (-x) & (-y) == ^(x-1) & ^(y-1) == ^((x-1) | (y-1)) == -(((x-1) | (y-1)) + 1)
   803				x1 := nat(nil).sub(x.abs, natOne)
   804				y1 := nat(nil).sub(y.abs, natOne)
   805				z.abs = z.abs.add(z.abs.or(x1, y1), natOne)
   806				z.neg = true // z cannot be zero if x and y are negative
   807				return z
   808			}
   809	
   810			// x & y == x & y
   811			z.abs = z.abs.and(x.abs, y.abs)
   812			z.neg = false
   813			return z
   814		}
   815	
   816		// x.neg != y.neg
   817		if x.neg {
   818			x, y = y, x // & is symmetric
   819		}
   820	
   821		// x & (-y) == x & ^(y-1) == x &^ (y-1)
   822		y1 := nat(nil).sub(y.abs, natOne)
   823		z.abs = z.abs.andNot(x.abs, y1)
   824		z.neg = false
   825		return z
   826	}
   827	
   828	// AndNot sets z = x &^ y and returns z.
   829	func (z *Int) AndNot(x, y *Int) *Int {
   830		if x.neg == y.neg {
   831			if x.neg {
   832				// (-x) &^ (-y) == ^(x-1) &^ ^(y-1) == ^(x-1) & (y-1) == (y-1) &^ (x-1)
   833				x1 := nat(nil).sub(x.abs, natOne)
   834				y1 := nat(nil).sub(y.abs, natOne)
   835				z.abs = z.abs.andNot(y1, x1)
   836				z.neg = false
   837				return z
   838			}
   839	
   840			// x &^ y == x &^ y
   841			z.abs = z.abs.andNot(x.abs, y.abs)
   842			z.neg = false
   843			return z
   844		}
   845	
   846		if x.neg {
   847			// (-x) &^ y == ^(x-1) &^ y == ^(x-1) & ^y == ^((x-1) | y) == -(((x-1) | y) + 1)
   848			x1 := nat(nil).sub(x.abs, natOne)
   849			z.abs = z.abs.add(z.abs.or(x1, y.abs), natOne)
   850			z.neg = true // z cannot be zero if x is negative and y is positive
   851			return z
   852		}
   853	
   854		// x &^ (-y) == x &^ ^(y-1) == x & (y-1)
   855		y1 := nat(nil).sub(y.abs, natOne)
   856		z.abs = z.abs.and(x.abs, y1)
   857		z.neg = false
   858		return z
   859	}
   860	
   861	// Or sets z = x | y and returns z.
   862	func (z *Int) Or(x, y *Int) *Int {
   863		if x.neg == y.neg {
   864			if x.neg {
   865				// (-x) | (-y) == ^(x-1) | ^(y-1) == ^((x-1) & (y-1)) == -(((x-1) & (y-1)) + 1)
   866				x1 := nat(nil).sub(x.abs, natOne)
   867				y1 := nat(nil).sub(y.abs, natOne)
   868				z.abs = z.abs.add(z.abs.and(x1, y1), natOne)
   869				z.neg = true // z cannot be zero if x and y are negative
   870				return z
   871			}
   872	
   873			// x | y == x | y
   874			z.abs = z.abs.or(x.abs, y.abs)
   875			z.neg = false
   876			return z
   877		}
   878	
   879		// x.neg != y.neg
   880		if x.neg {
   881			x, y = y, x // | is symmetric
   882		}
   883	
   884		// x | (-y) == x | ^(y-1) == ^((y-1) &^ x) == -(^((y-1) &^ x) + 1)
   885		y1 := nat(nil).sub(y.abs, natOne)
   886		z.abs = z.abs.add(z.abs.andNot(y1, x.abs), natOne)
   887		z.neg = true // z cannot be zero if one of x or y is negative
   888		return z
   889	}
   890	
   891	// Xor sets z = x ^ y and returns z.
   892	func (z *Int) Xor(x, y *Int) *Int {
   893		if x.neg == y.neg {
   894			if x.neg {
   895				// (-x) ^ (-y) == ^(x-1) ^ ^(y-1) == (x-1) ^ (y-1)
   896				x1 := nat(nil).sub(x.abs, natOne)
   897				y1 := nat(nil).sub(y.abs, natOne)
   898				z.abs = z.abs.xor(x1, y1)
   899				z.neg = false
   900				return z
   901			}
   902	
   903			// x ^ y == x ^ y
   904			z.abs = z.abs.xor(x.abs, y.abs)
   905			z.neg = false
   906			return z
   907		}
   908	
   909		// x.neg != y.neg
   910		if x.neg {
   911			x, y = y, x // ^ is symmetric
   912		}
   913	
   914		// x ^ (-y) == x ^ ^(y-1) == ^(x ^ (y-1)) == -((x ^ (y-1)) + 1)
   915		y1 := nat(nil).sub(y.abs, natOne)
   916		z.abs = z.abs.add(z.abs.xor(x.abs, y1), natOne)
   917		z.neg = true // z cannot be zero if only one of x or y is negative
   918		return z
   919	}
   920	
   921	// Not sets z = ^x and returns z.
   922	func (z *Int) Not(x *Int) *Int {
   923		if x.neg {
   924			// ^(-x) == ^(^(x-1)) == x-1
   925			z.abs = z.abs.sub(x.abs, natOne)
   926			z.neg = false
   927			return z
   928		}
   929	
   930		// ^x == -x-1 == -(x+1)
   931		z.abs = z.abs.add(x.abs, natOne)
   932		z.neg = true // z cannot be zero if x is positive
   933		return z
   934	}
   935	

View as plain text