...
Run Format

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

View as plain text