int.go 24 KB

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