PageRenderTime 59ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 0ms

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

http://github.com/axw/llgo
Go | 1274 lines | 847 code | 168 blank | 259 comment | 258 complexity | 0d30be98f72a851dea4d7886e77f528b 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. // Package big implements multi-precision arithmetic (big numbers).
  5. // The following numeric types are supported:
  6. //
  7. // Int signed integers
  8. // Rat rational numbers
  9. // Float floating-point numbers
  10. //
  11. // Methods are typically of the form:
  12. //
  13. // func (z *T) Unary(x *T) *T // z = op x
  14. // func (z *T) Binary(x, y *T) *T // z = x op y
  15. // func (x *T) M() T1 // v = x.M()
  16. //
  17. // with T one of Int, Rat, or Float. For unary and binary operations, the
  18. // result is the receiver (usually named z in that case); if it is one of
  19. // the operands x or y it may be overwritten (and its memory reused).
  20. // To enable chaining of operations, the result is also returned. Methods
  21. // returning a result other than *Int, *Rat, or *Float take an operand as
  22. // the receiver (usually named x in that case).
  23. //
  24. package big
  25. // This file contains operations on unsigned multi-precision integers.
  26. // These are the building blocks for the operations on signed integers
  27. // and rationals.
  28. import "math/rand"
  29. // An unsigned integer x of the form
  30. //
  31. // x = x[n-1]*_B^(n-1) + x[n-2]*_B^(n-2) + ... + x[1]*_B + x[0]
  32. //
  33. // with 0 <= x[i] < _B and 0 <= i < n is stored in a slice of length n,
  34. // with the digits x[i] as the slice elements.
  35. //
  36. // A number is normalized if the slice contains no leading 0 digits.
  37. // During arithmetic operations, denormalized values may occur but are
  38. // always normalized before returning the final result. The normalized
  39. // representation of 0 is the empty or nil slice (length = 0).
  40. //
  41. type nat []Word
  42. var (
  43. natOne = nat{1}
  44. natTwo = nat{2}
  45. natTen = nat{10}
  46. )
  47. func (z nat) clear() {
  48. for i := range z {
  49. z[i] = 0
  50. }
  51. }
  52. func (z nat) norm() nat {
  53. i := len(z)
  54. for i > 0 && z[i-1] == 0 {
  55. i--
  56. }
  57. return z[0:i]
  58. }
  59. func (z nat) make(n int) nat {
  60. if n <= cap(z) {
  61. return z[:n] // reuse z
  62. }
  63. // Choosing a good value for e has significant performance impact
  64. // because it increases the chance that a value can be reused.
  65. const e = 4 // extra capacity
  66. return make(nat, n, n+e)
  67. }
  68. func (z nat) setWord(x Word) nat {
  69. if x == 0 {
  70. return z[:0]
  71. }
  72. z = z.make(1)
  73. z[0] = x
  74. return z
  75. }
  76. func (z nat) setUint64(x uint64) nat {
  77. // single-digit values
  78. if w := Word(x); uint64(w) == x {
  79. return z.setWord(w)
  80. }
  81. // compute number of words n required to represent x
  82. n := 0
  83. for t := x; t > 0; t >>= _W {
  84. n++
  85. }
  86. // split x into n words
  87. z = z.make(n)
  88. for i := range z {
  89. z[i] = Word(x & _M)
  90. x >>= _W
  91. }
  92. return z
  93. }
  94. func (z nat) set(x nat) nat {
  95. z = z.make(len(x))
  96. copy(z, x)
  97. return z
  98. }
  99. func (z nat) add(x, y nat) nat {
  100. m := len(x)
  101. n := len(y)
  102. switch {
  103. case m < n:
  104. return z.add(y, x)
  105. case m == 0:
  106. // n == 0 because m >= n; result is 0
  107. return z[:0]
  108. case n == 0:
  109. // result is x
  110. return z.set(x)
  111. }
  112. // m > 0
  113. z = z.make(m + 1)
  114. c := addVV(z[0:n], x, y)
  115. if m > n {
  116. c = addVW(z[n:m], x[n:], c)
  117. }
  118. z[m] = c
  119. return z.norm()
  120. }
  121. func (z nat) sub(x, y nat) nat {
  122. m := len(x)
  123. n := len(y)
  124. switch {
  125. case m < n:
  126. panic("underflow")
  127. case m == 0:
  128. // n == 0 because m >= n; result is 0
  129. return z[:0]
  130. case n == 0:
  131. // result is x
  132. return z.set(x)
  133. }
  134. // m > 0
  135. z = z.make(m)
  136. c := subVV(z[0:n], x, y)
  137. if m > n {
  138. c = subVW(z[n:], x[n:], c)
  139. }
  140. if c != 0 {
  141. panic("underflow")
  142. }
  143. return z.norm()
  144. }
  145. func (x nat) cmp(y nat) (r int) {
  146. m := len(x)
  147. n := len(y)
  148. if m != n || m == 0 {
  149. switch {
  150. case m < n:
  151. r = -1
  152. case m > n:
  153. r = 1
  154. }
  155. return
  156. }
  157. i := m - 1
  158. for i > 0 && x[i] == y[i] {
  159. i--
  160. }
  161. switch {
  162. case x[i] < y[i]:
  163. r = -1
  164. case x[i] > y[i]:
  165. r = 1
  166. }
  167. return
  168. }
  169. func (z nat) mulAddWW(x nat, y, r Word) nat {
  170. m := len(x)
  171. if m == 0 || y == 0 {
  172. return z.setWord(r) // result is r
  173. }
  174. // m > 0
  175. z = z.make(m + 1)
  176. z[m] = mulAddVWW(z[0:m], x, y, r)
  177. return z.norm()
  178. }
  179. // basicMul multiplies x and y and leaves the result in z.
  180. // The (non-normalized) result is placed in z[0 : len(x) + len(y)].
  181. func basicMul(z, x, y nat) {
  182. z[0 : len(x)+len(y)].clear() // initialize z
  183. for i, d := range y {
  184. if d != 0 {
  185. z[len(x)+i] = addMulVVW(z[i:i+len(x)], x, d)
  186. }
  187. }
  188. }
  189. // montgomery computes x*y*2^(-n*_W) mod m,
  190. // assuming k = -1/m mod 2^_W.
  191. // z is used for storing the result which is returned;
  192. // z must not alias x, y or m.
  193. func (z nat) montgomery(x, y, m nat, k Word, n int) nat {
  194. var c1, c2 Word
  195. z = z.make(n)
  196. z.clear()
  197. for i := 0; i < n; i++ {
  198. d := y[i]
  199. c1 += addMulVVW(z, x, d)
  200. t := z[0] * k
  201. c2 = addMulVVW(z, m, t)
  202. copy(z, z[1:])
  203. z[n-1] = c1 + c2
  204. if z[n-1] < c1 {
  205. c1 = 1
  206. } else {
  207. c1 = 0
  208. }
  209. }
  210. if c1 != 0 {
  211. subVV(z, z, m)
  212. }
  213. return z
  214. }
  215. // Fast version of z[0:n+n>>1].add(z[0:n+n>>1], x[0:n]) w/o bounds checks.
  216. // Factored out for readability - do not use outside karatsuba.
  217. func karatsubaAdd(z, x nat, n int) {
  218. if c := addVV(z[0:n], z, x); c != 0 {
  219. addVW(z[n:n+n>>1], z[n:], c)
  220. }
  221. }
  222. // Like karatsubaAdd, but does subtract.
  223. func karatsubaSub(z, x nat, n int) {
  224. if c := subVV(z[0:n], z, x); c != 0 {
  225. subVW(z[n:n+n>>1], z[n:], c)
  226. }
  227. }
  228. // Operands that are shorter than karatsubaThreshold are multiplied using
  229. // "grade school" multiplication; for longer operands the Karatsuba algorithm
  230. // is used.
  231. var karatsubaThreshold int = 40 // computed by calibrate.go
  232. // karatsuba multiplies x and y and leaves the result in z.
  233. // Both x and y must have the same length n and n must be a
  234. // power of 2. The result vector z must have len(z) >= 6*n.
  235. // The (non-normalized) result is placed in z[0 : 2*n].
  236. func karatsuba(z, x, y nat) {
  237. n := len(y)
  238. // Switch to basic multiplication if numbers are odd or small.
  239. // (n is always even if karatsubaThreshold is even, but be
  240. // conservative)
  241. if n&1 != 0 || n < karatsubaThreshold || n < 2 {
  242. basicMul(z, x, y)
  243. return
  244. }
  245. // n&1 == 0 && n >= karatsubaThreshold && n >= 2
  246. // Karatsuba multiplication is based on the observation that
  247. // for two numbers x and y with:
  248. //
  249. // x = x1*b + x0
  250. // y = y1*b + y0
  251. //
  252. // the product x*y can be obtained with 3 products z2, z1, z0
  253. // instead of 4:
  254. //
  255. // x*y = x1*y1*b*b + (x1*y0 + x0*y1)*b + x0*y0
  256. // = z2*b*b + z1*b + z0
  257. //
  258. // with:
  259. //
  260. // xd = x1 - x0
  261. // yd = y0 - y1
  262. //
  263. // z1 = xd*yd + z2 + z0
  264. // = (x1-x0)*(y0 - y1) + z2 + z0
  265. // = x1*y0 - x1*y1 - x0*y0 + x0*y1 + z2 + z0
  266. // = x1*y0 - z2 - z0 + x0*y1 + z2 + z0
  267. // = x1*y0 + x0*y1
  268. // split x, y into "digits"
  269. n2 := n >> 1 // n2 >= 1
  270. x1, x0 := x[n2:], x[0:n2] // x = x1*b + y0
  271. y1, y0 := y[n2:], y[0:n2] // y = y1*b + y0
  272. // z is used for the result and temporary storage:
  273. //
  274. // 6*n 5*n 4*n 3*n 2*n 1*n 0*n
  275. // z = [z2 copy|z0 copy| xd*yd | yd:xd | x1*y1 | x0*y0 ]
  276. //
  277. // For each recursive call of karatsuba, an unused slice of
  278. // z is passed in that has (at least) half the length of the
  279. // caller's z.
  280. // compute z0 and z2 with the result "in place" in z
  281. karatsuba(z, x0, y0) // z0 = x0*y0
  282. karatsuba(z[n:], x1, y1) // z2 = x1*y1
  283. // compute xd (or the negative value if underflow occurs)
  284. s := 1 // sign of product xd*yd
  285. xd := z[2*n : 2*n+n2]
  286. if subVV(xd, x1, x0) != 0 { // x1-x0
  287. s = -s
  288. subVV(xd, x0, x1) // x0-x1
  289. }
  290. // compute yd (or the negative value if underflow occurs)
  291. yd := z[2*n+n2 : 3*n]
  292. if subVV(yd, y0, y1) != 0 { // y0-y1
  293. s = -s
  294. subVV(yd, y1, y0) // y1-y0
  295. }
  296. // p = (x1-x0)*(y0-y1) == x1*y0 - x1*y1 - x0*y0 + x0*y1 for s > 0
  297. // p = (x0-x1)*(y0-y1) == x0*y0 - x0*y1 - x1*y0 + x1*y1 for s < 0
  298. p := z[n*3:]
  299. karatsuba(p, xd, yd)
  300. // save original z2:z0
  301. // (ok to use upper half of z since we're done recursing)
  302. r := z[n*4:]
  303. copy(r, z[:n*2])
  304. // add up all partial products
  305. //
  306. // 2*n n 0
  307. // z = [ z2 | z0 ]
  308. // + [ z0 ]
  309. // + [ z2 ]
  310. // + [ p ]
  311. //
  312. karatsubaAdd(z[n2:], r, n)
  313. karatsubaAdd(z[n2:], r[n:], n)
  314. if s > 0 {
  315. karatsubaAdd(z[n2:], p, n)
  316. } else {
  317. karatsubaSub(z[n2:], p, n)
  318. }
  319. }
  320. // alias reports whether x and y share the same base array.
  321. func alias(x, y nat) bool {
  322. return cap(x) > 0 && cap(y) > 0 && &x[0:cap(x)][cap(x)-1] == &y[0:cap(y)][cap(y)-1]
  323. }
  324. // addAt implements z += x<<(_W*i); z must be long enough.
  325. // (we don't use nat.add because we need z to stay the same
  326. // slice, and we don't need to normalize z after each addition)
  327. func addAt(z, x nat, i int) {
  328. if n := len(x); n > 0 {
  329. if c := addVV(z[i:i+n], z[i:], x); c != 0 {
  330. j := i + n
  331. if j < len(z) {
  332. addVW(z[j:], z[j:], c)
  333. }
  334. }
  335. }
  336. }
  337. func max(x, y int) int {
  338. if x > y {
  339. return x
  340. }
  341. return y
  342. }
  343. // karatsubaLen computes an approximation to the maximum k <= n such that
  344. // k = p<<i for a number p <= karatsubaThreshold and an i >= 0. Thus, the
  345. // result is the largest number that can be divided repeatedly by 2 before
  346. // becoming about the value of karatsubaThreshold.
  347. func karatsubaLen(n int) int {
  348. i := uint(0)
  349. for n > karatsubaThreshold {
  350. n >>= 1
  351. i++
  352. }
  353. return n << i
  354. }
  355. func (z nat) mul(x, y nat) nat {
  356. m := len(x)
  357. n := len(y)
  358. switch {
  359. case m < n:
  360. return z.mul(y, x)
  361. case m == 0 || n == 0:
  362. return z[:0]
  363. case n == 1:
  364. return z.mulAddWW(x, y[0], 0)
  365. }
  366. // m >= n > 1
  367. // determine if z can be reused
  368. if alias(z, x) || alias(z, y) {
  369. z = nil // z is an alias for x or y - cannot reuse
  370. }
  371. // use basic multiplication if the numbers are small
  372. if n < karatsubaThreshold {
  373. z = z.make(m + n)
  374. basicMul(z, x, y)
  375. return z.norm()
  376. }
  377. // m >= n && n >= karatsubaThreshold && n >= 2
  378. // determine Karatsuba length k such that
  379. //
  380. // x = xh*b + x0 (0 <= x0 < b)
  381. // y = yh*b + y0 (0 <= y0 < b)
  382. // b = 1<<(_W*k) ("base" of digits xi, yi)
  383. //
  384. k := karatsubaLen(n)
  385. // k <= n
  386. // multiply x0 and y0 via Karatsuba
  387. x0 := x[0:k] // x0 is not normalized
  388. y0 := y[0:k] // y0 is not normalized
  389. z = z.make(max(6*k, m+n)) // enough space for karatsuba of x0*y0 and full result of x*y
  390. karatsuba(z, x0, y0)
  391. z = z[0 : m+n] // z has final length but may be incomplete
  392. z[2*k:].clear() // upper portion of z is garbage (and 2*k <= m+n since k <= n <= m)
  393. // If xh != 0 or yh != 0, add the missing terms to z. For
  394. //
  395. // xh = xi*b^i + ... + x2*b^2 + x1*b (0 <= xi < b)
  396. // yh = y1*b (0 <= y1 < b)
  397. //
  398. // the missing terms are
  399. //
  400. // x0*y1*b and xi*y0*b^i, xi*y1*b^(i+1) for i > 0
  401. //
  402. // since all the yi for i > 1 are 0 by choice of k: If any of them
  403. // were > 0, then yh >= b^2 and thus y >= b^2. Then k' = k*2 would
  404. // be a larger valid threshold contradicting the assumption about k.
  405. //
  406. if k < n || m != n {
  407. var t nat
  408. // add x0*y1*b
  409. x0 := x0.norm()
  410. y1 := y[k:] // y1 is normalized because y is
  411. t = t.mul(x0, y1) // update t so we don't lose t's underlying array
  412. addAt(z, t, k)
  413. // add xi*y0<<i, xi*y1*b<<(i+k)
  414. y0 := y0.norm()
  415. for i := k; i < len(x); i += k {
  416. xi := x[i:]
  417. if len(xi) > k {
  418. xi = xi[:k]
  419. }
  420. xi = xi.norm()
  421. t = t.mul(xi, y0)
  422. addAt(z, t, i)
  423. t = t.mul(xi, y1)
  424. addAt(z, t, i+k)
  425. }
  426. }
  427. return z.norm()
  428. }
  429. // mulRange computes the product of all the unsigned integers in the
  430. // range [a, b] inclusively. If a > b (empty range), the result is 1.
  431. func (z nat) mulRange(a, b uint64) nat {
  432. switch {
  433. case a == 0:
  434. // cut long ranges short (optimization)
  435. return z.setUint64(0)
  436. case a > b:
  437. return z.setUint64(1)
  438. case a == b:
  439. return z.setUint64(a)
  440. case a+1 == b:
  441. return z.mul(nat(nil).setUint64(a), nat(nil).setUint64(b))
  442. }
  443. m := (a + b) / 2
  444. return z.mul(nat(nil).mulRange(a, m), nat(nil).mulRange(m+1, b))
  445. }
  446. // q = (x-r)/y, with 0 <= r < y
  447. func (z nat) divW(x nat, y Word) (q nat, r Word) {
  448. m := len(x)
  449. switch {
  450. case y == 0:
  451. panic("division by zero")
  452. case y == 1:
  453. q = z.set(x) // result is x
  454. return
  455. case m == 0:
  456. q = z[:0] // result is 0
  457. return
  458. }
  459. // m > 0
  460. z = z.make(m)
  461. r = divWVW(z, 0, x, y)
  462. q = z.norm()
  463. return
  464. }
  465. func (z nat) div(z2, u, v nat) (q, r nat) {
  466. if len(v) == 0 {
  467. panic("division by zero")
  468. }
  469. if u.cmp(v) < 0 {
  470. q = z[:0]
  471. r = z2.set(u)
  472. return
  473. }
  474. if len(v) == 1 {
  475. var r2 Word
  476. q, r2 = z.divW(u, v[0])
  477. r = z2.setWord(r2)
  478. return
  479. }
  480. q, r = z.divLarge(z2, u, v)
  481. return
  482. }
  483. // q = (uIn-r)/v, with 0 <= r < y
  484. // Uses z as storage for q, and u as storage for r if possible.
  485. // See Knuth, Volume 2, section 4.3.1, Algorithm D.
  486. // Preconditions:
  487. // len(v) >= 2
  488. // len(uIn) >= len(v)
  489. func (z nat) divLarge(u, uIn, v nat) (q, r nat) {
  490. n := len(v)
  491. m := len(uIn) - n
  492. // determine if z can be reused
  493. // TODO(gri) should find a better solution - this if statement
  494. // is very costly (see e.g. time pidigits -s -n 10000)
  495. if alias(z, uIn) || alias(z, v) {
  496. z = nil // z is an alias for uIn or v - cannot reuse
  497. }
  498. q = z.make(m + 1)
  499. qhatv := make(nat, n+1)
  500. if alias(u, uIn) || alias(u, v) {
  501. u = nil // u is an alias for uIn or v - cannot reuse
  502. }
  503. u = u.make(len(uIn) + 1)
  504. u.clear() // TODO(gri) no need to clear if we allocated a new u
  505. // D1.
  506. shift := nlz(v[n-1])
  507. if shift > 0 {
  508. // do not modify v, it may be used by another goroutine simultaneously
  509. v1 := make(nat, n)
  510. shlVU(v1, v, shift)
  511. v = v1
  512. }
  513. u[len(uIn)] = shlVU(u[0:len(uIn)], uIn, shift)
  514. // D2.
  515. for j := m; j >= 0; j-- {
  516. // D3.
  517. qhat := Word(_M)
  518. if u[j+n] != v[n-1] {
  519. var rhat Word
  520. qhat, rhat = divWW(u[j+n], u[j+n-1], v[n-1])
  521. // x1 | x2 = q̂v_{n-2}
  522. x1, x2 := mulWW(qhat, v[n-2])
  523. // test if q̂v_{n-2} > br̂ + u_{j+n-2}
  524. for greaterThan(x1, x2, rhat, u[j+n-2]) {
  525. qhat--
  526. prevRhat := rhat
  527. rhat += v[n-1]
  528. // v[n-1] >= 0, so this tests for overflow.
  529. if rhat < prevRhat {
  530. break
  531. }
  532. x1, x2 = mulWW(qhat, v[n-2])
  533. }
  534. }
  535. // D4.
  536. qhatv[n] = mulAddVWW(qhatv[0:n], v, qhat, 0)
  537. c := subVV(u[j:j+len(qhatv)], u[j:], qhatv)
  538. if c != 0 {
  539. c := addVV(u[j:j+n], u[j:], v)
  540. u[j+n] += c
  541. qhat--
  542. }
  543. q[j] = qhat
  544. }
  545. q = q.norm()
  546. shrVU(u, u, shift)
  547. r = u.norm()
  548. return q, r
  549. }
  550. // Length of x in bits. x must be normalized.
  551. func (x nat) bitLen() int {
  552. if i := len(x) - 1; i >= 0 {
  553. return i*_W + bitLen(x[i])
  554. }
  555. return 0
  556. }
  557. const deBruijn32 = 0x077CB531
  558. var deBruijn32Lookup = []byte{
  559. 0, 1, 28, 2, 29, 14, 24, 3, 30, 22, 20, 15, 25, 17, 4, 8,
  560. 31, 27, 13, 23, 21, 19, 16, 7, 26, 12, 18, 6, 11, 5, 10, 9,
  561. }
  562. const deBruijn64 = 0x03f79d71b4ca8b09
  563. var deBruijn64Lookup = []byte{
  564. 0, 1, 56, 2, 57, 49, 28, 3, 61, 58, 42, 50, 38, 29, 17, 4,
  565. 62, 47, 59, 36, 45, 43, 51, 22, 53, 39, 33, 30, 24, 18, 12, 5,
  566. 63, 55, 48, 27, 60, 41, 37, 16, 46, 35, 44, 21, 52, 32, 23, 11,
  567. 54, 26, 40, 15, 34, 20, 31, 10, 25, 14, 19, 9, 13, 8, 7, 6,
  568. }
  569. // trailingZeroBits returns the number of consecutive least significant zero
  570. // bits of x.
  571. func trailingZeroBits(x Word) uint {
  572. // x & -x leaves only the right-most bit set in the word. Let k be the
  573. // index of that bit. Since only a single bit is set, the value is two
  574. // to the power of k. Multiplying by a power of two is equivalent to
  575. // left shifting, in this case by k bits. The de Bruijn constant is
  576. // such that all six bit, consecutive substrings are distinct.
  577. // Therefore, if we have a left shifted version of this constant we can
  578. // find by how many bits it was shifted by looking at which six bit
  579. // substring ended up at the top of the word.
  580. // (Knuth, volume 4, section 7.3.1)
  581. switch _W {
  582. case 32:
  583. return uint(deBruijn32Lookup[((x&-x)*deBruijn32)>>27])
  584. case 64:
  585. return uint(deBruijn64Lookup[((x&-x)*(deBruijn64&_M))>>58])
  586. default:
  587. panic("unknown word size")
  588. }
  589. }
  590. // trailingZeroBits returns the number of consecutive least significant zero
  591. // bits of x.
  592. func (x nat) trailingZeroBits() uint {
  593. if len(x) == 0 {
  594. return 0
  595. }
  596. var i uint
  597. for x[i] == 0 {
  598. i++
  599. }
  600. // x[i] != 0
  601. return i*_W + trailingZeroBits(x[i])
  602. }
  603. // z = x << s
  604. func (z nat) shl(x nat, s uint) nat {
  605. m := len(x)
  606. if m == 0 {
  607. return z[:0]
  608. }
  609. // m > 0
  610. n := m + int(s/_W)
  611. z = z.make(n + 1)
  612. z[n] = shlVU(z[n-m:n], x, s%_W)
  613. z[0 : n-m].clear()
  614. return z.norm()
  615. }
  616. // z = x >> s
  617. func (z nat) shr(x nat, s uint) nat {
  618. m := len(x)
  619. n := m - int(s/_W)
  620. if n <= 0 {
  621. return z[:0]
  622. }
  623. // n > 0
  624. z = z.make(n)
  625. shrVU(z, x[m-n:], s%_W)
  626. return z.norm()
  627. }
  628. func (z nat) setBit(x nat, i uint, b uint) nat {
  629. j := int(i / _W)
  630. m := Word(1) << (i % _W)
  631. n := len(x)
  632. switch b {
  633. case 0:
  634. z = z.make(n)
  635. copy(z, x)
  636. if j >= n {
  637. // no need to grow
  638. return z
  639. }
  640. z[j] &^= m
  641. return z.norm()
  642. case 1:
  643. if j >= n {
  644. z = z.make(j + 1)
  645. z[n:].clear()
  646. } else {
  647. z = z.make(n)
  648. }
  649. copy(z, x)
  650. z[j] |= m
  651. // no need to normalize
  652. return z
  653. }
  654. panic("set bit is not 0 or 1")
  655. }
  656. // bit returns the value of the i'th bit, with lsb == bit 0.
  657. func (x nat) bit(i uint) uint {
  658. j := i / _W
  659. if j >= uint(len(x)) {
  660. return 0
  661. }
  662. // 0 <= j < len(x)
  663. return uint(x[j] >> (i % _W) & 1)
  664. }
  665. // sticky returns 1 if there's a 1 bit within the
  666. // i least significant bits, otherwise it returns 0.
  667. func (x nat) sticky(i uint) uint {
  668. j := i / _W
  669. if j >= uint(len(x)) {
  670. if len(x) == 0 {
  671. return 0
  672. }
  673. return 1
  674. }
  675. // 0 <= j < len(x)
  676. for _, x := range x[:j] {
  677. if x != 0 {
  678. return 1
  679. }
  680. }
  681. if x[j]<<(_W-i%_W) != 0 {
  682. return 1
  683. }
  684. return 0
  685. }
  686. func (z nat) and(x, y nat) nat {
  687. m := len(x)
  688. n := len(y)
  689. if m > n {
  690. m = n
  691. }
  692. // m <= n
  693. z = z.make(m)
  694. for i := 0; i < m; i++ {
  695. z[i] = x[i] & y[i]
  696. }
  697. return z.norm()
  698. }
  699. func (z nat) andNot(x, y nat) nat {
  700. m := len(x)
  701. n := len(y)
  702. if n > m {
  703. n = m
  704. }
  705. // m >= n
  706. z = z.make(m)
  707. for i := 0; i < n; i++ {
  708. z[i] = x[i] &^ y[i]
  709. }
  710. copy(z[n:m], x[n:m])
  711. return z.norm()
  712. }
  713. func (z nat) or(x, y nat) nat {
  714. m := len(x)
  715. n := len(y)
  716. s := x
  717. if m < n {
  718. n, m = m, n
  719. s = y
  720. }
  721. // m >= n
  722. z = z.make(m)
  723. for i := 0; i < n; i++ {
  724. z[i] = x[i] | y[i]
  725. }
  726. copy(z[n:m], s[n:m])
  727. return z.norm()
  728. }
  729. func (z nat) xor(x, y nat) nat {
  730. m := len(x)
  731. n := len(y)
  732. s := x
  733. if m < n {
  734. n, m = m, n
  735. s = y
  736. }
  737. // m >= n
  738. z = z.make(m)
  739. for i := 0; i < n; i++ {
  740. z[i] = x[i] ^ y[i]
  741. }
  742. copy(z[n:m], s[n:m])
  743. return z.norm()
  744. }
  745. // greaterThan reports whether (x1<<_W + x2) > (y1<<_W + y2)
  746. func greaterThan(x1, x2, y1, y2 Word) bool {
  747. return x1 > y1 || x1 == y1 && x2 > y2
  748. }
  749. // modW returns x % d.
  750. func (x nat) modW(d Word) (r Word) {
  751. // TODO(agl): we don't actually need to store the q value.
  752. var q nat
  753. q = q.make(len(x))
  754. return divWVW(q, 0, x, d)
  755. }
  756. // random creates a random integer in [0..limit), using the space in z if
  757. // possible. n is the bit length of limit.
  758. func (z nat) random(rand *rand.Rand, limit nat, n int) nat {
  759. if alias(z, limit) {
  760. z = nil // z is an alias for limit - cannot reuse
  761. }
  762. z = z.make(len(limit))
  763. bitLengthOfMSW := uint(n % _W)
  764. if bitLengthOfMSW == 0 {
  765. bitLengthOfMSW = _W
  766. }
  767. mask := Word((1 << bitLengthOfMSW) - 1)
  768. for {
  769. switch _W {
  770. case 32:
  771. for i := range z {
  772. z[i] = Word(rand.Uint32())
  773. }
  774. case 64:
  775. for i := range z {
  776. z[i] = Word(rand.Uint32()) | Word(rand.Uint32())<<32
  777. }
  778. default:
  779. panic("unknown word size")
  780. }
  781. z[len(limit)-1] &= mask
  782. if z.cmp(limit) < 0 {
  783. break
  784. }
  785. }
  786. return z.norm()
  787. }
  788. // If m != 0 (i.e., len(m) != 0), expNN sets z to x**y mod m;
  789. // otherwise it sets z to x**y. The result is the value of z.
  790. func (z nat) expNN(x, y, m nat) nat {
  791. if alias(z, x) || alias(z, y) {
  792. // We cannot allow in-place modification of x or y.
  793. z = nil
  794. }
  795. // x**y mod 1 == 0
  796. if len(m) == 1 && m[0] == 1 {
  797. return z.setWord(0)
  798. }
  799. // m == 0 || m > 1
  800. // x**0 == 1
  801. if len(y) == 0 {
  802. return z.setWord(1)
  803. }
  804. // y > 0
  805. // x**1 mod m == x mod m
  806. if len(y) == 1 && y[0] == 1 && len(m) != 0 {
  807. _, z = z.div(z, x, m)
  808. return z
  809. }
  810. // y > 1
  811. if len(m) != 0 {
  812. // We likely end up being as long as the modulus.
  813. z = z.make(len(m))
  814. }
  815. z = z.set(x)
  816. // If the base is non-trivial and the exponent is large, we use
  817. // 4-bit, windowed exponentiation. This involves precomputing 14 values
  818. // (x^2...x^15) but then reduces the number of multiply-reduces by a
  819. // third. Even for a 32-bit exponent, this reduces the number of
  820. // operations. Uses Montgomery method for odd moduli.
  821. if len(x) > 1 && len(y) > 1 && len(m) > 0 {
  822. if m[0]&1 == 1 {
  823. return z.expNNMontgomery(x, y, m)
  824. }
  825. return z.expNNWindowed(x, y, m)
  826. }
  827. v := y[len(y)-1] // v > 0 because y is normalized and y > 0
  828. shift := nlz(v) + 1
  829. v <<= shift
  830. var q nat
  831. const mask = 1 << (_W - 1)
  832. // We walk through the bits of the exponent one by one. Each time we
  833. // see a bit, we square, thus doubling the power. If the bit is a one,
  834. // we also multiply by x, thus adding one to the power.
  835. w := _W - int(shift)
  836. // zz and r are used to avoid allocating in mul and div as
  837. // otherwise the arguments would alias.
  838. var zz, r nat
  839. for j := 0; j < w; j++ {
  840. zz = zz.mul(z, z)
  841. zz, z = z, zz
  842. if v&mask != 0 {
  843. zz = zz.mul(z, x)
  844. zz, z = z, zz
  845. }
  846. if len(m) != 0 {
  847. zz, r = zz.div(r, z, m)
  848. zz, r, q, z = q, z, zz, r
  849. }
  850. v <<= 1
  851. }
  852. for i := len(y) - 2; i >= 0; i-- {
  853. v = y[i]
  854. for j := 0; j < _W; j++ {
  855. zz = zz.mul(z, z)
  856. zz, z = z, zz
  857. if v&mask != 0 {
  858. zz = zz.mul(z, x)
  859. zz, z = z, zz
  860. }
  861. if len(m) != 0 {
  862. zz, r = zz.div(r, z, m)
  863. zz, r, q, z = q, z, zz, r
  864. }
  865. v <<= 1
  866. }
  867. }
  868. return z.norm()
  869. }
  870. // expNNWindowed calculates x**y mod m using a fixed, 4-bit window.
  871. func (z nat) expNNWindowed(x, y, m nat) nat {
  872. // zz and r are used to avoid allocating in mul and div as otherwise
  873. // the arguments would alias.
  874. var zz, r nat
  875. const n = 4
  876. // powers[i] contains x^i.
  877. var powers [1 << n]nat
  878. powers[0] = natOne
  879. powers[1] = x
  880. for i := 2; i < 1<<n; i += 2 {
  881. p2, p, p1 := &powers[i/2], &powers[i], &powers[i+1]
  882. *p = p.mul(*p2, *p2)
  883. zz, r = zz.div(r, *p, m)
  884. *p, r = r, *p
  885. *p1 = p1.mul(*p, x)
  886. zz, r = zz.div(r, *p1, m)
  887. *p1, r = r, *p1
  888. }
  889. z = z.setWord(1)
  890. for i := len(y) - 1; i >= 0; i-- {
  891. yi := y[i]
  892. for j := 0; j < _W; j += n {
  893. if i != len(y)-1 || j != 0 {
  894. // Unrolled loop for significant performance
  895. // gain. Use go test -bench=".*" in crypto/rsa
  896. // to check performance before making changes.
  897. zz = zz.mul(z, z)
  898. zz, z = z, zz
  899. zz, r = zz.div(r, z, m)
  900. z, r = r, z
  901. zz = zz.mul(z, z)
  902. zz, z = z, zz
  903. zz, r = zz.div(r, z, m)
  904. z, r = r, z
  905. zz = zz.mul(z, z)
  906. zz, z = z, zz
  907. zz, r = zz.div(r, z, m)
  908. z, r = r, z
  909. zz = zz.mul(z, z)
  910. zz, z = z, zz
  911. zz, r = zz.div(r, z, m)
  912. z, r = r, z
  913. }
  914. zz = zz.mul(z, powers[yi>>(_W-n)])
  915. zz, z = z, zz
  916. zz, r = zz.div(r, z, m)
  917. z, r = r, z
  918. yi <<= n
  919. }
  920. }
  921. return z.norm()
  922. }
  923. // expNNMontgomery calculates x**y mod m using a fixed, 4-bit window.
  924. // Uses Montgomery representation.
  925. func (z nat) expNNMontgomery(x, y, m nat) nat {
  926. var zz, one, rr, RR nat
  927. numWords := len(m)
  928. // We want the lengths of x and m to be equal.
  929. if len(x) > numWords {
  930. _, rr = rr.div(rr, x, m)
  931. } else if len(x) < numWords {
  932. rr = rr.make(numWords)
  933. rr.clear()
  934. for i := range x {
  935. rr[i] = x[i]
  936. }
  937. } else {
  938. rr = x
  939. }
  940. x = rr
  941. // Ideally the precomputations would be performed outside, and reused
  942. // k0 = -mˆ-1 mod 2ˆ_W. Algorithm from: Dumas, J.G. "On Newton–Raphson
  943. // Iteration for Multiplicative Inverses Modulo Prime Powers".
  944. k0 := 2 - m[0]
  945. t := m[0] - 1
  946. for i := 1; i < _W; i <<= 1 {
  947. t *= t
  948. k0 *= (t + 1)
  949. }
  950. k0 = -k0
  951. // RR = 2ˆ(2*_W*len(m)) mod m
  952. RR = RR.setWord(1)
  953. zz = zz.shl(RR, uint(2*numWords*_W))
  954. _, RR = RR.div(RR, zz, m)
  955. if len(RR) < numWords {
  956. zz = zz.make(numWords)
  957. copy(zz, RR)
  958. RR = zz
  959. }
  960. // one = 1, with equal length to that of m
  961. one = one.make(numWords)
  962. one.clear()
  963. one[0] = 1
  964. const n = 4
  965. // powers[i] contains x^i
  966. var powers [1 << n]nat
  967. powers[0] = powers[0].montgomery(one, RR, m, k0, numWords)
  968. powers[1] = powers[1].montgomery(x, RR, m, k0, numWords)
  969. for i := 2; i < 1<<n; i++ {
  970. powers[i] = powers[i].montgomery(powers[i-1], powers[1], m, k0, numWords)
  971. }
  972. // initialize z = 1 (Montgomery 1)
  973. z = z.make(numWords)
  974. copy(z, powers[0])
  975. zz = zz.make(numWords)
  976. // same windowed exponent, but with Montgomery multiplications
  977. for i := len(y) - 1; i >= 0; i-- {
  978. yi := y[i]
  979. for j := 0; j < _W; j += n {
  980. if i != len(y)-1 || j != 0 {
  981. zz = zz.montgomery(z, z, m, k0, numWords)
  982. z = z.montgomery(zz, zz, m, k0, numWords)
  983. zz = zz.montgomery(z, z, m, k0, numWords)
  984. z = z.montgomery(zz, zz, m, k0, numWords)
  985. }
  986. zz = zz.montgomery(z, powers[yi>>(_W-n)], m, k0, numWords)
  987. z, zz = zz, z
  988. yi <<= n
  989. }
  990. }
  991. // convert to regular number
  992. zz = zz.montgomery(z, one, m, k0, numWords)
  993. return zz.norm()
  994. }
  995. // probablyPrime performs reps Miller-Rabin tests to check whether n is prime.
  996. // If it returns true, n is prime with probability 1 - 1/4^reps.
  997. // If it returns false, n is not prime.
  998. func (n nat) probablyPrime(reps int) bool {
  999. if len(n) == 0 {
  1000. return false
  1001. }
  1002. if len(n) == 1 {
  1003. if n[0] < 2 {
  1004. return false
  1005. }
  1006. if n[0]%2 == 0 {
  1007. return n[0] == 2
  1008. }
  1009. // We have to exclude these cases because we reject all
  1010. // multiples of these numbers below.
  1011. switch n[0] {
  1012. case 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53:
  1013. return true
  1014. }
  1015. }
  1016. if n[0]&1 == 0 {
  1017. return false // n is even
  1018. }
  1019. const primesProduct32 = 0xC0CFD797 // Π {p ∈ primes, 2 < p <= 29}
  1020. const primesProduct64 = 0xE221F97C30E94E1D // Π {p ∈ primes, 2 < p <= 53}
  1021. var r Word
  1022. switch _W {
  1023. case 32:
  1024. r = n.modW(primesProduct32)
  1025. case 64:
  1026. r = n.modW(primesProduct64 & _M)
  1027. default:
  1028. panic("Unknown word size")
  1029. }
  1030. if r%3 == 0 || r%5 == 0 || r%7 == 0 || r%11 == 0 ||
  1031. r%13 == 0 || r%17 == 0 || r%19 == 0 || r%23 == 0 || r%29 == 0 {
  1032. return false
  1033. }
  1034. if _W == 64 && (r%31 == 0 || r%37 == 0 || r%41 == 0 ||
  1035. r%43 == 0 || r%47 == 0 || r%53 == 0) {
  1036. return false
  1037. }
  1038. nm1 := nat(nil).sub(n, natOne)
  1039. // determine q, k such that nm1 = q << k
  1040. k := nm1.trailingZeroBits()
  1041. q := nat(nil).shr(nm1, k)
  1042. nm3 := nat(nil).sub(nm1, natTwo)
  1043. rand := rand.New(rand.NewSource(int64(n[0])))
  1044. var x, y, quotient nat
  1045. nm3Len := nm3.bitLen()
  1046. NextRandom:
  1047. for i := 0; i < reps; i++ {
  1048. x = x.random(rand, nm3, nm3Len)
  1049. x = x.add(x, natTwo)
  1050. y = y.expNN(x, q, n)
  1051. if y.cmp(natOne) == 0 || y.cmp(nm1) == 0 {
  1052. continue
  1053. }
  1054. for j := uint(1); j < k; j++ {
  1055. y = y.mul(y, y)
  1056. quotient, y = quotient.div(y, y, n)
  1057. if y.cmp(nm1) == 0 {
  1058. continue NextRandom
  1059. }
  1060. if y.cmp(natOne) == 0 {
  1061. return false
  1062. }
  1063. }
  1064. return false
  1065. }
  1066. return true
  1067. }
  1068. // bytes writes the value of z into buf using big-endian encoding.
  1069. // len(buf) must be >= len(z)*_S. The value of z is encoded in the
  1070. // slice buf[i:]. The number i of unused bytes at the beginning of
  1071. // buf is returned as result.
  1072. func (z nat) bytes(buf []byte) (i int) {
  1073. i = len(buf)
  1074. for _, d := range z {
  1075. for j := 0; j < _S; j++ {
  1076. i--
  1077. buf[i] = byte(d)
  1078. d >>= 8
  1079. }
  1080. }
  1081. for i < len(buf) && buf[i] == 0 {
  1082. i++
  1083. }
  1084. return
  1085. }
  1086. // setBytes interprets buf as the bytes of a big-endian unsigned
  1087. // integer, sets z to that value, and returns z.
  1088. func (z nat) setBytes(buf []byte) nat {
  1089. z = z.make((len(buf) + _S - 1) / _S)
  1090. k := 0
  1091. s := uint(0)
  1092. var d Word
  1093. for i := len(buf); i > 0; i-- {
  1094. d |= Word(buf[i-1]) << s
  1095. if s += 8; s == _S*8 {
  1096. z[k] = d
  1097. k++
  1098. s = 0
  1099. d = 0
  1100. }
  1101. }
  1102. if k < len(z) {
  1103. z[k] = d
  1104. }
  1105. return z.norm()
  1106. }