github.com/varialus/godfly@v0.0.0-20130904042352-1934f9f095ab/src/pkg/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 "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 z 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 z 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; 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 if y.neg || len(y.abs) == 0 { 583 return z.SetInt64(1) 584 } 585 // y > 0 586 587 var mWords nat 588 if m != nil { 589 mWords = m.abs // m.abs may be nil for m == 0 590 } 591 592 z.abs = z.abs.expNN(x.abs, y.abs, mWords) 593 z.neg = len(z.abs) > 0 && x.neg && y.abs[0]&1 == 1 // 0 has no sign 594 return z 595 } 596 597 // GCD sets z to the greatest common divisor of a and b, which both must 598 // be > 0, and returns z. 599 // If x and y are not nil, GCD sets x and y such that z = a*x + b*y. 600 // If either a or b is <= 0, GCD sets z = x = y = 0. 601 func (z *Int) GCD(x, y, a, b *Int) *Int { 602 if a.Sign() <= 0 || b.Sign() <= 0 { 603 z.SetInt64(0) 604 if x != nil { 605 x.SetInt64(0) 606 } 607 if y != nil { 608 y.SetInt64(0) 609 } 610 return z 611 } 612 if x == nil && y == nil { 613 return z.binaryGCD(a, b) 614 } 615 616 A := new(Int).Set(a) 617 B := new(Int).Set(b) 618 619 X := new(Int) 620 Y := new(Int).SetInt64(1) 621 622 lastX := new(Int).SetInt64(1) 623 lastY := new(Int) 624 625 q := new(Int) 626 temp := new(Int) 627 628 for len(B.abs) > 0 { 629 r := new(Int) 630 q, r = q.QuoRem(A, B, r) 631 632 A, B = B, r 633 634 temp.Set(X) 635 X.Mul(X, q) 636 X.neg = !X.neg 637 X.Add(X, lastX) 638 lastX.Set(temp) 639 640 temp.Set(Y) 641 Y.Mul(Y, q) 642 Y.neg = !Y.neg 643 Y.Add(Y, lastY) 644 lastY.Set(temp) 645 } 646 647 if x != nil { 648 *x = *lastX 649 } 650 651 if y != nil { 652 *y = *lastY 653 } 654 655 *z = *A 656 return z 657 } 658 659 // binaryGCD sets z to the greatest common divisor of a and b, which both must 660 // be > 0, and returns z. 661 // See Knuth, The Art of Computer Programming, Vol. 2, Section 4.5.2, Algorithm B. 662 func (z *Int) binaryGCD(a, b *Int) *Int { 663 u := z 664 v := new(Int) 665 666 // use one Euclidean iteration to ensure that u and v are approx. the same size 667 switch { 668 case len(a.abs) > len(b.abs): 669 u.Set(b) 670 v.Rem(a, b) 671 case len(a.abs) < len(b.abs): 672 u.Set(a) 673 v.Rem(b, a) 674 default: 675 u.Set(a) 676 v.Set(b) 677 } 678 679 // v might be 0 now 680 if len(v.abs) == 0 { 681 return u 682 } 683 // u > 0 && v > 0 684 685 // determine largest k such that u = u' << k, v = v' << k 686 k := u.abs.trailingZeroBits() 687 if vk := v.abs.trailingZeroBits(); vk < k { 688 k = vk 689 } 690 u.Rsh(u, k) 691 v.Rsh(v, k) 692 693 // determine t (we know that u > 0) 694 t := new(Int) 695 if u.abs[0]&1 != 0 { 696 // u is odd 697 t.Neg(v) 698 } else { 699 t.Set(u) 700 } 701 702 for len(t.abs) > 0 { 703 // reduce t 704 t.Rsh(t, t.abs.trailingZeroBits()) 705 if t.neg { 706 v, t = t, v 707 v.neg = len(v.abs) > 0 && !v.neg // 0 has no sign 708 } else { 709 u, t = t, u 710 } 711 t.Sub(u, v) 712 } 713 714 return z.Lsh(u, k) 715 } 716 717 // ProbablyPrime performs n Miller-Rabin tests to check whether x is prime. 718 // If it returns true, x is prime with probability 1 - 1/4^n. 719 // If it returns false, x is not prime. 720 func (x *Int) ProbablyPrime(n int) bool { 721 return !x.neg && x.abs.probablyPrime(n) 722 } 723 724 // Rand sets z to a pseudo-random number in [0, n) and returns z. 725 func (z *Int) Rand(rnd *rand.Rand, n *Int) *Int { 726 z.neg = false 727 if n.neg == true || len(n.abs) == 0 { 728 z.abs = nil 729 return z 730 } 731 z.abs = z.abs.random(rnd, n.abs, n.abs.bitLen()) 732 return z 733 } 734 735 // ModInverse sets z to the multiplicative inverse of g in the group ℤ/pℤ (where 736 // p is a prime) and returns z. 737 func (z *Int) ModInverse(g, p *Int) *Int { 738 var d Int 739 d.GCD(z, nil, g, p) 740 // x and y are such that g*x + p*y = d. Since p is prime, d = 1. Taking 741 // that modulo p results in g*x = 1, therefore x is the inverse element. 742 if z.neg { 743 z.Add(z, p) 744 } 745 return z 746 } 747 748 // Lsh sets z = x << n and returns z. 749 func (z *Int) Lsh(x *Int, n uint) *Int { 750 z.abs = z.abs.shl(x.abs, n) 751 z.neg = x.neg 752 return z 753 } 754 755 // Rsh sets z = x >> n and returns z. 756 func (z *Int) Rsh(x *Int, n uint) *Int { 757 if x.neg { 758 // (-x) >> s == ^(x-1) >> s == ^((x-1) >> s) == -(((x-1) >> s) + 1) 759 t := z.abs.sub(x.abs, natOne) // no underflow because |x| > 0 760 t = t.shr(t, n) 761 z.abs = t.add(t, natOne) 762 z.neg = true // z cannot be zero if x is negative 763 return z 764 } 765 766 z.abs = z.abs.shr(x.abs, n) 767 z.neg = false 768 return z 769 } 770 771 // Bit returns the value of the i'th bit of x. That is, it 772 // returns (x>>i)&1. The bit index i must be >= 0. 773 func (x *Int) Bit(i int) uint { 774 if i == 0 { 775 // optimization for common case: odd/even test of x 776 if len(x.abs) > 0 { 777 return uint(x.abs[0] & 1) // bit 0 is same for -x 778 } 779 return 0 780 } 781 if i < 0 { 782 panic("negative bit index") 783 } 784 if x.neg { 785 t := nat(nil).sub(x.abs, natOne) 786 return t.bit(uint(i)) ^ 1 787 } 788 789 return x.abs.bit(uint(i)) 790 } 791 792 // SetBit sets z to x, with x's i'th bit set to b (0 or 1). 793 // That is, if b is 1 SetBit sets z = x | (1 << i); 794 // if b is 0 SetBit sets z = x &^ (1 << i). If b is not 0 or 1, 795 // SetBit will panic. 796 func (z *Int) SetBit(x *Int, i int, b uint) *Int { 797 if i < 0 { 798 panic("negative bit index") 799 } 800 if x.neg { 801 t := z.abs.sub(x.abs, natOne) 802 t = t.setBit(t, uint(i), b^1) 803 z.abs = t.add(t, natOne) 804 z.neg = len(z.abs) > 0 805 return z 806 } 807 z.abs = z.abs.setBit(x.abs, uint(i), b) 808 z.neg = false 809 return z 810 } 811 812 // And sets z = x & y and returns z. 813 func (z *Int) And(x, y *Int) *Int { 814 if x.neg == y.neg { 815 if x.neg { 816 // (-x) & (-y) == ^(x-1) & ^(y-1) == ^((x-1) | (y-1)) == -(((x-1) | (y-1)) + 1) 817 x1 := nat(nil).sub(x.abs, natOne) 818 y1 := nat(nil).sub(y.abs, natOne) 819 z.abs = z.abs.add(z.abs.or(x1, y1), natOne) 820 z.neg = true // z cannot be zero if x and y are negative 821 return z 822 } 823 824 // x & y == x & y 825 z.abs = z.abs.and(x.abs, y.abs) 826 z.neg = false 827 return z 828 } 829 830 // x.neg != y.neg 831 if x.neg { 832 x, y = y, x // & is symmetric 833 } 834 835 // x & (-y) == x & ^(y-1) == x &^ (y-1) 836 y1 := nat(nil).sub(y.abs, natOne) 837 z.abs = z.abs.andNot(x.abs, y1) 838 z.neg = false 839 return z 840 } 841 842 // AndNot sets z = x &^ y and returns z. 843 func (z *Int) AndNot(x, y *Int) *Int { 844 if x.neg == y.neg { 845 if x.neg { 846 // (-x) &^ (-y) == ^(x-1) &^ ^(y-1) == ^(x-1) & (y-1) == (y-1) &^ (x-1) 847 x1 := nat(nil).sub(x.abs, natOne) 848 y1 := nat(nil).sub(y.abs, natOne) 849 z.abs = z.abs.andNot(y1, x1) 850 z.neg = false 851 return z 852 } 853 854 // x &^ y == x &^ y 855 z.abs = z.abs.andNot(x.abs, y.abs) 856 z.neg = false 857 return z 858 } 859 860 if x.neg { 861 // (-x) &^ y == ^(x-1) &^ y == ^(x-1) & ^y == ^((x-1) | y) == -(((x-1) | y) + 1) 862 x1 := nat(nil).sub(x.abs, natOne) 863 z.abs = z.abs.add(z.abs.or(x1, y.abs), natOne) 864 z.neg = true // z cannot be zero if x is negative and y is positive 865 return z 866 } 867 868 // x &^ (-y) == x &^ ^(y-1) == x & (y-1) 869 y1 := nat(nil).add(y.abs, natOne) 870 z.abs = z.abs.and(x.abs, y1) 871 z.neg = false 872 return z 873 } 874 875 // Or sets z = x | y and returns z. 876 func (z *Int) Or(x, y *Int) *Int { 877 if x.neg == y.neg { 878 if x.neg { 879 // (-x) | (-y) == ^(x-1) | ^(y-1) == ^((x-1) & (y-1)) == -(((x-1) & (y-1)) + 1) 880 x1 := nat(nil).sub(x.abs, natOne) 881 y1 := nat(nil).sub(y.abs, natOne) 882 z.abs = z.abs.add(z.abs.and(x1, y1), natOne) 883 z.neg = true // z cannot be zero if x and y are negative 884 return z 885 } 886 887 // x | y == x | y 888 z.abs = z.abs.or(x.abs, y.abs) 889 z.neg = false 890 return z 891 } 892 893 // x.neg != y.neg 894 if x.neg { 895 x, y = y, x // | is symmetric 896 } 897 898 // x | (-y) == x | ^(y-1) == ^((y-1) &^ x) == -(^((y-1) &^ x) + 1) 899 y1 := nat(nil).sub(y.abs, natOne) 900 z.abs = z.abs.add(z.abs.andNot(y1, x.abs), natOne) 901 z.neg = true // z cannot be zero if one of x or y is negative 902 return z 903 } 904 905 // Xor sets z = x ^ y and returns z. 906 func (z *Int) Xor(x, y *Int) *Int { 907 if x.neg == y.neg { 908 if x.neg { 909 // (-x) ^ (-y) == ^(x-1) ^ ^(y-1) == (x-1) ^ (y-1) 910 x1 := nat(nil).sub(x.abs, natOne) 911 y1 := nat(nil).sub(y.abs, natOne) 912 z.abs = z.abs.xor(x1, y1) 913 z.neg = false 914 return z 915 } 916 917 // x ^ y == x ^ y 918 z.abs = z.abs.xor(x.abs, y.abs) 919 z.neg = false 920 return z 921 } 922 923 // x.neg != y.neg 924 if x.neg { 925 x, y = y, x // ^ is symmetric 926 } 927 928 // x ^ (-y) == x ^ ^(y-1) == ^(x ^ (y-1)) == -((x ^ (y-1)) + 1) 929 y1 := nat(nil).sub(y.abs, natOne) 930 z.abs = z.abs.add(z.abs.xor(x.abs, y1), natOne) 931 z.neg = true // z cannot be zero if only one of x or y is negative 932 return z 933 } 934 935 // Not sets z = ^x and returns z. 936 func (z *Int) Not(x *Int) *Int { 937 if x.neg { 938 // ^(-x) == ^(^(x-1)) == x-1 939 z.abs = z.abs.sub(x.abs, natOne) 940 z.neg = false 941 return z 942 } 943 944 // ^x == -x-1 == -(x+1) 945 z.abs = z.abs.add(x.abs, natOne) 946 z.neg = true // z cannot be zero if x is positive 947 return z 948 } 949 950 // Gob codec version. Permits backward-compatible changes to the encoding. 951 const intGobVersion byte = 1 952 953 // GobEncode implements the gob.GobEncoder interface. 954 func (x *Int) GobEncode() ([]byte, error) { 955 if x == nil { 956 return nil, nil 957 } 958 buf := make([]byte, 1+len(x.abs)*_S) // extra byte for version and sign bit 959 i := x.abs.bytes(buf) - 1 // i >= 0 960 b := intGobVersion << 1 // make space for sign bit 961 if x.neg { 962 b |= 1 963 } 964 buf[i] = b 965 return buf[i:], nil 966 } 967 968 // GobDecode implements the gob.GobDecoder interface. 969 func (z *Int) GobDecode(buf []byte) error { 970 if len(buf) == 0 { 971 // Other side sent a nil or default value. 972 *z = Int{} 973 return nil 974 } 975 b := buf[0] 976 if b>>1 != intGobVersion { 977 return errors.New(fmt.Sprintf("Int.GobDecode: encoding version %d not supported", b>>1)) 978 } 979 z.neg = b&1 != 0 980 z.abs = z.abs.setBytes(buf[1:]) 981 return nil 982 } 983 984 // MarshalJSON implements the json.Marshaler interface. 985 func (x *Int) MarshalJSON() ([]byte, error) { 986 // TODO(gri): get rid of the []byte/string conversions 987 return []byte(x.String()), nil 988 } 989 990 // UnmarshalJSON implements the json.Unmarshaler interface. 991 func (z *Int) UnmarshalJSON(x []byte) error { 992 // TODO(gri): get rid of the []byte/string conversions 993 _, ok := z.SetString(string(x), 0) 994 if !ok { 995 return fmt.Errorf("math/big: cannot unmarshal %s into a *big.Int", x) 996 } 997 return nil 998 }