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 // Jacobi returns the Jacobi symbol (x/y), either +1, -1, or 0. 587 // The y argument must be an odd integer. 588 func Jacobi(x, y *Int) int { 589 if len(y.abs) == 0 || y.abs[0]&1 == 0 { 590 panic(fmt.Sprintf("big: invalid 2nd argument to Int.Jacobi: need odd integer but got %s", y)) 591 } 592 593 // We use the formulation described in chapter 2, section 2.4, 594 // "The Yacas Book of Algorithms": 595 // http://yacas.sourceforge.net/Algo.book.pdf 596 597 var a, b, c Int 598 a.Set(x) 599 b.Set(y) 600 j := 1 601 602 if b.neg { 603 if a.neg { 604 j = -1 605 } 606 b.neg = false 607 } 608 609 for { 610 if b.Cmp(intOne) == 0 { 611 return j 612 } 613 if len(a.abs) == 0 { 614 return 0 615 } 616 a.Mod(&a, &b) 617 if len(a.abs) == 0 { 618 return 0 619 } 620 // a > 0 621 622 // handle factors of 2 in 'a' 623 s := a.abs.trailingZeroBits() 624 if s&1 != 0 { 625 bmod8 := b.abs[0] & 7 626 if bmod8 == 3 || bmod8 == 5 { 627 j = -j 628 } 629 } 630 c.Rsh(&a, s) // a = 2^s*c 631 632 // swap numerator and denominator 633 if b.abs[0]&3 == 3 && c.abs[0]&3 == 3 { 634 j = -j 635 } 636 a.Set(&b) 637 b.Set(&c) 638 } 639 } 640 641 // ModSqrt sets z to a square root of x mod p if such a square root exists, and 642 // returns z. The modulus p must be an odd prime. If x is not a square mod p, 643 // ModSqrt leaves z unchanged and returns nil. This function panics if p is 644 // not an odd integer. 645 func (z *Int) ModSqrt(x, p *Int) *Int { 646 switch Jacobi(x, p) { 647 case -1: 648 return nil // x is not a square mod p 649 case 0: 650 return z.SetInt64(0) // sqrt(0) mod p = 0 651 case 1: 652 break 653 } 654 if x.neg || x.Cmp(p) >= 0 { // ensure 0 <= x < p 655 x = new(Int).Mod(x, p) 656 } 657 658 // Break p-1 into s*2^e such that s is odd. 659 var s Int 660 s.Sub(p, intOne) 661 e := s.abs.trailingZeroBits() 662 s.Rsh(&s, e) 663 664 // find some non-square n 665 var n Int 666 n.SetInt64(2) 667 for Jacobi(&n, p) != -1 { 668 n.Add(&n, intOne) 669 } 670 671 // Core of the Tonelli-Shanks algorithm. Follows the description in 672 // section 6 of "Square roots from 1; 24, 51, 10 to Dan Shanks" by Ezra 673 // Brown: 674 // https://www.maa.org/sites/default/files/pdf/upload_library/22/Polya/07468342.di020786.02p0470a.pdf 675 var y, b, g, t Int 676 y.Add(&s, intOne) 677 y.Rsh(&y, 1) 678 y.Exp(x, &y, p) // y = x^((s+1)/2) 679 b.Exp(x, &s, p) // b = x^s 680 g.Exp(&n, &s, p) // g = n^s 681 r := e 682 for { 683 // find the least m such that ord_p(b) = 2^m 684 var m uint 685 t.Set(&b) 686 for t.Cmp(intOne) != 0 { 687 t.Mul(&t, &t).Mod(&t, p) 688 m++ 689 } 690 691 if m == 0 { 692 return z.Set(&y) 693 } 694 695 t.SetInt64(0).SetBit(&t, int(r-m-1), 1).Exp(&g, &t, p) 696 // t = g^(2^(r-m-1)) mod p 697 g.Mul(&t, &t).Mod(&g, p) // g = g^(2^(r-m)) mod p 698 y.Mul(&y, &t).Mod(&y, p) 699 b.Mul(&b, &g).Mod(&b, p) 700 r = m 701 } 702 } 703 704 // Lsh sets z = x << n and returns z. 705 func (z *Int) Lsh(x *Int, n uint) *Int { 706 z.abs = z.abs.shl(x.abs, n) 707 z.neg = x.neg 708 return z 709 } 710 711 // Rsh sets z = x >> n and returns z. 712 func (z *Int) Rsh(x *Int, n uint) *Int { 713 if x.neg { 714 // (-x) >> s == ^(x-1) >> s == ^((x-1) >> s) == -(((x-1) >> s) + 1) 715 t := z.abs.sub(x.abs, natOne) // no underflow because |x| > 0 716 t = t.shr(t, n) 717 z.abs = t.add(t, natOne) 718 z.neg = true // z cannot be zero if x is negative 719 return z 720 } 721 722 z.abs = z.abs.shr(x.abs, n) 723 z.neg = false 724 return z 725 } 726 727 // Bit returns the value of the i'th bit of x. That is, it 728 // returns (x>>i)&1. The bit index i must be >= 0. 729 func (x *Int) Bit(i int) uint { 730 if i == 0 { 731 // optimization for common case: odd/even test of x 732 if len(x.abs) > 0 { 733 return uint(x.abs[0] & 1) // bit 0 is same for -x 734 } 735 return 0 736 } 737 if i < 0 { 738 panic("negative bit index") 739 } 740 if x.neg { 741 t := nat(nil).sub(x.abs, natOne) 742 return t.bit(uint(i)) ^ 1 743 } 744 745 return x.abs.bit(uint(i)) 746 } 747 748 // SetBit sets z to x, with x's i'th bit set to b (0 or 1). 749 // That is, if b is 1 SetBit sets z = x | (1 << i); 750 // if b is 0 SetBit sets z = x &^ (1 << i). If b is not 0 or 1, 751 // SetBit will panic. 752 func (z *Int) SetBit(x *Int, i int, b uint) *Int { 753 if i < 0 { 754 panic("negative bit index") 755 } 756 if x.neg { 757 t := z.abs.sub(x.abs, natOne) 758 t = t.setBit(t, uint(i), b^1) 759 z.abs = t.add(t, natOne) 760 z.neg = len(z.abs) > 0 761 return z 762 } 763 z.abs = z.abs.setBit(x.abs, uint(i), b) 764 z.neg = false 765 return z 766 } 767 768 // And sets z = x & y and returns z. 769 func (z *Int) And(x, y *Int) *Int { 770 if x.neg == y.neg { 771 if x.neg { 772 // (-x) & (-y) == ^(x-1) & ^(y-1) == ^((x-1) | (y-1)) == -(((x-1) | (y-1)) + 1) 773 x1 := nat(nil).sub(x.abs, natOne) 774 y1 := nat(nil).sub(y.abs, natOne) 775 z.abs = z.abs.add(z.abs.or(x1, y1), natOne) 776 z.neg = true // z cannot be zero if x and y are negative 777 return z 778 } 779 780 // x & y == x & y 781 z.abs = z.abs.and(x.abs, y.abs) 782 z.neg = false 783 return z 784 } 785 786 // x.neg != y.neg 787 if x.neg { 788 x, y = y, x // & is symmetric 789 } 790 791 // x & (-y) == x & ^(y-1) == x &^ (y-1) 792 y1 := nat(nil).sub(y.abs, natOne) 793 z.abs = z.abs.andNot(x.abs, y1) 794 z.neg = false 795 return z 796 } 797 798 // AndNot sets z = x &^ y and returns z. 799 func (z *Int) AndNot(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) == (y-1) &^ (x-1) 803 x1 := nat(nil).sub(x.abs, natOne) 804 y1 := nat(nil).sub(y.abs, natOne) 805 z.abs = z.abs.andNot(y1, x1) 806 z.neg = false 807 return z 808 } 809 810 // x &^ y == x &^ y 811 z.abs = z.abs.andNot(x.abs, y.abs) 812 z.neg = false 813 return z 814 } 815 816 if x.neg { 817 // (-x) &^ y == ^(x-1) &^ y == ^(x-1) & ^y == ^((x-1) | y) == -(((x-1) | y) + 1) 818 x1 := nat(nil).sub(x.abs, natOne) 819 z.abs = z.abs.add(z.abs.or(x1, y.abs), natOne) 820 z.neg = true // z cannot be zero if x is negative and y is positive 821 return z 822 } 823 824 // x &^ (-y) == x &^ ^(y-1) == x & (y-1) 825 y1 := nat(nil).sub(y.abs, natOne) 826 z.abs = z.abs.and(x.abs, y1) 827 z.neg = false 828 return z 829 } 830 831 // Or sets z = x | y and returns z. 832 func (z *Int) Or(x, y *Int) *Int { 833 if x.neg == y.neg { 834 if x.neg { 835 // (-x) | (-y) == ^(x-1) | ^(y-1) == ^((x-1) & (y-1)) == -(((x-1) & (y-1)) + 1) 836 x1 := nat(nil).sub(x.abs, natOne) 837 y1 := nat(nil).sub(y.abs, natOne) 838 z.abs = z.abs.add(z.abs.and(x1, y1), natOne) 839 z.neg = true // z cannot be zero if x and y are negative 840 return z 841 } 842 843 // x | y == x | y 844 z.abs = z.abs.or(x.abs, y.abs) 845 z.neg = false 846 return z 847 } 848 849 // x.neg != y.neg 850 if x.neg { 851 x, y = y, x // | is symmetric 852 } 853 854 // x | (-y) == x | ^(y-1) == ^((y-1) &^ x) == -(^((y-1) &^ x) + 1) 855 y1 := nat(nil).sub(y.abs, natOne) 856 z.abs = z.abs.add(z.abs.andNot(y1, x.abs), natOne) 857 z.neg = true // z cannot be zero if one of x or y is negative 858 return z 859 } 860 861 // Xor sets z = x ^ y and returns z. 862 func (z *Int) Xor(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) 866 x1 := nat(nil).sub(x.abs, natOne) 867 y1 := nat(nil).sub(y.abs, natOne) 868 z.abs = z.abs.xor(x1, y1) 869 z.neg = false 870 return z 871 } 872 873 // x ^ y == x ^ y 874 z.abs = z.abs.xor(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) == ^(x ^ (y-1)) == -((x ^ (y-1)) + 1) 885 y1 := nat(nil).sub(y.abs, natOne) 886 z.abs = z.abs.add(z.abs.xor(x.abs, y1), natOne) 887 z.neg = true // z cannot be zero if only one of x or y is negative 888 return z 889 } 890 891 // Not sets z = ^x and returns z. 892 func (z *Int) Not(x *Int) *Int { 893 if x.neg { 894 // ^(-x) == ^(^(x-1)) == x-1 895 z.abs = z.abs.sub(x.abs, natOne) 896 z.neg = false 897 return z 898 } 899 900 // ^x == -x-1 == -(x+1) 901 z.abs = z.abs.add(x.abs, natOne) 902 z.neg = true // z cannot be zero if x is positive 903 return z 904 } 905 906 // Gob codec version. Permits backward-compatible changes to the encoding. 907 const intGobVersion byte = 1 908 909 // GobEncode implements the gob.GobEncoder interface. 910 func (x *Int) GobEncode() ([]byte, error) { 911 if x == nil { 912 return nil, nil 913 } 914 buf := make([]byte, 1+len(x.abs)*_S) // extra byte for version and sign bit 915 i := x.abs.bytes(buf) - 1 // i >= 0 916 b := intGobVersion << 1 // make space for sign bit 917 if x.neg { 918 b |= 1 919 } 920 buf[i] = b 921 return buf[i:], nil 922 } 923 924 // GobDecode implements the gob.GobDecoder interface. 925 func (z *Int) GobDecode(buf []byte) error { 926 if len(buf) == 0 { 927 // Other side sent a nil or default value. 928 *z = Int{} 929 return nil 930 } 931 b := buf[0] 932 if b>>1 != intGobVersion { 933 return fmt.Errorf("Int.GobDecode: encoding version %d not supported", b>>1) 934 } 935 z.neg = b&1 != 0 936 z.abs = z.abs.setBytes(buf[1:]) 937 return nil 938 } 939 940 // MarshalJSON implements the json.Marshaler interface. 941 func (z *Int) MarshalJSON() ([]byte, error) { 942 // TODO(gri): get rid of the []byte/string conversions 943 return []byte(z.String()), nil 944 } 945 946 // UnmarshalJSON implements the json.Unmarshaler interface. 947 func (z *Int) UnmarshalJSON(text []byte) error { 948 // TODO(gri): get rid of the []byte/string conversions 949 if _, ok := z.SetString(string(text), 0); !ok { 950 return fmt.Errorf("math/big: cannot unmarshal %q into a *big.Int", text) 951 } 952 return nil 953 } 954 955 // MarshalText implements the encoding.TextMarshaler interface. 956 func (z *Int) MarshalText() (text []byte, err error) { 957 return []byte(z.String()), nil 958 } 959 960 // UnmarshalText implements the encoding.TextUnmarshaler interface. 961 func (z *Int) UnmarshalText(text []byte) error { 962 if _, ok := z.SetString(string(text), 0); !ok { 963 return fmt.Errorf("math/big: cannot unmarshal %q into a *big.Int", text) 964 } 965 return nil 966 } 967