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