github.com/mattn/go@v0.0.0-20171011075504-07f7db3ea99f/src/math/big/int.go (about) 1 // Copyright 2009 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 // This file implements signed multi-precision integers. 6 7 package big 8 9 import ( 10 "fmt" 11 "io" 12 "math/rand" 13 "strings" 14 ) 15 16 // An Int represents a signed multi-precision integer. 17 // The zero value for an Int represents the value 0. 18 type Int struct { 19 neg bool // sign 20 abs nat // absolute value of the integer 21 } 22 23 var intOne = &Int{false, natOne} 24 25 // Sign returns: 26 // 27 // -1 if x < 0 28 // 0 if x == 0 29 // +1 if x > 0 30 // 31 func (x *Int) Sign() int { 32 if len(x.abs) == 0 { 33 return 0 34 } 35 if x.neg { 36 return -1 37 } 38 return 1 39 } 40 41 // SetInt64 sets z to x and returns z. 42 func (z *Int) SetInt64(x int64) *Int { 43 neg := false 44 if x < 0 { 45 neg = true 46 x = -x 47 } 48 z.abs = z.abs.setUint64(uint64(x)) 49 z.neg = neg 50 return z 51 } 52 53 // SetUint64 sets z to x and returns z. 54 func (z *Int) SetUint64(x uint64) *Int { 55 z.abs = z.abs.setUint64(x) 56 z.neg = false 57 return z 58 } 59 60 // NewInt allocates and returns a new Int set to x. 61 func NewInt(x int64) *Int { 62 return new(Int).SetInt64(x) 63 } 64 65 // Set sets z to x and returns z. 66 func (z *Int) Set(x *Int) *Int { 67 if z != x { 68 z.abs = z.abs.set(x.abs) 69 z.neg = x.neg 70 } 71 return z 72 } 73 74 // Bits provides raw (unchecked but fast) access to x by returning its 75 // absolute value as a little-endian Word slice. The result and x share 76 // the same underlying array. 77 // Bits is intended to support implementation of missing low-level Int 78 // functionality outside this package; it should be avoided otherwise. 79 func (x *Int) Bits() []Word { 80 return x.abs 81 } 82 83 // SetBits provides raw (unchecked but fast) access to z by setting its 84 // value to abs, interpreted as a little-endian Word slice, and returning 85 // z. The result and abs share the same underlying array. 86 // SetBits is intended to support implementation of missing low-level Int 87 // functionality outside this package; it should be avoided otherwise. 88 func (z *Int) SetBits(abs []Word) *Int { 89 z.abs = nat(abs).norm() 90 z.neg = false 91 return z 92 } 93 94 // Abs sets z to |x| (the absolute value of x) and returns z. 95 func (z *Int) Abs(x *Int) *Int { 96 z.Set(x) 97 z.neg = false 98 return z 99 } 100 101 // Neg sets z to -x and returns z. 102 func (z *Int) Neg(x *Int) *Int { 103 z.Set(x) 104 z.neg = len(z.abs) > 0 && !z.neg // 0 has no sign 105 return z 106 } 107 108 // Add sets z to the sum x+y and returns z. 109 func (z *Int) Add(x, y *Int) *Int { 110 neg := x.neg 111 if x.neg == y.neg { 112 // x + y == x + y 113 // (-x) + (-y) == -(x + y) 114 z.abs = z.abs.add(x.abs, y.abs) 115 } else { 116 // x + (-y) == x - y == -(y - x) 117 // (-x) + y == y - x == -(x - y) 118 if x.abs.cmp(y.abs) >= 0 { 119 z.abs = z.abs.sub(x.abs, y.abs) 120 } else { 121 neg = !neg 122 z.abs = z.abs.sub(y.abs, x.abs) 123 } 124 } 125 z.neg = len(z.abs) > 0 && neg // 0 has no sign 126 return z 127 } 128 129 // Sub sets z to the difference x-y and returns z. 130 func (z *Int) Sub(x, y *Int) *Int { 131 neg := x.neg 132 if x.neg != y.neg { 133 // x - (-y) == x + y 134 // (-x) - y == -(x + y) 135 z.abs = z.abs.add(x.abs, y.abs) 136 } else { 137 // x - y == x - y == -(y - x) 138 // (-x) - (-y) == y - x == -(x - y) 139 if x.abs.cmp(y.abs) >= 0 { 140 z.abs = z.abs.sub(x.abs, y.abs) 141 } else { 142 neg = !neg 143 z.abs = z.abs.sub(y.abs, x.abs) 144 } 145 } 146 z.neg = len(z.abs) > 0 && neg // 0 has no sign 147 return z 148 } 149 150 // Mul sets z to the product x*y and returns z. 151 func (z *Int) Mul(x, y *Int) *Int { 152 // x * y == x * y 153 // x * (-y) == -(x * y) 154 // (-x) * y == -(x * y) 155 // (-x) * (-y) == x * y 156 if x == y { 157 z.abs = z.abs.sqr(x.abs) 158 z.neg = false 159 return z 160 } 161 z.abs = z.abs.mul(x.abs, y.abs) 162 z.neg = len(z.abs) > 0 && x.neg != y.neg // 0 has no sign 163 return z 164 } 165 166 // MulRange sets z to the product of all integers 167 // in the range [a, b] inclusively and returns z. 168 // If a > b (empty range), the result is 1. 169 func (z *Int) MulRange(a, b int64) *Int { 170 switch { 171 case a > b: 172 return z.SetInt64(1) // empty range 173 case a <= 0 && b >= 0: 174 return z.SetInt64(0) // range includes 0 175 } 176 // a <= b && (b < 0 || a > 0) 177 178 neg := false 179 if a < 0 { 180 neg = (b-a)&1 == 0 181 a, b = -b, -a 182 } 183 184 z.abs = z.abs.mulRange(uint64(a), uint64(b)) 185 z.neg = neg 186 return z 187 } 188 189 // Binomial sets z to the binomial coefficient of (n, k) and returns z. 190 func (z *Int) Binomial(n, k int64) *Int { 191 // reduce the number of multiplications by reducing k 192 if n/2 < k && k <= n { 193 k = n - k // Binomial(n, k) == Binomial(n, n-k) 194 } 195 var a, b Int 196 a.MulRange(n-k+1, n) 197 b.MulRange(1, k) 198 return z.Quo(&a, &b) 199 } 200 201 // Quo sets z to the quotient x/y for y != 0 and returns z. 202 // If y == 0, a division-by-zero run-time panic occurs. 203 // Quo implements truncated division (like Go); see QuoRem for more details. 204 func (z *Int) Quo(x, y *Int) *Int { 205 z.abs, _ = z.abs.div(nil, x.abs, y.abs) 206 z.neg = len(z.abs) > 0 && x.neg != y.neg // 0 has no sign 207 return z 208 } 209 210 // Rem sets z to the remainder x%y for y != 0 and returns z. 211 // If y == 0, a division-by-zero run-time panic occurs. 212 // Rem implements truncated modulus (like Go); see QuoRem for more details. 213 func (z *Int) Rem(x, y *Int) *Int { 214 _, z.abs = nat(nil).div(z.abs, x.abs, y.abs) 215 z.neg = len(z.abs) > 0 && x.neg // 0 has no sign 216 return z 217 } 218 219 // QuoRem sets z to the quotient x/y and r to the remainder x%y 220 // and returns the pair (z, r) for y != 0. 221 // If y == 0, a division-by-zero run-time panic occurs. 222 // 223 // QuoRem implements T-division and modulus (like Go): 224 // 225 // q = x/y with the result truncated to zero 226 // r = x - y*q 227 // 228 // (See Daan Leijen, ``Division and Modulus for Computer Scientists''.) 229 // See DivMod for Euclidean division and modulus (unlike Go). 230 // 231 func (z *Int) QuoRem(x, y, r *Int) (*Int, *Int) { 232 z.abs, r.abs = z.abs.div(r.abs, x.abs, y.abs) 233 z.neg, r.neg = len(z.abs) > 0 && x.neg != y.neg, len(r.abs) > 0 && x.neg // 0 has no sign 234 return z, r 235 } 236 237 // Div sets z to the quotient x/y for y != 0 and returns z. 238 // If y == 0, a division-by-zero run-time panic occurs. 239 // Div implements Euclidean division (unlike Go); see DivMod for more details. 240 func (z *Int) Div(x, y *Int) *Int { 241 y_neg := y.neg // z may be an alias for y 242 var r Int 243 z.QuoRem(x, y, &r) 244 if r.neg { 245 if y_neg { 246 z.Add(z, intOne) 247 } else { 248 z.Sub(z, intOne) 249 } 250 } 251 return z 252 } 253 254 // Mod sets z to the modulus x%y for y != 0 and returns z. 255 // If y == 0, a division-by-zero run-time panic occurs. 256 // Mod implements Euclidean modulus (unlike Go); see DivMod for more details. 257 func (z *Int) Mod(x, y *Int) *Int { 258 y0 := y // save y 259 if z == y || alias(z.abs, y.abs) { 260 y0 = new(Int).Set(y) 261 } 262 var q Int 263 q.QuoRem(x, y, z) 264 if z.neg { 265 if y0.neg { 266 z.Sub(z, y0) 267 } else { 268 z.Add(z, y0) 269 } 270 } 271 return z 272 } 273 274 // DivMod sets z to the quotient x div y and m to the modulus x mod y 275 // and returns the pair (z, m) for y != 0. 276 // If y == 0, a division-by-zero run-time panic occurs. 277 // 278 // DivMod implements Euclidean division and modulus (unlike Go): 279 // 280 // q = x div y such that 281 // m = x - y*q with 0 <= m < |y| 282 // 283 // (See Raymond T. Boute, ``The Euclidean definition of the functions 284 // div and mod''. ACM Transactions on Programming Languages and 285 // Systems (TOPLAS), 14(2):127-144, New York, NY, USA, 4/1992. 286 // ACM press.) 287 // See QuoRem for T-division and modulus (like Go). 288 // 289 func (z *Int) DivMod(x, y, m *Int) (*Int, *Int) { 290 y0 := y // save y 291 if z == y || alias(z.abs, y.abs) { 292 y0 = new(Int).Set(y) 293 } 294 z.QuoRem(x, y, m) 295 if m.neg { 296 if y0.neg { 297 z.Add(z, intOne) 298 m.Sub(m, y0) 299 } else { 300 z.Sub(z, intOne) 301 m.Add(m, y0) 302 } 303 } 304 return z, m 305 } 306 307 // Cmp compares x and y and returns: 308 // 309 // -1 if x < y 310 // 0 if x == y 311 // +1 if x > y 312 // 313 func (x *Int) Cmp(y *Int) (r int) { 314 // x cmp y == x cmp y 315 // x cmp (-y) == x 316 // (-x) cmp y == y 317 // (-x) cmp (-y) == -(x cmp y) 318 switch { 319 case x.neg == y.neg: 320 r = x.abs.cmp(y.abs) 321 if x.neg { 322 r = -r 323 } 324 case x.neg: 325 r = -1 326 default: 327 r = 1 328 } 329 return 330 } 331 332 // low32 returns the least significant 32 bits of x. 333 func low32(x nat) uint32 { 334 if len(x) == 0 { 335 return 0 336 } 337 return uint32(x[0]) 338 } 339 340 // low64 returns the least significant 64 bits of x. 341 func low64(x nat) uint64 { 342 if len(x) == 0 { 343 return 0 344 } 345 v := uint64(x[0]) 346 if _W == 32 && len(x) > 1 { 347 return uint64(x[1])<<32 | v 348 } 349 return v 350 } 351 352 // Int64 returns the int64 representation of x. 353 // If x cannot be represented in an int64, the result is undefined. 354 func (x *Int) Int64() int64 { 355 v := int64(low64(x.abs)) 356 if x.neg { 357 v = -v 358 } 359 return v 360 } 361 362 // Uint64 returns the uint64 representation of x. 363 // If x cannot be represented in a uint64, the result is undefined. 364 func (x *Int) Uint64() uint64 { 365 return low64(x.abs) 366 } 367 368 // IsInt64 reports whether x can be represented as an int64. 369 func (x *Int) IsInt64() bool { 370 if len(x.abs) <= 64/_W { 371 w := int64(low64(x.abs)) 372 return w >= 0 || x.neg && w == -w 373 } 374 return false 375 } 376 377 // IsUint64 reports whether x can be represented as a uint64. 378 func (x *Int) IsUint64() bool { 379 return !x.neg && len(x.abs) <= 64/_W 380 } 381 382 // SetString sets z to the value of s, interpreted in the given base, 383 // and returns z and a boolean indicating success. The entire string 384 // (not just a prefix) must be valid for success. If SetString fails, 385 // the value of z is undefined but the returned value is nil. 386 // 387 // The base argument must be 0 or a value between 2 and MaxBase. If the base 388 // is 0, the string prefix determines the actual conversion base. A prefix of 389 // ``0x'' or ``0X'' selects base 16; the ``0'' prefix selects base 8, and a 390 // ``0b'' or ``0B'' prefix selects base 2. Otherwise the selected base is 10. 391 // 392 // For bases <= 36, lower and upper case letters are considered the same: 393 // The letters 'a' to 'z' and 'A' to 'Z' represent digit values 10 to 35. 394 // For bases > 36, the upper case letters 'A' to 'Z' represent the digit 395 // values 36 to 61. 396 // 397 func (z *Int) SetString(s string, base int) (*Int, bool) { 398 return z.setFromScanner(strings.NewReader(s), base) 399 } 400 401 // setFromScanner implements SetString given an io.BytesScanner. 402 // For documentation see comments of SetString. 403 func (z *Int) setFromScanner(r io.ByteScanner, base int) (*Int, bool) { 404 if _, _, err := z.scan(r, base); err != nil { 405 return nil, false 406 } 407 // entire content must have been consumed 408 if _, err := r.ReadByte(); err != io.EOF { 409 return nil, false 410 } 411 return z, true // err == io.EOF => scan consumed all content of r 412 } 413 414 // SetBytes interprets buf as the bytes of a big-endian unsigned 415 // integer, sets z to that value, and returns z. 416 func (z *Int) SetBytes(buf []byte) *Int { 417 z.abs = z.abs.setBytes(buf) 418 z.neg = false 419 return z 420 } 421 422 // Bytes returns the absolute value of x as a big-endian byte slice. 423 func (x *Int) Bytes() []byte { 424 buf := make([]byte, len(x.abs)*_S) 425 return buf[x.abs.bytes(buf):] 426 } 427 428 // BitLen returns the length of the absolute value of x in bits. 429 // The bit length of 0 is 0. 430 func (x *Int) BitLen() int { 431 return x.abs.bitLen() 432 } 433 434 // Exp sets z = x**y mod |m| (i.e. the sign of m is ignored), and returns z. 435 // If y <= 0, the result is 1 mod |m|; if m == nil or m == 0, z = x**y. 436 // 437 // Modular exponentation of inputs of a particular size is not a 438 // cryptographically constant-time operation. 439 func (z *Int) Exp(x, y, m *Int) *Int { 440 // See Knuth, volume 2, section 4.6.3. 441 var yWords nat 442 if !y.neg { 443 yWords = y.abs 444 } 445 // y >= 0 446 447 var mWords nat 448 if m != nil { 449 mWords = m.abs // m.abs may be nil for m == 0 450 } 451 452 z.abs = z.abs.expNN(x.abs, yWords, mWords) 453 z.neg = len(z.abs) > 0 && x.neg && len(yWords) > 0 && yWords[0]&1 == 1 // 0 has no sign 454 if z.neg && len(mWords) > 0 { 455 // make modulus result positive 456 z.abs = z.abs.sub(mWords, z.abs) // z == x**y mod |m| && 0 <= z < |m| 457 z.neg = false 458 } 459 460 return z 461 } 462 463 // GCD sets z to the greatest common divisor of a and b, which both must 464 // be > 0, and returns z. 465 // If x or y are not nil, GCD sets their value such that z = a*x + b*y. 466 // If either a or b is <= 0, GCD sets z = x = y = 0. 467 func (z *Int) GCD(x, y, a, b *Int) *Int { 468 if a.Sign() <= 0 || b.Sign() <= 0 { 469 z.SetInt64(0) 470 if x != nil { 471 x.SetInt64(0) 472 } 473 if y != nil { 474 y.SetInt64(0) 475 } 476 return z 477 } 478 if x == nil && y == nil { 479 return z.binaryGCD(a, b) 480 } 481 482 A := new(Int).Set(a) 483 B := new(Int).Set(b) 484 485 X := new(Int) 486 lastX := new(Int).SetInt64(1) 487 488 q := new(Int) 489 temp := new(Int) 490 491 r := new(Int) 492 for len(B.abs) > 0 { 493 q, r = q.QuoRem(A, B, r) 494 495 A, B, r = B, r, A 496 497 temp.Set(X) 498 X.Mul(X, q) 499 X.Sub(lastX, X) 500 lastX.Set(temp) 501 } 502 503 if x != nil { 504 *x = *lastX 505 } 506 507 if y != nil { 508 // y = (z - a*x)/b 509 y.Mul(a, lastX) 510 y.Sub(A, y) 511 y.Div(y, b) 512 } 513 514 *z = *A 515 return z 516 } 517 518 // binaryGCD sets z to the greatest common divisor of a and b, which both must 519 // be > 0, and returns z. 520 // See Knuth, The Art of Computer Programming, Vol. 2, Section 4.5.2, Algorithm B. 521 func (z *Int) binaryGCD(a, b *Int) *Int { 522 u := z 523 v := new(Int) 524 525 // use one Euclidean iteration to ensure that u and v are approx. the same size 526 switch { 527 case len(a.abs) > len(b.abs): 528 // must set v before u since u may be alias for a or b (was issue #11284) 529 v.Rem(a, b) 530 u.Set(b) 531 case len(a.abs) < len(b.abs): 532 v.Rem(b, a) 533 u.Set(a) 534 default: 535 v.Set(b) 536 u.Set(a) 537 } 538 // a, b must not be used anymore (may be aliases with u) 539 540 // v might be 0 now 541 if len(v.abs) == 0 { 542 return u 543 } 544 // u > 0 && v > 0 545 546 // determine largest k such that u = u' << k, v = v' << k 547 k := u.abs.trailingZeroBits() 548 if vk := v.abs.trailingZeroBits(); vk < k { 549 k = vk 550 } 551 u.Rsh(u, k) 552 v.Rsh(v, k) 553 554 // determine t (we know that u > 0) 555 t := new(Int) 556 if u.abs[0]&1 != 0 { 557 // u is odd 558 t.Neg(v) 559 } else { 560 t.Set(u) 561 } 562 563 for len(t.abs) > 0 { 564 // reduce t 565 t.Rsh(t, t.abs.trailingZeroBits()) 566 if t.neg { 567 v, t = t, v 568 v.neg = len(v.abs) > 0 && !v.neg // 0 has no sign 569 } else { 570 u, t = t, u 571 } 572 t.Sub(u, v) 573 } 574 575 return z.Lsh(u, k) 576 } 577 578 // Rand sets z to a pseudo-random number in [0, n) and returns z. 579 func (z *Int) Rand(rnd *rand.Rand, n *Int) *Int { 580 z.neg = false 581 if n.neg || len(n.abs) == 0 { 582 z.abs = nil 583 return z 584 } 585 z.abs = z.abs.random(rnd, n.abs, n.abs.bitLen()) 586 return z 587 } 588 589 // ModInverse sets z to the multiplicative inverse of g in the ring ℤ/nℤ 590 // and returns z. If g and n are not relatively prime, the result is undefined. 591 func (z *Int) ModInverse(g, n *Int) *Int { 592 if g.neg { 593 // GCD expects parameters a and b to be > 0. 594 var g2 Int 595 g = g2.Mod(g, n) 596 } 597 var d Int 598 d.GCD(z, nil, g, n) 599 // x and y are such that g*x + n*y = d. Since g and n are 600 // relatively prime, d = 1. Taking that modulo n results in 601 // g*x = 1, therefore x is the inverse element. 602 if z.neg { 603 z.Add(z, n) 604 } 605 return z 606 } 607 608 // Jacobi returns the Jacobi symbol (x/y), either +1, -1, or 0. 609 // The y argument must be an odd integer. 610 func Jacobi(x, y *Int) int { 611 if len(y.abs) == 0 || y.abs[0]&1 == 0 { 612 panic(fmt.Sprintf("big: invalid 2nd argument to Int.Jacobi: need odd integer but got %s", y)) 613 } 614 615 // We use the formulation described in chapter 2, section 2.4, 616 // "The Yacas Book of Algorithms": 617 // http://yacas.sourceforge.net/Algo.book.pdf 618 619 var a, b, c Int 620 a.Set(x) 621 b.Set(y) 622 j := 1 623 624 if b.neg { 625 if a.neg { 626 j = -1 627 } 628 b.neg = false 629 } 630 631 for { 632 if b.Cmp(intOne) == 0 { 633 return j 634 } 635 if len(a.abs) == 0 { 636 return 0 637 } 638 a.Mod(&a, &b) 639 if len(a.abs) == 0 { 640 return 0 641 } 642 // a > 0 643 644 // handle factors of 2 in 'a' 645 s := a.abs.trailingZeroBits() 646 if s&1 != 0 { 647 bmod8 := b.abs[0] & 7 648 if bmod8 == 3 || bmod8 == 5 { 649 j = -j 650 } 651 } 652 c.Rsh(&a, s) // a = 2^s*c 653 654 // swap numerator and denominator 655 if b.abs[0]&3 == 3 && c.abs[0]&3 == 3 { 656 j = -j 657 } 658 a.Set(&b) 659 b.Set(&c) 660 } 661 } 662 663 // modSqrt3Mod4 uses the identity 664 // (a^((p+1)/4))^2 mod p 665 // == u^(p+1) mod p 666 // == u^2 mod p 667 // to calculate the square root of any quadratic residue mod p quickly for 3 668 // mod 4 primes. 669 func (z *Int) modSqrt3Mod4Prime(x, p *Int) *Int { 670 z.Set(p) // z = p 671 z.Add(z, intOne) // z = p + 1 672 z.Rsh(z, 2) // z = (p + 1) / 4 673 z.Exp(x, z, p) // z = x^z mod p 674 return z 675 } 676 677 // modSqrtTonelliShanks uses the Tonelli-Shanks algorithm to find the square 678 // root of a quadratic residue modulo any prime. 679 func (z *Int) modSqrtTonelliShanks(x, p *Int) *Int { 680 // Break p-1 into s*2^e such that s is odd. 681 var s Int 682 s.Sub(p, intOne) 683 e := s.abs.trailingZeroBits() 684 s.Rsh(&s, e) 685 686 // find some non-square n 687 var n Int 688 n.SetInt64(2) 689 for Jacobi(&n, p) != -1 { 690 n.Add(&n, intOne) 691 } 692 693 // Core of the Tonelli-Shanks algorithm. Follows the description in 694 // section 6 of "Square roots from 1; 24, 51, 10 to Dan Shanks" by Ezra 695 // Brown: 696 // https://www.maa.org/sites/default/files/pdf/upload_library/22/Polya/07468342.di020786.02p0470a.pdf 697 var y, b, g, t Int 698 y.Add(&s, intOne) 699 y.Rsh(&y, 1) 700 y.Exp(x, &y, p) // y = x^((s+1)/2) 701 b.Exp(x, &s, p) // b = x^s 702 g.Exp(&n, &s, p) // g = n^s 703 r := e 704 for { 705 // find the least m such that ord_p(b) = 2^m 706 var m uint 707 t.Set(&b) 708 for t.Cmp(intOne) != 0 { 709 t.Mul(&t, &t).Mod(&t, p) 710 m++ 711 } 712 713 if m == 0 { 714 return z.Set(&y) 715 } 716 717 t.SetInt64(0).SetBit(&t, int(r-m-1), 1).Exp(&g, &t, p) 718 // t = g^(2^(r-m-1)) mod p 719 g.Mul(&t, &t).Mod(&g, p) // g = g^(2^(r-m)) mod p 720 y.Mul(&y, &t).Mod(&y, p) 721 b.Mul(&b, &g).Mod(&b, p) 722 r = m 723 } 724 } 725 726 // ModSqrt sets z to a square root of x mod p if such a square root exists, and 727 // returns z. The modulus p must be an odd prime. If x is not a square mod p, 728 // ModSqrt leaves z unchanged and returns nil. This function panics if p is 729 // not an odd integer. 730 func (z *Int) ModSqrt(x, p *Int) *Int { 731 switch Jacobi(x, p) { 732 case -1: 733 return nil // x is not a square mod p 734 case 0: 735 return z.SetInt64(0) // sqrt(0) mod p = 0 736 case 1: 737 break 738 } 739 if x.neg || x.Cmp(p) >= 0 { // ensure 0 <= x < p 740 x = new(Int).Mod(x, p) 741 } 742 743 // Check whether p is 3 mod 4, and if so, use the faster algorithm. 744 if len(p.abs) > 0 && p.abs[0]%4 == 3 { 745 return z.modSqrt3Mod4Prime(x, p) 746 } 747 // Otherwise, use Tonelli-Shanks. 748 return z.modSqrtTonelliShanks(x, p) 749 } 750 751 // Lsh sets z = x << n and returns z. 752 func (z *Int) Lsh(x *Int, n uint) *Int { 753 z.abs = z.abs.shl(x.abs, n) 754 z.neg = x.neg 755 return z 756 } 757 758 // Rsh sets z = x >> n and returns z. 759 func (z *Int) Rsh(x *Int, n uint) *Int { 760 if x.neg { 761 // (-x) >> s == ^(x-1) >> s == ^((x-1) >> s) == -(((x-1) >> s) + 1) 762 t := z.abs.sub(x.abs, natOne) // no underflow because |x| > 0 763 t = t.shr(t, n) 764 z.abs = t.add(t, natOne) 765 z.neg = true // z cannot be zero if x is negative 766 return z 767 } 768 769 z.abs = z.abs.shr(x.abs, n) 770 z.neg = false 771 return z 772 } 773 774 // Bit returns the value of the i'th bit of x. That is, it 775 // returns (x>>i)&1. The bit index i must be >= 0. 776 func (x *Int) Bit(i int) uint { 777 if i == 0 { 778 // optimization for common case: odd/even test of x 779 if len(x.abs) > 0 { 780 return uint(x.abs[0] & 1) // bit 0 is same for -x 781 } 782 return 0 783 } 784 if i < 0 { 785 panic("negative bit index") 786 } 787 if x.neg { 788 t := nat(nil).sub(x.abs, natOne) 789 return t.bit(uint(i)) ^ 1 790 } 791 792 return x.abs.bit(uint(i)) 793 } 794 795 // SetBit sets z to x, with x's i'th bit set to b (0 or 1). 796 // That is, if b is 1 SetBit sets z = x | (1 << i); 797 // if b is 0 SetBit sets z = x &^ (1 << i). If b is not 0 or 1, 798 // SetBit will panic. 799 func (z *Int) SetBit(x *Int, i int, b uint) *Int { 800 if i < 0 { 801 panic("negative bit index") 802 } 803 if x.neg { 804 t := z.abs.sub(x.abs, natOne) 805 t = t.setBit(t, uint(i), b^1) 806 z.abs = t.add(t, natOne) 807 z.neg = len(z.abs) > 0 808 return z 809 } 810 z.abs = z.abs.setBit(x.abs, uint(i), b) 811 z.neg = false 812 return z 813 } 814 815 // And sets z = x & y and returns z. 816 func (z *Int) And(x, y *Int) *Int { 817 if x.neg == y.neg { 818 if x.neg { 819 // (-x) & (-y) == ^(x-1) & ^(y-1) == ^((x-1) | (y-1)) == -(((x-1) | (y-1)) + 1) 820 x1 := nat(nil).sub(x.abs, natOne) 821 y1 := nat(nil).sub(y.abs, natOne) 822 z.abs = z.abs.add(z.abs.or(x1, y1), natOne) 823 z.neg = true // z cannot be zero if x and y are negative 824 return z 825 } 826 827 // x & y == x & y 828 z.abs = z.abs.and(x.abs, y.abs) 829 z.neg = false 830 return z 831 } 832 833 // x.neg != y.neg 834 if x.neg { 835 x, y = y, x // & is symmetric 836 } 837 838 // x & (-y) == x & ^(y-1) == x &^ (y-1) 839 y1 := nat(nil).sub(y.abs, natOne) 840 z.abs = z.abs.andNot(x.abs, y1) 841 z.neg = false 842 return z 843 } 844 845 // AndNot sets z = x &^ y and returns z. 846 func (z *Int) AndNot(x, y *Int) *Int { 847 if x.neg == y.neg { 848 if x.neg { 849 // (-x) &^ (-y) == ^(x-1) &^ ^(y-1) == ^(x-1) & (y-1) == (y-1) &^ (x-1) 850 x1 := nat(nil).sub(x.abs, natOne) 851 y1 := nat(nil).sub(y.abs, natOne) 852 z.abs = z.abs.andNot(y1, x1) 853 z.neg = false 854 return z 855 } 856 857 // x &^ y == x &^ y 858 z.abs = z.abs.andNot(x.abs, y.abs) 859 z.neg = false 860 return z 861 } 862 863 if x.neg { 864 // (-x) &^ y == ^(x-1) &^ y == ^(x-1) & ^y == ^((x-1) | y) == -(((x-1) | y) + 1) 865 x1 := nat(nil).sub(x.abs, natOne) 866 z.abs = z.abs.add(z.abs.or(x1, y.abs), natOne) 867 z.neg = true // z cannot be zero if x is negative and y is positive 868 return z 869 } 870 871 // x &^ (-y) == x &^ ^(y-1) == x & (y-1) 872 y1 := nat(nil).sub(y.abs, natOne) 873 z.abs = z.abs.and(x.abs, y1) 874 z.neg = false 875 return z 876 } 877 878 // Or sets z = x | y and returns z. 879 func (z *Int) Or(x, y *Int) *Int { 880 if x.neg == y.neg { 881 if x.neg { 882 // (-x) | (-y) == ^(x-1) | ^(y-1) == ^((x-1) & (y-1)) == -(((x-1) & (y-1)) + 1) 883 x1 := nat(nil).sub(x.abs, natOne) 884 y1 := nat(nil).sub(y.abs, natOne) 885 z.abs = z.abs.add(z.abs.and(x1, y1), natOne) 886 z.neg = true // z cannot be zero if x and y are negative 887 return z 888 } 889 890 // x | y == x | y 891 z.abs = z.abs.or(x.abs, y.abs) 892 z.neg = false 893 return z 894 } 895 896 // x.neg != y.neg 897 if x.neg { 898 x, y = y, x // | is symmetric 899 } 900 901 // x | (-y) == x | ^(y-1) == ^((y-1) &^ x) == -(^((y-1) &^ x) + 1) 902 y1 := nat(nil).sub(y.abs, natOne) 903 z.abs = z.abs.add(z.abs.andNot(y1, x.abs), natOne) 904 z.neg = true // z cannot be zero if one of x or y is negative 905 return z 906 } 907 908 // Xor sets z = x ^ y and returns z. 909 func (z *Int) Xor(x, y *Int) *Int { 910 if x.neg == y.neg { 911 if x.neg { 912 // (-x) ^ (-y) == ^(x-1) ^ ^(y-1) == (x-1) ^ (y-1) 913 x1 := nat(nil).sub(x.abs, natOne) 914 y1 := nat(nil).sub(y.abs, natOne) 915 z.abs = z.abs.xor(x1, y1) 916 z.neg = false 917 return z 918 } 919 920 // x ^ y == x ^ y 921 z.abs = z.abs.xor(x.abs, y.abs) 922 z.neg = false 923 return z 924 } 925 926 // x.neg != y.neg 927 if x.neg { 928 x, y = y, x // ^ is symmetric 929 } 930 931 // x ^ (-y) == x ^ ^(y-1) == ^(x ^ (y-1)) == -((x ^ (y-1)) + 1) 932 y1 := nat(nil).sub(y.abs, natOne) 933 z.abs = z.abs.add(z.abs.xor(x.abs, y1), natOne) 934 z.neg = true // z cannot be zero if only one of x or y is negative 935 return z 936 } 937 938 // Not sets z = ^x and returns z. 939 func (z *Int) Not(x *Int) *Int { 940 if x.neg { 941 // ^(-x) == ^(^(x-1)) == x-1 942 z.abs = z.abs.sub(x.abs, natOne) 943 z.neg = false 944 return z 945 } 946 947 // ^x == -x-1 == -(x+1) 948 z.abs = z.abs.add(x.abs, natOne) 949 z.neg = true // z cannot be zero if x is positive 950 return z 951 } 952 953 // Sqrt sets z to ⌊√x⌋, the largest integer such that z² ≤ x, and returns z. 954 // It panics if x is negative. 955 func (z *Int) Sqrt(x *Int) *Int { 956 if x.neg { 957 panic("square root of negative number") 958 } 959 z.neg = false 960 z.abs = z.abs.sqrt(x.abs) 961 return z 962 }