github.com/mtsmfm/go/src@v0.0.0-20221020090648-44bdcb9f8fde/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 // 19 // Operations always take pointer arguments (*Int) rather 20 // than Int values, and each unique Int value requires 21 // its own unique *Int pointer. To "copy" an Int value, 22 // an existing (or newly allocated) Int must be set to 23 // a new value using the Int.Set method; shallow copies 24 // of Ints are not supported and may lead to errors. 25 type Int struct { 26 neg bool // sign 27 abs nat // absolute value of the integer 28 } 29 30 var intOne = &Int{false, natOne} 31 32 // Sign returns: 33 // 34 // -1 if x < 0 35 // 0 if x == 0 36 // +1 if x > 0 37 func (x *Int) Sign() int { 38 if len(x.abs) == 0 { 39 return 0 40 } 41 if x.neg { 42 return -1 43 } 44 return 1 45 } 46 47 // SetInt64 sets z to x and returns z. 48 func (z *Int) SetInt64(x int64) *Int { 49 neg := false 50 if x < 0 { 51 neg = true 52 x = -x 53 } 54 z.abs = z.abs.setUint64(uint64(x)) 55 z.neg = neg 56 return z 57 } 58 59 // SetUint64 sets z to x and returns z. 60 func (z *Int) SetUint64(x uint64) *Int { 61 z.abs = z.abs.setUint64(x) 62 z.neg = false 63 return z 64 } 65 66 // NewInt allocates and returns a new Int set to x. 67 func NewInt(x int64) *Int { 68 // This code is arranged to be inlineable and produce 69 // zero allocations when inlined. See issue 29951. 70 u := uint64(x) 71 if x < 0 { 72 u = -u 73 } 74 var abs []Word 75 if x == 0 { 76 } else if _W == 32 && u>>32 != 0 { 77 abs = []Word{Word(u), Word(u >> 32)} 78 } else { 79 abs = []Word{Word(u)} 80 } 81 return &Int{neg: x < 0, abs: abs} 82 } 83 84 // Set sets z to x and returns z. 85 func (z *Int) Set(x *Int) *Int { 86 if z != x { 87 z.abs = z.abs.set(x.abs) 88 z.neg = x.neg 89 } 90 return z 91 } 92 93 // Bits provides raw (unchecked but fast) access to x by returning its 94 // absolute value as a little-endian Word slice. The result and x share 95 // the same underlying array. 96 // Bits is intended to support implementation of missing low-level Int 97 // functionality outside this package; it should be avoided otherwise. 98 func (x *Int) Bits() []Word { 99 return x.abs 100 } 101 102 // SetBits provides raw (unchecked but fast) access to z by setting its 103 // value to abs, interpreted as a little-endian Word slice, and returning 104 // z. The result and abs share the same underlying array. 105 // SetBits is intended to support implementation of missing low-level Int 106 // functionality outside this package; it should be avoided otherwise. 107 func (z *Int) SetBits(abs []Word) *Int { 108 z.abs = nat(abs).norm() 109 z.neg = false 110 return z 111 } 112 113 // Abs sets z to |x| (the absolute value of x) and returns z. 114 func (z *Int) Abs(x *Int) *Int { 115 z.Set(x) 116 z.neg = false 117 return z 118 } 119 120 // Neg sets z to -x and returns z. 121 func (z *Int) Neg(x *Int) *Int { 122 z.Set(x) 123 z.neg = len(z.abs) > 0 && !z.neg // 0 has no sign 124 return z 125 } 126 127 // Add sets z to the sum x+y and returns z. 128 func (z *Int) Add(x, y *Int) *Int { 129 neg := x.neg 130 if x.neg == y.neg { 131 // x + y == x + y 132 // (-x) + (-y) == -(x + y) 133 z.abs = z.abs.add(x.abs, y.abs) 134 } else { 135 // x + (-y) == x - y == -(y - x) 136 // (-x) + y == y - x == -(x - y) 137 if x.abs.cmp(y.abs) >= 0 { 138 z.abs = z.abs.sub(x.abs, y.abs) 139 } else { 140 neg = !neg 141 z.abs = z.abs.sub(y.abs, x.abs) 142 } 143 } 144 z.neg = len(z.abs) > 0 && neg // 0 has no sign 145 return z 146 } 147 148 // Sub sets z to the difference x-y and returns z. 149 func (z *Int) Sub(x, y *Int) *Int { 150 neg := x.neg 151 if x.neg != y.neg { 152 // x - (-y) == x + y 153 // (-x) - y == -(x + y) 154 z.abs = z.abs.add(x.abs, y.abs) 155 } else { 156 // x - y == x - y == -(y - x) 157 // (-x) - (-y) == y - x == -(x - y) 158 if x.abs.cmp(y.abs) >= 0 { 159 z.abs = z.abs.sub(x.abs, y.abs) 160 } else { 161 neg = !neg 162 z.abs = z.abs.sub(y.abs, x.abs) 163 } 164 } 165 z.neg = len(z.abs) > 0 && neg // 0 has no sign 166 return z 167 } 168 169 // Mul sets z to the product x*y and returns z. 170 func (z *Int) Mul(x, y *Int) *Int { 171 // x * y == x * y 172 // x * (-y) == -(x * y) 173 // (-x) * y == -(x * y) 174 // (-x) * (-y) == x * y 175 if x == y { 176 z.abs = z.abs.sqr(x.abs) 177 z.neg = false 178 return z 179 } 180 z.abs = z.abs.mul(x.abs, y.abs) 181 z.neg = len(z.abs) > 0 && x.neg != y.neg // 0 has no sign 182 return z 183 } 184 185 // MulRange sets z to the product of all integers 186 // in the range [a, b] inclusively and returns z. 187 // If a > b (empty range), the result is 1. 188 func (z *Int) MulRange(a, b int64) *Int { 189 switch { 190 case a > b: 191 return z.SetInt64(1) // empty range 192 case a <= 0 && b >= 0: 193 return z.SetInt64(0) // range includes 0 194 } 195 // a <= b && (b < 0 || a > 0) 196 197 neg := false 198 if a < 0 { 199 neg = (b-a)&1 == 0 200 a, b = -b, -a 201 } 202 203 z.abs = z.abs.mulRange(uint64(a), uint64(b)) 204 z.neg = neg 205 return z 206 } 207 208 // Binomial sets z to the binomial coefficient of (n, k) and returns z. 209 func (z *Int) Binomial(n, k int64) *Int { 210 // reduce the number of multiplications by reducing k 211 if n/2 < k && k <= n { 212 k = n - k // Binomial(n, k) == Binomial(n, n-k) 213 } 214 var a, b Int 215 a.MulRange(n-k+1, n) 216 b.MulRange(1, k) 217 return z.Quo(&a, &b) 218 } 219 220 // Quo sets z to the quotient x/y for y != 0 and returns z. 221 // If y == 0, a division-by-zero run-time panic occurs. 222 // Quo implements truncated division (like Go); see QuoRem for more details. 223 func (z *Int) Quo(x, y *Int) *Int { 224 z.abs, _ = z.abs.div(nil, x.abs, y.abs) 225 z.neg = len(z.abs) > 0 && x.neg != y.neg // 0 has no sign 226 return z 227 } 228 229 // Rem sets z to the remainder x%y for y != 0 and returns z. 230 // If y == 0, a division-by-zero run-time panic occurs. 231 // Rem implements truncated modulus (like Go); see QuoRem for more details. 232 func (z *Int) Rem(x, y *Int) *Int { 233 _, z.abs = nat(nil).div(z.abs, x.abs, y.abs) 234 z.neg = len(z.abs) > 0 && x.neg // 0 has no sign 235 return z 236 } 237 238 // QuoRem sets z to the quotient x/y and r to the remainder x%y 239 // and returns the pair (z, r) for y != 0. 240 // If y == 0, a division-by-zero run-time panic occurs. 241 // 242 // QuoRem implements T-division and modulus (like Go): 243 // 244 // q = x/y with the result truncated to zero 245 // r = x - y*q 246 // 247 // (See Daan Leijen, “Division and Modulus for Computer Scientists”.) 248 // See DivMod for Euclidean division and modulus (unlike Go). 249 func (z *Int) QuoRem(x, y, r *Int) (*Int, *Int) { 250 z.abs, r.abs = z.abs.div(r.abs, x.abs, y.abs) 251 z.neg, r.neg = len(z.abs) > 0 && x.neg != y.neg, len(r.abs) > 0 && x.neg // 0 has no sign 252 return z, r 253 } 254 255 // Div sets z to the quotient x/y for y != 0 and returns z. 256 // If y == 0, a division-by-zero run-time panic occurs. 257 // Div implements Euclidean division (unlike Go); see DivMod for more details. 258 func (z *Int) Div(x, y *Int) *Int { 259 y_neg := y.neg // z may be an alias for y 260 var r Int 261 z.QuoRem(x, y, &r) 262 if r.neg { 263 if y_neg { 264 z.Add(z, intOne) 265 } else { 266 z.Sub(z, intOne) 267 } 268 } 269 return z 270 } 271 272 // Mod sets z to the modulus x%y for y != 0 and returns z. 273 // If y == 0, a division-by-zero run-time panic occurs. 274 // Mod implements Euclidean modulus (unlike Go); see DivMod for more details. 275 func (z *Int) Mod(x, y *Int) *Int { 276 y0 := y // save y 277 if z == y || alias(z.abs, y.abs) { 278 y0 = new(Int).Set(y) 279 } 280 var q Int 281 q.QuoRem(x, y, z) 282 if z.neg { 283 if y0.neg { 284 z.Sub(z, y0) 285 } else { 286 z.Add(z, y0) 287 } 288 } 289 return z 290 } 291 292 // DivMod sets z to the quotient x div y and m to the modulus x mod y 293 // and returns the pair (z, m) for y != 0. 294 // If y == 0, a division-by-zero run-time panic occurs. 295 // 296 // DivMod implements Euclidean division and modulus (unlike Go): 297 // 298 // q = x div y such that 299 // m = x - y*q with 0 <= m < |y| 300 // 301 // (See Raymond T. Boute, “The Euclidean definition of the functions 302 // div and mod”. ACM Transactions on Programming Languages and 303 // Systems (TOPLAS), 14(2):127-144, New York, NY, USA, 4/1992. 304 // ACM press.) 305 // See QuoRem for T-division and modulus (like Go). 306 func (z *Int) DivMod(x, y, m *Int) (*Int, *Int) { 307 y0 := y // save y 308 if z == y || alias(z.abs, y.abs) { 309 y0 = new(Int).Set(y) 310 } 311 z.QuoRem(x, y, m) 312 if m.neg { 313 if y0.neg { 314 z.Add(z, intOne) 315 m.Sub(m, y0) 316 } else { 317 z.Sub(z, intOne) 318 m.Add(m, y0) 319 } 320 } 321 return z, m 322 } 323 324 // Cmp compares x and y and returns: 325 // 326 // -1 if x < y 327 // 0 if x == y 328 // +1 if x > y 329 func (x *Int) Cmp(y *Int) (r int) { 330 // x cmp y == x cmp y 331 // x cmp (-y) == x 332 // (-x) cmp y == y 333 // (-x) cmp (-y) == -(x cmp y) 334 switch { 335 case x == y: 336 // nothing to do 337 case x.neg == y.neg: 338 r = x.abs.cmp(y.abs) 339 if x.neg { 340 r = -r 341 } 342 case x.neg: 343 r = -1 344 default: 345 r = 1 346 } 347 return 348 } 349 350 // CmpAbs compares the absolute values of x and y and returns: 351 // 352 // -1 if |x| < |y| 353 // 0 if |x| == |y| 354 // +1 if |x| > |y| 355 func (x *Int) CmpAbs(y *Int) int { 356 return x.abs.cmp(y.abs) 357 } 358 359 // low32 returns the least significant 32 bits of x. 360 func low32(x nat) uint32 { 361 if len(x) == 0 { 362 return 0 363 } 364 return uint32(x[0]) 365 } 366 367 // low64 returns the least significant 64 bits of x. 368 func low64(x nat) uint64 { 369 if len(x) == 0 { 370 return 0 371 } 372 v := uint64(x[0]) 373 if _W == 32 && len(x) > 1 { 374 return uint64(x[1])<<32 | v 375 } 376 return v 377 } 378 379 // Int64 returns the int64 representation of x. 380 // If x cannot be represented in an int64, the result is undefined. 381 func (x *Int) Int64() int64 { 382 v := int64(low64(x.abs)) 383 if x.neg { 384 v = -v 385 } 386 return v 387 } 388 389 // Uint64 returns the uint64 representation of x. 390 // If x cannot be represented in a uint64, the result is undefined. 391 func (x *Int) Uint64() uint64 { 392 return low64(x.abs) 393 } 394 395 // IsInt64 reports whether x can be represented as an int64. 396 func (x *Int) IsInt64() bool { 397 if len(x.abs) <= 64/_W { 398 w := int64(low64(x.abs)) 399 return w >= 0 || x.neg && w == -w 400 } 401 return false 402 } 403 404 // IsUint64 reports whether x can be represented as a uint64. 405 func (x *Int) IsUint64() bool { 406 return !x.neg && len(x.abs) <= 64/_W 407 } 408 409 // SetString sets z to the value of s, interpreted in the given base, 410 // and returns z and a boolean indicating success. The entire string 411 // (not just a prefix) must be valid for success. If SetString fails, 412 // the value of z is undefined but the returned value is nil. 413 // 414 // The base argument must be 0 or a value between 2 and MaxBase. 415 // For base 0, the number prefix determines the actual base: A prefix of 416 // “0b” or “0B” selects base 2, “0”, “0o” or “0O” selects base 8, 417 // and “0x” or “0X” selects base 16. Otherwise, the selected base is 10 418 // and no prefix is accepted. 419 // 420 // For bases <= 36, lower and upper case letters are considered the same: 421 // The letters 'a' to 'z' and 'A' to 'Z' represent digit values 10 to 35. 422 // For bases > 36, the upper case letters 'A' to 'Z' represent the digit 423 // values 36 to 61. 424 // 425 // For base 0, an underscore character “_” may appear between a base 426 // prefix and an adjacent digit, and between successive digits; such 427 // underscores do not change the value of the number. 428 // Incorrect placement of underscores is reported as an error if there 429 // are no other errors. If base != 0, underscores are not recognized 430 // and act like any other character that is not a valid digit. 431 func (z *Int) SetString(s string, base int) (*Int, bool) { 432 return z.setFromScanner(strings.NewReader(s), base) 433 } 434 435 // setFromScanner implements SetString given an io.ByteScanner. 436 // For documentation see comments of SetString. 437 func (z *Int) setFromScanner(r io.ByteScanner, base int) (*Int, bool) { 438 if _, _, err := z.scan(r, base); err != nil { 439 return nil, false 440 } 441 // entire content must have been consumed 442 if _, err := r.ReadByte(); err != io.EOF { 443 return nil, false 444 } 445 return z, true // err == io.EOF => scan consumed all content of r 446 } 447 448 // SetBytes interprets buf as the bytes of a big-endian unsigned 449 // integer, sets z to that value, and returns z. 450 func (z *Int) SetBytes(buf []byte) *Int { 451 z.abs = z.abs.setBytes(buf) 452 z.neg = false 453 return z 454 } 455 456 // Bytes returns the absolute value of x as a big-endian byte slice. 457 // 458 // To use a fixed length slice, or a preallocated one, use FillBytes. 459 func (x *Int) Bytes() []byte { 460 buf := make([]byte, len(x.abs)*_S) 461 return buf[x.abs.bytes(buf):] 462 } 463 464 // FillBytes sets buf to the absolute value of x, storing it as a zero-extended 465 // big-endian byte slice, and returns buf. 466 // 467 // If the absolute value of x doesn't fit in buf, FillBytes will panic. 468 func (x *Int) FillBytes(buf []byte) []byte { 469 // Clear whole buffer. (This gets optimized into a memclr.) 470 for i := range buf { 471 buf[i] = 0 472 } 473 x.abs.bytes(buf) 474 return buf 475 } 476 477 // BitLen returns the length of the absolute value of x in bits. 478 // The bit length of 0 is 0. 479 func (x *Int) BitLen() int { 480 return x.abs.bitLen() 481 } 482 483 // TrailingZeroBits returns the number of consecutive least significant zero 484 // bits of |x|. 485 func (x *Int) TrailingZeroBits() uint { 486 return x.abs.trailingZeroBits() 487 } 488 489 // Exp sets z = x**y mod |m| (i.e. the sign of m is ignored), and returns z. 490 // If m == nil or m == 0, z = x**y unless y <= 0 then z = 1. If m != 0, y < 0, 491 // and x and m are not relatively prime, z is unchanged and nil is returned. 492 // 493 // Modular exponentiation of inputs of a particular size is not a 494 // cryptographically constant-time operation. 495 func (z *Int) Exp(x, y, m *Int) *Int { 496 // See Knuth, volume 2, section 4.6.3. 497 xWords := x.abs 498 if y.neg { 499 if m == nil || len(m.abs) == 0 { 500 return z.SetInt64(1) 501 } 502 // for y < 0: x**y mod m == (x**(-1))**|y| mod m 503 inverse := new(Int).ModInverse(x, m) 504 if inverse == nil { 505 return nil 506 } 507 xWords = inverse.abs 508 } 509 yWords := y.abs 510 511 var mWords nat 512 if m != nil { 513 if z == m || alias(z.abs, m.abs) { 514 m = new(Int).Set(m) 515 } 516 mWords = m.abs // m.abs may be nil for m == 0 517 } 518 519 z.abs = z.abs.expNN(xWords, yWords, mWords) 520 z.neg = len(z.abs) > 0 && x.neg && len(yWords) > 0 && yWords[0]&1 == 1 // 0 has no sign 521 if z.neg && len(mWords) > 0 { 522 // make modulus result positive 523 z.abs = z.abs.sub(mWords, z.abs) // z == x**y mod |m| && 0 <= z < |m| 524 z.neg = false 525 } 526 527 return z 528 } 529 530 // GCD sets z to the greatest common divisor of a and b and returns z. 531 // If x or y are not nil, GCD sets their value such that z = a*x + b*y. 532 // 533 // a and b may be positive, zero or negative. (Before Go 1.14 both had 534 // to be > 0.) Regardless of the signs of a and b, z is always >= 0. 535 // 536 // If a == b == 0, GCD sets z = x = y = 0. 537 // 538 // If a == 0 and b != 0, GCD sets z = |b|, x = 0, y = sign(b) * 1. 539 // 540 // If a != 0 and b == 0, GCD sets z = |a|, x = sign(a) * 1, y = 0. 541 func (z *Int) GCD(x, y, a, b *Int) *Int { 542 if len(a.abs) == 0 || len(b.abs) == 0 { 543 lenA, lenB, negA, negB := len(a.abs), len(b.abs), a.neg, b.neg 544 if lenA == 0 { 545 z.Set(b) 546 } else { 547 z.Set(a) 548 } 549 z.neg = false 550 if x != nil { 551 if lenA == 0 { 552 x.SetUint64(0) 553 } else { 554 x.SetUint64(1) 555 x.neg = negA 556 } 557 } 558 if y != nil { 559 if lenB == 0 { 560 y.SetUint64(0) 561 } else { 562 y.SetUint64(1) 563 y.neg = negB 564 } 565 } 566 return z 567 } 568 569 return z.lehmerGCD(x, y, a, b) 570 } 571 572 // lehmerSimulate attempts to simulate several Euclidean update steps 573 // using the leading digits of A and B. It returns u0, u1, v0, v1 574 // such that A and B can be updated as: 575 // 576 // A = u0*A + v0*B 577 // B = u1*A + v1*B 578 // 579 // Requirements: A >= B and len(B.abs) >= 2 580 // Since we are calculating with full words to avoid overflow, 581 // we use 'even' to track the sign of the cosequences. 582 // For even iterations: u0, v1 >= 0 && u1, v0 <= 0 583 // For odd iterations: u0, v1 <= 0 && u1, v0 >= 0 584 func lehmerSimulate(A, B *Int) (u0, u1, v0, v1 Word, even bool) { 585 // initialize the digits 586 var a1, a2, u2, v2 Word 587 588 m := len(B.abs) // m >= 2 589 n := len(A.abs) // n >= m >= 2 590 591 // extract the top Word of bits from A and B 592 h := nlz(A.abs[n-1]) 593 a1 = A.abs[n-1]<<h | A.abs[n-2]>>(_W-h) 594 // B may have implicit zero words in the high bits if the lengths differ 595 switch { 596 case n == m: 597 a2 = B.abs[n-1]<<h | B.abs[n-2]>>(_W-h) 598 case n == m+1: 599 a2 = B.abs[n-2] >> (_W - h) 600 default: 601 a2 = 0 602 } 603 604 // Since we are calculating with full words to avoid overflow, 605 // we use 'even' to track the sign of the cosequences. 606 // For even iterations: u0, v1 >= 0 && u1, v0 <= 0 607 // For odd iterations: u0, v1 <= 0 && u1, v0 >= 0 608 // The first iteration starts with k=1 (odd). 609 even = false 610 // variables to track the cosequences 611 u0, u1, u2 = 0, 1, 0 612 v0, v1, v2 = 0, 0, 1 613 614 // Calculate the quotient and cosequences using Collins' stopping condition. 615 // Note that overflow of a Word is not possible when computing the remainder 616 // sequence and cosequences since the cosequence size is bounded by the input size. 617 // See section 4.2 of Jebelean for details. 618 for a2 >= v2 && a1-a2 >= v1+v2 { 619 q, r := a1/a2, a1%a2 620 a1, a2 = a2, r 621 u0, u1, u2 = u1, u2, u1+q*u2 622 v0, v1, v2 = v1, v2, v1+q*v2 623 even = !even 624 } 625 return 626 } 627 628 // lehmerUpdate updates the inputs A and B such that: 629 // 630 // A = u0*A + v0*B 631 // B = u1*A + v1*B 632 // 633 // where the signs of u0, u1, v0, v1 are given by even 634 // For even == true: u0, v1 >= 0 && u1, v0 <= 0 635 // For even == false: u0, v1 <= 0 && u1, v0 >= 0 636 // q, r, s, t are temporary variables to avoid allocations in the multiplication 637 func lehmerUpdate(A, B, q, r, s, t *Int, u0, u1, v0, v1 Word, even bool) { 638 639 t.abs = t.abs.setWord(u0) 640 s.abs = s.abs.setWord(v0) 641 t.neg = !even 642 s.neg = even 643 644 t.Mul(A, t) 645 s.Mul(B, s) 646 647 r.abs = r.abs.setWord(u1) 648 q.abs = q.abs.setWord(v1) 649 r.neg = even 650 q.neg = !even 651 652 r.Mul(A, r) 653 q.Mul(B, q) 654 655 A.Add(t, s) 656 B.Add(r, q) 657 } 658 659 // euclidUpdate performs a single step of the Euclidean GCD algorithm 660 // if extended is true, it also updates the cosequence Ua, Ub 661 func euclidUpdate(A, B, Ua, Ub, q, r, s, t *Int, extended bool) { 662 q, r = q.QuoRem(A, B, r) 663 664 *A, *B, *r = *B, *r, *A 665 666 if extended { 667 // Ua, Ub = Ub, Ua - q*Ub 668 t.Set(Ub) 669 s.Mul(Ub, q) 670 Ub.Sub(Ua, s) 671 Ua.Set(t) 672 } 673 } 674 675 // lehmerGCD sets z to the greatest common divisor of a and b, 676 // which both must be != 0, and returns z. 677 // If x or y are not nil, their values are set such that z = a*x + b*y. 678 // See Knuth, The Art of Computer Programming, Vol. 2, Section 4.5.2, Algorithm L. 679 // This implementation uses the improved condition by Collins requiring only one 680 // quotient and avoiding the possibility of single Word overflow. 681 // See Jebelean, "Improving the multiprecision Euclidean algorithm", 682 // Design and Implementation of Symbolic Computation Systems, pp 45-58. 683 // The cosequences are updated according to Algorithm 10.45 from 684 // Cohen et al. "Handbook of Elliptic and Hyperelliptic Curve Cryptography" pp 192. 685 func (z *Int) lehmerGCD(x, y, a, b *Int) *Int { 686 var A, B, Ua, Ub *Int 687 688 A = new(Int).Abs(a) 689 B = new(Int).Abs(b) 690 691 extended := x != nil || y != nil 692 693 if extended { 694 // Ua (Ub) tracks how many times input a has been accumulated into A (B). 695 Ua = new(Int).SetInt64(1) 696 Ub = new(Int) 697 } 698 699 // temp variables for multiprecision update 700 q := new(Int) 701 r := new(Int) 702 s := new(Int) 703 t := new(Int) 704 705 // ensure A >= B 706 if A.abs.cmp(B.abs) < 0 { 707 A, B = B, A 708 Ub, Ua = Ua, Ub 709 } 710 711 // loop invariant A >= B 712 for len(B.abs) > 1 { 713 // Attempt to calculate in single-precision using leading words of A and B. 714 u0, u1, v0, v1, even := lehmerSimulate(A, B) 715 716 // multiprecision Step 717 if v0 != 0 { 718 // Simulate the effect of the single-precision steps using the cosequences. 719 // A = u0*A + v0*B 720 // B = u1*A + v1*B 721 lehmerUpdate(A, B, q, r, s, t, u0, u1, v0, v1, even) 722 723 if extended { 724 // Ua = u0*Ua + v0*Ub 725 // Ub = u1*Ua + v1*Ub 726 lehmerUpdate(Ua, Ub, q, r, s, t, u0, u1, v0, v1, even) 727 } 728 729 } else { 730 // Single-digit calculations failed to simulate any quotients. 731 // Do a standard Euclidean step. 732 euclidUpdate(A, B, Ua, Ub, q, r, s, t, extended) 733 } 734 } 735 736 if len(B.abs) > 0 { 737 // extended Euclidean algorithm base case if B is a single Word 738 if len(A.abs) > 1 { 739 // A is longer than a single Word, so one update is needed. 740 euclidUpdate(A, B, Ua, Ub, q, r, s, t, extended) 741 } 742 if len(B.abs) > 0 { 743 // A and B are both a single Word. 744 aWord, bWord := A.abs[0], B.abs[0] 745 if extended { 746 var ua, ub, va, vb Word 747 ua, ub = 1, 0 748 va, vb = 0, 1 749 even := true 750 for bWord != 0 { 751 q, r := aWord/bWord, aWord%bWord 752 aWord, bWord = bWord, r 753 ua, ub = ub, ua+q*ub 754 va, vb = vb, va+q*vb 755 even = !even 756 } 757 758 t.abs = t.abs.setWord(ua) 759 s.abs = s.abs.setWord(va) 760 t.neg = !even 761 s.neg = even 762 763 t.Mul(Ua, t) 764 s.Mul(Ub, s) 765 766 Ua.Add(t, s) 767 } else { 768 for bWord != 0 { 769 aWord, bWord = bWord, aWord%bWord 770 } 771 } 772 A.abs[0] = aWord 773 } 774 } 775 negA := a.neg 776 if y != nil { 777 // avoid aliasing b needed in the division below 778 if y == b { 779 B.Set(b) 780 } else { 781 B = b 782 } 783 // y = (z - a*x)/b 784 y.Mul(a, Ua) // y can safely alias a 785 if negA { 786 y.neg = !y.neg 787 } 788 y.Sub(A, y) 789 y.Div(y, B) 790 } 791 792 if x != nil { 793 *x = *Ua 794 if negA { 795 x.neg = !x.neg 796 } 797 } 798 799 *z = *A 800 801 return z 802 } 803 804 // Rand sets z to a pseudo-random number in [0, n) and returns z. 805 // 806 // As this uses the math/rand package, it must not be used for 807 // security-sensitive work. Use crypto/rand.Int instead. 808 func (z *Int) Rand(rnd *rand.Rand, n *Int) *Int { 809 // z.neg is not modified before the if check, because z and n might alias. 810 if n.neg || len(n.abs) == 0 { 811 z.neg = false 812 z.abs = nil 813 return z 814 } 815 z.neg = false 816 z.abs = z.abs.random(rnd, n.abs, n.abs.bitLen()) 817 return z 818 } 819 820 // ModInverse sets z to the multiplicative inverse of g in the ring ℤ/nℤ 821 // and returns z. If g and n are not relatively prime, g has no multiplicative 822 // inverse in the ring ℤ/nℤ. In this case, z is unchanged and the return value 823 // is nil. If n == 0, a division-by-zero run-time panic occurs. 824 func (z *Int) ModInverse(g, n *Int) *Int { 825 // GCD expects parameters a and b to be > 0. 826 if n.neg { 827 var n2 Int 828 n = n2.Neg(n) 829 } 830 if g.neg { 831 var g2 Int 832 g = g2.Mod(g, n) 833 } 834 var d, x Int 835 d.GCD(&x, nil, g, n) 836 837 // if and only if d==1, g and n are relatively prime 838 if d.Cmp(intOne) != 0 { 839 return nil 840 } 841 842 // x and y are such that g*x + n*y = 1, therefore x is the inverse element, 843 // but it may be negative, so convert to the range 0 <= z < |n| 844 if x.neg { 845 z.Add(&x, n) 846 } else { 847 z.Set(&x) 848 } 849 return z 850 } 851 852 // Jacobi returns the Jacobi symbol (x/y), either +1, -1, or 0. 853 // The y argument must be an odd integer. 854 func Jacobi(x, y *Int) int { 855 if len(y.abs) == 0 || y.abs[0]&1 == 0 { 856 panic(fmt.Sprintf("big: invalid 2nd argument to Int.Jacobi: need odd integer but got %s", y.String())) 857 } 858 859 // We use the formulation described in chapter 2, section 2.4, 860 // "The Yacas Book of Algorithms": 861 // http://yacas.sourceforge.net/Algo.book.pdf 862 863 var a, b, c Int 864 a.Set(x) 865 b.Set(y) 866 j := 1 867 868 if b.neg { 869 if a.neg { 870 j = -1 871 } 872 b.neg = false 873 } 874 875 for { 876 if b.Cmp(intOne) == 0 { 877 return j 878 } 879 if len(a.abs) == 0 { 880 return 0 881 } 882 a.Mod(&a, &b) 883 if len(a.abs) == 0 { 884 return 0 885 } 886 // a > 0 887 888 // handle factors of 2 in 'a' 889 s := a.abs.trailingZeroBits() 890 if s&1 != 0 { 891 bmod8 := b.abs[0] & 7 892 if bmod8 == 3 || bmod8 == 5 { 893 j = -j 894 } 895 } 896 c.Rsh(&a, s) // a = 2^s*c 897 898 // swap numerator and denominator 899 if b.abs[0]&3 == 3 && c.abs[0]&3 == 3 { 900 j = -j 901 } 902 a.Set(&b) 903 b.Set(&c) 904 } 905 } 906 907 // modSqrt3Mod4 uses the identity 908 // 909 // (a^((p+1)/4))^2 mod p 910 // == u^(p+1) mod p 911 // == u^2 mod p 912 // 913 // to calculate the square root of any quadratic residue mod p quickly for 3 914 // mod 4 primes. 915 func (z *Int) modSqrt3Mod4Prime(x, p *Int) *Int { 916 e := new(Int).Add(p, intOne) // e = p + 1 917 e.Rsh(e, 2) // e = (p + 1) / 4 918 z.Exp(x, e, p) // z = x^e mod p 919 return z 920 } 921 922 // modSqrt5Mod8 uses Atkin's observation that 2 is not a square mod p 923 // 924 // alpha == (2*a)^((p-5)/8) mod p 925 // beta == 2*a*alpha^2 mod p is a square root of -1 926 // b == a*alpha*(beta-1) mod p is a square root of a 927 // 928 // to calculate the square root of any quadratic residue mod p quickly for 5 929 // mod 8 primes. 930 func (z *Int) modSqrt5Mod8Prime(x, p *Int) *Int { 931 // p == 5 mod 8 implies p = e*8 + 5 932 // e is the quotient and 5 the remainder on division by 8 933 e := new(Int).Rsh(p, 3) // e = (p - 5) / 8 934 tx := new(Int).Lsh(x, 1) // tx = 2*x 935 alpha := new(Int).Exp(tx, e, p) 936 beta := new(Int).Mul(alpha, alpha) 937 beta.Mod(beta, p) 938 beta.Mul(beta, tx) 939 beta.Mod(beta, p) 940 beta.Sub(beta, intOne) 941 beta.Mul(beta, x) 942 beta.Mod(beta, p) 943 beta.Mul(beta, alpha) 944 z.Mod(beta, p) 945 return z 946 } 947 948 // modSqrtTonelliShanks uses the Tonelli-Shanks algorithm to find the square 949 // root of a quadratic residue modulo any prime. 950 func (z *Int) modSqrtTonelliShanks(x, p *Int) *Int { 951 // Break p-1 into s*2^e such that s is odd. 952 var s Int 953 s.Sub(p, intOne) 954 e := s.abs.trailingZeroBits() 955 s.Rsh(&s, e) 956 957 // find some non-square n 958 var n Int 959 n.SetInt64(2) 960 for Jacobi(&n, p) != -1 { 961 n.Add(&n, intOne) 962 } 963 964 // Core of the Tonelli-Shanks algorithm. Follows the description in 965 // section 6 of "Square roots from 1; 24, 51, 10 to Dan Shanks" by Ezra 966 // Brown: 967 // https://www.maa.org/sites/default/files/pdf/upload_library/22/Polya/07468342.di020786.02p0470a.pdf 968 var y, b, g, t Int 969 y.Add(&s, intOne) 970 y.Rsh(&y, 1) 971 y.Exp(x, &y, p) // y = x^((s+1)/2) 972 b.Exp(x, &s, p) // b = x^s 973 g.Exp(&n, &s, p) // g = n^s 974 r := e 975 for { 976 // find the least m such that ord_p(b) = 2^m 977 var m uint 978 t.Set(&b) 979 for t.Cmp(intOne) != 0 { 980 t.Mul(&t, &t).Mod(&t, p) 981 m++ 982 } 983 984 if m == 0 { 985 return z.Set(&y) 986 } 987 988 t.SetInt64(0).SetBit(&t, int(r-m-1), 1).Exp(&g, &t, p) 989 // t = g^(2^(r-m-1)) mod p 990 g.Mul(&t, &t).Mod(&g, p) // g = g^(2^(r-m)) mod p 991 y.Mul(&y, &t).Mod(&y, p) 992 b.Mul(&b, &g).Mod(&b, p) 993 r = m 994 } 995 } 996 997 // ModSqrt sets z to a square root of x mod p if such a square root exists, and 998 // returns z. The modulus p must be an odd prime. If x is not a square mod p, 999 // ModSqrt leaves z unchanged and returns nil. This function panics if p is 1000 // not an odd integer, its behavior is undefined if p is odd but not prime. 1001 func (z *Int) ModSqrt(x, p *Int) *Int { 1002 switch Jacobi(x, p) { 1003 case -1: 1004 return nil // x is not a square mod p 1005 case 0: 1006 return z.SetInt64(0) // sqrt(0) mod p = 0 1007 case 1: 1008 break 1009 } 1010 if x.neg || x.Cmp(p) >= 0 { // ensure 0 <= x < p 1011 x = new(Int).Mod(x, p) 1012 } 1013 1014 switch { 1015 case p.abs[0]%4 == 3: 1016 // Check whether p is 3 mod 4, and if so, use the faster algorithm. 1017 return z.modSqrt3Mod4Prime(x, p) 1018 case p.abs[0]%8 == 5: 1019 // Check whether p is 5 mod 8, use Atkin's algorithm. 1020 return z.modSqrt5Mod8Prime(x, p) 1021 default: 1022 // Otherwise, use Tonelli-Shanks. 1023 return z.modSqrtTonelliShanks(x, p) 1024 } 1025 } 1026 1027 // Lsh sets z = x << n and returns z. 1028 func (z *Int) Lsh(x *Int, n uint) *Int { 1029 z.abs = z.abs.shl(x.abs, n) 1030 z.neg = x.neg 1031 return z 1032 } 1033 1034 // Rsh sets z = x >> n and returns z. 1035 func (z *Int) Rsh(x *Int, n uint) *Int { 1036 if x.neg { 1037 // (-x) >> s == ^(x-1) >> s == ^((x-1) >> s) == -(((x-1) >> s) + 1) 1038 t := z.abs.sub(x.abs, natOne) // no underflow because |x| > 0 1039 t = t.shr(t, n) 1040 z.abs = t.add(t, natOne) 1041 z.neg = true // z cannot be zero if x is negative 1042 return z 1043 } 1044 1045 z.abs = z.abs.shr(x.abs, n) 1046 z.neg = false 1047 return z 1048 } 1049 1050 // Bit returns the value of the i'th bit of x. That is, it 1051 // returns (x>>i)&1. The bit index i must be >= 0. 1052 func (x *Int) Bit(i int) uint { 1053 if i == 0 { 1054 // optimization for common case: odd/even test of x 1055 if len(x.abs) > 0 { 1056 return uint(x.abs[0] & 1) // bit 0 is same for -x 1057 } 1058 return 0 1059 } 1060 if i < 0 { 1061 panic("negative bit index") 1062 } 1063 if x.neg { 1064 t := nat(nil).sub(x.abs, natOne) 1065 return t.bit(uint(i)) ^ 1 1066 } 1067 1068 return x.abs.bit(uint(i)) 1069 } 1070 1071 // SetBit sets z to x, with x's i'th bit set to b (0 or 1). 1072 // That is, if b is 1 SetBit sets z = x | (1 << i); 1073 // if b is 0 SetBit sets z = x &^ (1 << i). If b is not 0 or 1, 1074 // SetBit will panic. 1075 func (z *Int) SetBit(x *Int, i int, b uint) *Int { 1076 if i < 0 { 1077 panic("negative bit index") 1078 } 1079 if x.neg { 1080 t := z.abs.sub(x.abs, natOne) 1081 t = t.setBit(t, uint(i), b^1) 1082 z.abs = t.add(t, natOne) 1083 z.neg = len(z.abs) > 0 1084 return z 1085 } 1086 z.abs = z.abs.setBit(x.abs, uint(i), b) 1087 z.neg = false 1088 return z 1089 } 1090 1091 // And sets z = x & y and returns z. 1092 func (z *Int) And(x, y *Int) *Int { 1093 if x.neg == y.neg { 1094 if x.neg { 1095 // (-x) & (-y) == ^(x-1) & ^(y-1) == ^((x-1) | (y-1)) == -(((x-1) | (y-1)) + 1) 1096 x1 := nat(nil).sub(x.abs, natOne) 1097 y1 := nat(nil).sub(y.abs, natOne) 1098 z.abs = z.abs.add(z.abs.or(x1, y1), natOne) 1099 z.neg = true // z cannot be zero if x and y are negative 1100 return z 1101 } 1102 1103 // x & y == x & y 1104 z.abs = z.abs.and(x.abs, y.abs) 1105 z.neg = false 1106 return z 1107 } 1108 1109 // x.neg != y.neg 1110 if x.neg { 1111 x, y = y, x // & is symmetric 1112 } 1113 1114 // x & (-y) == x & ^(y-1) == x &^ (y-1) 1115 y1 := nat(nil).sub(y.abs, natOne) 1116 z.abs = z.abs.andNot(x.abs, y1) 1117 z.neg = false 1118 return z 1119 } 1120 1121 // AndNot sets z = x &^ y and returns z. 1122 func (z *Int) AndNot(x, y *Int) *Int { 1123 if x.neg == y.neg { 1124 if x.neg { 1125 // (-x) &^ (-y) == ^(x-1) &^ ^(y-1) == ^(x-1) & (y-1) == (y-1) &^ (x-1) 1126 x1 := nat(nil).sub(x.abs, natOne) 1127 y1 := nat(nil).sub(y.abs, natOne) 1128 z.abs = z.abs.andNot(y1, x1) 1129 z.neg = false 1130 return z 1131 } 1132 1133 // x &^ y == x &^ y 1134 z.abs = z.abs.andNot(x.abs, y.abs) 1135 z.neg = false 1136 return z 1137 } 1138 1139 if x.neg { 1140 // (-x) &^ y == ^(x-1) &^ y == ^(x-1) & ^y == ^((x-1) | y) == -(((x-1) | y) + 1) 1141 x1 := nat(nil).sub(x.abs, natOne) 1142 z.abs = z.abs.add(z.abs.or(x1, y.abs), natOne) 1143 z.neg = true // z cannot be zero if x is negative and y is positive 1144 return z 1145 } 1146 1147 // x &^ (-y) == x &^ ^(y-1) == x & (y-1) 1148 y1 := nat(nil).sub(y.abs, natOne) 1149 z.abs = z.abs.and(x.abs, y1) 1150 z.neg = false 1151 return z 1152 } 1153 1154 // Or sets z = x | y and returns z. 1155 func (z *Int) Or(x, y *Int) *Int { 1156 if x.neg == y.neg { 1157 if x.neg { 1158 // (-x) | (-y) == ^(x-1) | ^(y-1) == ^((x-1) & (y-1)) == -(((x-1) & (y-1)) + 1) 1159 x1 := nat(nil).sub(x.abs, natOne) 1160 y1 := nat(nil).sub(y.abs, natOne) 1161 z.abs = z.abs.add(z.abs.and(x1, y1), natOne) 1162 z.neg = true // z cannot be zero if x and y are negative 1163 return z 1164 } 1165 1166 // x | y == x | y 1167 z.abs = z.abs.or(x.abs, y.abs) 1168 z.neg = false 1169 return z 1170 } 1171 1172 // x.neg != y.neg 1173 if x.neg { 1174 x, y = y, x // | is symmetric 1175 } 1176 1177 // x | (-y) == x | ^(y-1) == ^((y-1) &^ x) == -(^((y-1) &^ x) + 1) 1178 y1 := nat(nil).sub(y.abs, natOne) 1179 z.abs = z.abs.add(z.abs.andNot(y1, x.abs), natOne) 1180 z.neg = true // z cannot be zero if one of x or y is negative 1181 return z 1182 } 1183 1184 // Xor sets z = x ^ y and returns z. 1185 func (z *Int) Xor(x, y *Int) *Int { 1186 if x.neg == y.neg { 1187 if x.neg { 1188 // (-x) ^ (-y) == ^(x-1) ^ ^(y-1) == (x-1) ^ (y-1) 1189 x1 := nat(nil).sub(x.abs, natOne) 1190 y1 := nat(nil).sub(y.abs, natOne) 1191 z.abs = z.abs.xor(x1, y1) 1192 z.neg = false 1193 return z 1194 } 1195 1196 // x ^ y == x ^ y 1197 z.abs = z.abs.xor(x.abs, y.abs) 1198 z.neg = false 1199 return z 1200 } 1201 1202 // x.neg != y.neg 1203 if x.neg { 1204 x, y = y, x // ^ is symmetric 1205 } 1206 1207 // x ^ (-y) == x ^ ^(y-1) == ^(x ^ (y-1)) == -((x ^ (y-1)) + 1) 1208 y1 := nat(nil).sub(y.abs, natOne) 1209 z.abs = z.abs.add(z.abs.xor(x.abs, y1), natOne) 1210 z.neg = true // z cannot be zero if only one of x or y is negative 1211 return z 1212 } 1213 1214 // Not sets z = ^x and returns z. 1215 func (z *Int) Not(x *Int) *Int { 1216 if x.neg { 1217 // ^(-x) == ^(^(x-1)) == x-1 1218 z.abs = z.abs.sub(x.abs, natOne) 1219 z.neg = false 1220 return z 1221 } 1222 1223 // ^x == -x-1 == -(x+1) 1224 z.abs = z.abs.add(x.abs, natOne) 1225 z.neg = true // z cannot be zero if x is positive 1226 return z 1227 } 1228 1229 // Sqrt sets z to ⌊√x⌋, the largest integer such that z² ≤ x, and returns z. 1230 // It panics if x is negative. 1231 func (z *Int) Sqrt(x *Int) *Int { 1232 if x.neg { 1233 panic("square root of negative number") 1234 } 1235 z.neg = false 1236 z.abs = z.abs.sqrt(x.abs) 1237 return z 1238 }