PageRenderTime 28ms CodeModel.GetById 21ms RepoModel.GetById 1ms app.codeStats 0ms

/third_party/gofrontend/libgo/go/math/big/int.go

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