PageRenderTime 57ms CodeModel.GetById 19ms RepoModel.GetById 1ms app.codeStats 0ms

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

http://github.com/axw/llgo
Go | 1540 lines | 1338 code | 159 blank | 43 comment | 300 complexity | def4b3945b26415a2b7c49d229522b7e 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
  5. import (
  6. "bytes"
  7. "encoding/gob"
  8. "encoding/hex"
  9. "encoding/json"
  10. "encoding/xml"
  11. "fmt"
  12. "math/rand"
  13. "testing"
  14. "testing/quick"
  15. )
  16. func isNormalized(x *Int) bool {
  17. if len(x.abs) == 0 {
  18. return !x.neg
  19. }
  20. // len(x.abs) > 0
  21. return x.abs[len(x.abs)-1] != 0
  22. }
  23. type funZZ func(z, x, y *Int) *Int
  24. type argZZ struct {
  25. z, x, y *Int
  26. }
  27. var sumZZ = []argZZ{
  28. {NewInt(0), NewInt(0), NewInt(0)},
  29. {NewInt(1), NewInt(1), NewInt(0)},
  30. {NewInt(1111111110), NewInt(123456789), NewInt(987654321)},
  31. {NewInt(-1), NewInt(-1), NewInt(0)},
  32. {NewInt(864197532), NewInt(-123456789), NewInt(987654321)},
  33. {NewInt(-1111111110), NewInt(-123456789), NewInt(-987654321)},
  34. }
  35. var prodZZ = []argZZ{
  36. {NewInt(0), NewInt(0), NewInt(0)},
  37. {NewInt(0), NewInt(1), NewInt(0)},
  38. {NewInt(1), NewInt(1), NewInt(1)},
  39. {NewInt(-991 * 991), NewInt(991), NewInt(-991)},
  40. // TODO(gri) add larger products
  41. }
  42. func TestSignZ(t *testing.T) {
  43. var zero Int
  44. for _, a := range sumZZ {
  45. s := a.z.Sign()
  46. e := a.z.Cmp(&zero)
  47. if s != e {
  48. t.Errorf("got %d; want %d for z = %v", s, e, a.z)
  49. }
  50. }
  51. }
  52. func TestSetZ(t *testing.T) {
  53. for _, a := range sumZZ {
  54. var z Int
  55. z.Set(a.z)
  56. if !isNormalized(&z) {
  57. t.Errorf("%v is not normalized", z)
  58. }
  59. if (&z).Cmp(a.z) != 0 {
  60. t.Errorf("got z = %v; want %v", z, a.z)
  61. }
  62. }
  63. }
  64. func TestAbsZ(t *testing.T) {
  65. var zero Int
  66. for _, a := range sumZZ {
  67. var z Int
  68. z.Abs(a.z)
  69. var e Int
  70. e.Set(a.z)
  71. if e.Cmp(&zero) < 0 {
  72. e.Sub(&zero, &e)
  73. }
  74. if z.Cmp(&e) != 0 {
  75. t.Errorf("got z = %v; want %v", z, e)
  76. }
  77. }
  78. }
  79. func testFunZZ(t *testing.T, msg string, f funZZ, a argZZ) {
  80. var z Int
  81. f(&z, a.x, a.y)
  82. if !isNormalized(&z) {
  83. t.Errorf("%s%v is not normalized", msg, z)
  84. }
  85. if (&z).Cmp(a.z) != 0 {
  86. t.Errorf("%s%+v\n\tgot z = %v; want %v", msg, a, &z, a.z)
  87. }
  88. }
  89. func TestSumZZ(t *testing.T) {
  90. AddZZ := func(z, x, y *Int) *Int { return z.Add(x, y) }
  91. SubZZ := func(z, x, y *Int) *Int { return z.Sub(x, y) }
  92. for _, a := range sumZZ {
  93. arg := a
  94. testFunZZ(t, "AddZZ", AddZZ, arg)
  95. arg = argZZ{a.z, a.y, a.x}
  96. testFunZZ(t, "AddZZ symmetric", AddZZ, arg)
  97. arg = argZZ{a.x, a.z, a.y}
  98. testFunZZ(t, "SubZZ", SubZZ, arg)
  99. arg = argZZ{a.y, a.z, a.x}
  100. testFunZZ(t, "SubZZ symmetric", SubZZ, arg)
  101. }
  102. }
  103. func TestProdZZ(t *testing.T) {
  104. MulZZ := func(z, x, y *Int) *Int { return z.Mul(x, y) }
  105. for _, a := range prodZZ {
  106. arg := a
  107. testFunZZ(t, "MulZZ", MulZZ, arg)
  108. arg = argZZ{a.z, a.y, a.x}
  109. testFunZZ(t, "MulZZ symmetric", MulZZ, arg)
  110. }
  111. }
  112. // mulBytes returns x*y via grade school multiplication. Both inputs
  113. // and the result are assumed to be in big-endian representation (to
  114. // match the semantics of Int.Bytes and Int.SetBytes).
  115. func mulBytes(x, y []byte) []byte {
  116. z := make([]byte, len(x)+len(y))
  117. // multiply
  118. k0 := len(z) - 1
  119. for j := len(y) - 1; j >= 0; j-- {
  120. d := int(y[j])
  121. if d != 0 {
  122. k := k0
  123. carry := 0
  124. for i := len(x) - 1; i >= 0; i-- {
  125. t := int(z[k]) + int(x[i])*d + carry
  126. z[k], carry = byte(t), t>>8
  127. k--
  128. }
  129. z[k] = byte(carry)
  130. }
  131. k0--
  132. }
  133. // normalize (remove leading 0's)
  134. i := 0
  135. for i < len(z) && z[i] == 0 {
  136. i++
  137. }
  138. return z[i:]
  139. }
  140. func checkMul(a, b []byte) bool {
  141. var x, y, z1 Int
  142. x.SetBytes(a)
  143. y.SetBytes(b)
  144. z1.Mul(&x, &y)
  145. var z2 Int
  146. z2.SetBytes(mulBytes(a, b))
  147. return z1.Cmp(&z2) == 0
  148. }
  149. func TestMul(t *testing.T) {
  150. if err := quick.Check(checkMul, nil); err != nil {
  151. t.Error(err)
  152. }
  153. }
  154. var mulRangesZ = []struct {
  155. a, b int64
  156. prod string
  157. }{
  158. // entirely positive ranges are covered by mulRangesN
  159. {-1, 1, "0"},
  160. {-2, -1, "2"},
  161. {-3, -2, "6"},
  162. {-3, -1, "-6"},
  163. {1, 3, "6"},
  164. {-10, -10, "-10"},
  165. {0, -1, "1"}, // empty range
  166. {-1, -100, "1"}, // empty range
  167. {-1, 1, "0"}, // range includes 0
  168. {-1e9, 0, "0"}, // range includes 0
  169. {-1e9, 1e9, "0"}, // range includes 0
  170. {-10, -1, "3628800"}, // 10!
  171. {-20, -2, "-2432902008176640000"}, // -20!
  172. {-99, -1,
  173. "-933262154439441526816992388562667004907159682643816214685929" +
  174. "638952175999932299156089414639761565182862536979208272237582" +
  175. "511852109168640000000000000000000000", // -99!
  176. },
  177. }
  178. func TestMulRangeZ(t *testing.T) {
  179. var tmp Int
  180. // test entirely positive ranges
  181. for i, r := range mulRangesN {
  182. prod := tmp.MulRange(int64(r.a), int64(r.b)).String()
  183. if prod != r.prod {
  184. t.Errorf("#%da: got %s; want %s", i, prod, r.prod)
  185. }
  186. }
  187. // test other ranges
  188. for i, r := range mulRangesZ {
  189. prod := tmp.MulRange(r.a, r.b).String()
  190. if prod != r.prod {
  191. t.Errorf("#%db: got %s; want %s", i, prod, r.prod)
  192. }
  193. }
  194. }
  195. func TestBinomial(t *testing.T) {
  196. var z Int
  197. for _, test := range []struct {
  198. n, k int64
  199. want string
  200. }{
  201. {0, 0, "1"},
  202. {0, 1, "0"},
  203. {1, 0, "1"},
  204. {1, 1, "1"},
  205. {1, 10, "0"},
  206. {4, 0, "1"},
  207. {4, 1, "4"},
  208. {4, 2, "6"},
  209. {4, 3, "4"},
  210. {4, 4, "1"},
  211. {10, 1, "10"},
  212. {10, 9, "10"},
  213. {10, 5, "252"},
  214. {11, 5, "462"},
  215. {11, 6, "462"},
  216. {100, 10, "17310309456440"},
  217. {100, 90, "17310309456440"},
  218. {1000, 10, "263409560461970212832400"},
  219. {1000, 990, "263409560461970212832400"},
  220. } {
  221. if got := z.Binomial(test.n, test.k).String(); got != test.want {
  222. t.Errorf("Binomial(%d, %d) = %s; want %s", test.n, test.k, got, test.want)
  223. }
  224. }
  225. }
  226. func BenchmarkBinomial(b *testing.B) {
  227. var z Int
  228. for i := b.N - 1; i >= 0; i-- {
  229. z.Binomial(1000, 990)
  230. }
  231. }
  232. // Examples from the Go Language Spec, section "Arithmetic operators"
  233. var divisionSignsTests = []struct {
  234. x, y int64
  235. q, r int64 // T-division
  236. d, m int64 // Euclidian division
  237. }{
  238. {5, 3, 1, 2, 1, 2},
  239. {-5, 3, -1, -2, -2, 1},
  240. {5, -3, -1, 2, -1, 2},
  241. {-5, -3, 1, -2, 2, 1},
  242. {1, 2, 0, 1, 0, 1},
  243. {8, 4, 2, 0, 2, 0},
  244. }
  245. func TestDivisionSigns(t *testing.T) {
  246. for i, test := range divisionSignsTests {
  247. x := NewInt(test.x)
  248. y := NewInt(test.y)
  249. q := NewInt(test.q)
  250. r := NewInt(test.r)
  251. d := NewInt(test.d)
  252. m := NewInt(test.m)
  253. q1 := new(Int).Quo(x, y)
  254. r1 := new(Int).Rem(x, y)
  255. if !isNormalized(q1) {
  256. t.Errorf("#%d Quo: %v is not normalized", i, *q1)
  257. }
  258. if !isNormalized(r1) {
  259. t.Errorf("#%d Rem: %v is not normalized", i, *r1)
  260. }
  261. if q1.Cmp(q) != 0 || r1.Cmp(r) != 0 {
  262. t.Errorf("#%d QuoRem: got (%s, %s), want (%s, %s)", i, q1, r1, q, r)
  263. }
  264. q2, r2 := new(Int).QuoRem(x, y, new(Int))
  265. if !isNormalized(q2) {
  266. t.Errorf("#%d Quo: %v is not normalized", i, *q2)
  267. }
  268. if !isNormalized(r2) {
  269. t.Errorf("#%d Rem: %v is not normalized", i, *r2)
  270. }
  271. if q2.Cmp(q) != 0 || r2.Cmp(r) != 0 {
  272. t.Errorf("#%d QuoRem: got (%s, %s), want (%s, %s)", i, q2, r2, q, r)
  273. }
  274. d1 := new(Int).Div(x, y)
  275. m1 := new(Int).Mod(x, y)
  276. if !isNormalized(d1) {
  277. t.Errorf("#%d Div: %v is not normalized", i, *d1)
  278. }
  279. if !isNormalized(m1) {
  280. t.Errorf("#%d Mod: %v is not normalized", i, *m1)
  281. }
  282. if d1.Cmp(d) != 0 || m1.Cmp(m) != 0 {
  283. t.Errorf("#%d DivMod: got (%s, %s), want (%s, %s)", i, d1, m1, d, m)
  284. }
  285. d2, m2 := new(Int).DivMod(x, y, new(Int))
  286. if !isNormalized(d2) {
  287. t.Errorf("#%d Div: %v is not normalized", i, *d2)
  288. }
  289. if !isNormalized(m2) {
  290. t.Errorf("#%d Mod: %v is not normalized", i, *m2)
  291. }
  292. if d2.Cmp(d) != 0 || m2.Cmp(m) != 0 {
  293. t.Errorf("#%d DivMod: got (%s, %s), want (%s, %s)", i, d2, m2, d, m)
  294. }
  295. }
  296. }
  297. func norm(x nat) nat {
  298. i := len(x)
  299. for i > 0 && x[i-1] == 0 {
  300. i--
  301. }
  302. return x[:i]
  303. }
  304. func TestBits(t *testing.T) {
  305. for _, test := range []nat{
  306. nil,
  307. {0},
  308. {1},
  309. {0, 1, 2, 3, 4},
  310. {4, 3, 2, 1, 0},
  311. {4, 3, 2, 1, 0, 0, 0, 0},
  312. } {
  313. var z Int
  314. z.neg = true
  315. got := z.SetBits(test)
  316. want := norm(test)
  317. if got.abs.cmp(want) != 0 {
  318. t.Errorf("SetBits(%v) = %v; want %v", test, got.abs, want)
  319. }
  320. if got.neg {
  321. t.Errorf("SetBits(%v): got negative result", test)
  322. }
  323. bits := nat(z.Bits())
  324. if bits.cmp(want) != 0 {
  325. t.Errorf("%v.Bits() = %v; want %v", z.abs, bits, want)
  326. }
  327. }
  328. }
  329. func checkSetBytes(b []byte) bool {
  330. hex1 := hex.EncodeToString(new(Int).SetBytes(b).Bytes())
  331. hex2 := hex.EncodeToString(b)
  332. for len(hex1) < len(hex2) {
  333. hex1 = "0" + hex1
  334. }
  335. for len(hex1) > len(hex2) {
  336. hex2 = "0" + hex2
  337. }
  338. return hex1 == hex2
  339. }
  340. func TestSetBytes(t *testing.T) {
  341. if err := quick.Check(checkSetBytes, nil); err != nil {
  342. t.Error(err)
  343. }
  344. }
  345. func checkBytes(b []byte) bool {
  346. b2 := new(Int).SetBytes(b).Bytes()
  347. return bytes.Equal(b, b2)
  348. }
  349. func TestBytes(t *testing.T) {
  350. if err := quick.Check(checkBytes, nil); err != nil {
  351. t.Error(err)
  352. }
  353. }
  354. func checkQuo(x, y []byte) bool {
  355. u := new(Int).SetBytes(x)
  356. v := new(Int).SetBytes(y)
  357. if len(v.abs) == 0 {
  358. return true
  359. }
  360. r := new(Int)
  361. q, r := new(Int).QuoRem(u, v, r)
  362. if r.Cmp(v) >= 0 {
  363. return false
  364. }
  365. uprime := new(Int).Set(q)
  366. uprime.Mul(uprime, v)
  367. uprime.Add(uprime, r)
  368. return uprime.Cmp(u) == 0
  369. }
  370. var quoTests = []struct {
  371. x, y string
  372. q, r string
  373. }{
  374. {
  375. "476217953993950760840509444250624797097991362735329973741718102894495832294430498335824897858659711275234906400899559094370964723884706254265559534144986498357",
  376. "9353930466774385905609975137998169297361893554149986716853295022578535724979483772383667534691121982974895531435241089241440253066816724367338287092081996",
  377. "50911",
  378. "1",
  379. },
  380. {
  381. "11510768301994997771168",
  382. "1328165573307167369775",
  383. "8",
  384. "885443715537658812968",
  385. },
  386. }
  387. func TestQuo(t *testing.T) {
  388. if err := quick.Check(checkQuo, nil); err != nil {
  389. t.Error(err)
  390. }
  391. for i, test := range quoTests {
  392. x, _ := new(Int).SetString(test.x, 10)
  393. y, _ := new(Int).SetString(test.y, 10)
  394. expectedQ, _ := new(Int).SetString(test.q, 10)
  395. expectedR, _ := new(Int).SetString(test.r, 10)
  396. r := new(Int)
  397. q, r := new(Int).QuoRem(x, y, r)
  398. if q.Cmp(expectedQ) != 0 || r.Cmp(expectedR) != 0 {
  399. t.Errorf("#%d got (%s, %s) want (%s, %s)", i, q, r, expectedQ, expectedR)
  400. }
  401. }
  402. }
  403. func TestQuoStepD6(t *testing.T) {
  404. // See Knuth, Volume 2, section 4.3.1, exercise 21. This code exercises
  405. // a code path which only triggers 1 in 10^{-19} cases.
  406. u := &Int{false, nat{0, 0, 1 + 1<<(_W-1), _M ^ (1 << (_W - 1))}}
  407. v := &Int{false, nat{5, 2 + 1<<(_W-1), 1 << (_W - 1)}}
  408. r := new(Int)
  409. q, r := new(Int).QuoRem(u, v, r)
  410. const expectedQ64 = "18446744073709551613"
  411. const expectedR64 = "3138550867693340382088035895064302439801311770021610913807"
  412. const expectedQ32 = "4294967293"
  413. const expectedR32 = "39614081266355540837921718287"
  414. if q.String() != expectedQ64 && q.String() != expectedQ32 ||
  415. r.String() != expectedR64 && r.String() != expectedR32 {
  416. t.Errorf("got (%s, %s) want (%s, %s) or (%s, %s)", q, r, expectedQ64, expectedR64, expectedQ32, expectedR32)
  417. }
  418. }
  419. var bitLenTests = []struct {
  420. in string
  421. out int
  422. }{
  423. {"-1", 1},
  424. {"0", 0},
  425. {"1", 1},
  426. {"2", 2},
  427. {"4", 3},
  428. {"0xabc", 12},
  429. {"0x8000", 16},
  430. {"0x80000000", 32},
  431. {"0x800000000000", 48},
  432. {"0x8000000000000000", 64},
  433. {"0x80000000000000000000", 80},
  434. {"-0x4000000000000000000000", 87},
  435. }
  436. func TestBitLen(t *testing.T) {
  437. for i, test := range bitLenTests {
  438. x, ok := new(Int).SetString(test.in, 0)
  439. if !ok {
  440. t.Errorf("#%d test input invalid: %s", i, test.in)
  441. continue
  442. }
  443. if n := x.BitLen(); n != test.out {
  444. t.Errorf("#%d got %d want %d", i, n, test.out)
  445. }
  446. }
  447. }
  448. var expTests = []struct {
  449. x, y, m string
  450. out string
  451. }{
  452. // y <= 0
  453. {"0", "0", "", "1"},
  454. {"1", "0", "", "1"},
  455. {"-10", "0", "", "1"},
  456. {"1234", "-1", "", "1"},
  457. // m == 1
  458. {"0", "0", "1", "0"},
  459. {"1", "0", "1", "0"},
  460. {"-10", "0", "1", "0"},
  461. {"1234", "-1", "1", "0"},
  462. // misc
  463. {"5", "1", "3", "2"},
  464. {"5", "-7", "", "1"},
  465. {"-5", "-7", "", "1"},
  466. {"5", "0", "", "1"},
  467. {"-5", "0", "", "1"},
  468. {"5", "1", "", "5"},
  469. {"-5", "1", "", "-5"},
  470. {"-5", "1", "7", "2"},
  471. {"-2", "3", "2", "0"},
  472. {"5", "2", "", "25"},
  473. {"1", "65537", "2", "1"},
  474. {"0x8000000000000000", "2", "", "0x40000000000000000000000000000000"},
  475. {"0x8000000000000000", "2", "6719", "4944"},
  476. {"0x8000000000000000", "3", "6719", "5447"},
  477. {"0x8000000000000000", "1000", "6719", "1603"},
  478. {"0x8000000000000000", "1000000", "6719", "3199"},
  479. {"0x8000000000000000", "-1000000", "6719", "1"},
  480. {
  481. "2938462938472983472983659726349017249287491026512746239764525612965293865296239471239874193284792387498274256129746192347",
  482. "298472983472983471903246121093472394872319615612417471234712061",
  483. "29834729834729834729347290846729561262544958723956495615629569234729836259263598127342374289365912465901365498236492183464",
  484. "23537740700184054162508175125554701713153216681790245129157191391322321508055833908509185839069455749219131480588829346291",
  485. },
  486. // test case for issue 8822
  487. {
  488. "-0x1BCE04427D8032319A89E5C4136456671AC620883F2C4139E57F91307C485AD2D6204F4F87A58262652DB5DBBAC72B0613E51B835E7153BEC6068F5C8D696B74DBD18FEC316AEF73985CF0475663208EB46B4F17DD9DA55367B03323E5491A70997B90C059FB34809E6EE55BCFBD5F2F52233BFE62E6AA9E4E26A1D4C2439883D14F2633D55D8AA66A1ACD5595E778AC3A280517F1157989E70C1A437B849F1877B779CC3CDDEDE2DAA6594A6C66D181A00A5F777EE60596D8773998F6E988DEAE4CCA60E4DDCF9590543C89F74F603259FCAD71660D30294FBBE6490300F78A9D63FA660DC9417B8B9DDA28BEB3977B621B988E23D4D954F322C3540541BC649ABD504C50FADFD9F0987D58A2BF689313A285E773FF02899A6EF887D1D4A0D2",
  489. "0xB08FFB20760FFED58FADA86DFEF71AD72AA0FA763219618FE022C197E54708BB1191C66470250FCE8879487507CEE41381CA4D932F81C2B3F1AB20B539D50DCD",
  490. "0xAC6BDB41324A9A9BF166DE5E1389582FAF72B6651987EE07FC3192943DB56050A37329CBB4A099ED8193E0757767A13DD52312AB4B03310DCD7F48A9DA04FD50E8083969EDB767B0CF6095179A163AB3661A05FBD5FAAAE82918A9962F0B93B855F97993EC975EEAA80D740ADBF4FF747359D041D5C33EA71D281E446B14773BCA97B43A23FB801676BD207A436C6481F1D2B9078717461A5B9D32E688F87748544523B524B0D57D5EA77A2775D2ECFA032CFBDBF52FB3786160279004E57AE6AF874E7303CE53299CCC041C7BC308D82A5698F3A8D0C38271AE35F8E9DBFBB694B5C803D89F7AE435DE236D525F54759B65E372FCD68EF20FA7111F9E4AFF73",
  491. "21484252197776302499639938883777710321993113097987201050501182909581359357618579566746556372589385361683610524730509041328855066514963385522570894839035884713051640171474186548713546686476761306436434146475140156284389181808675016576845833340494848283681088886584219750554408060556769486628029028720727393293111678826356480455433909233520504112074401376133077150471237549474149190242010469539006449596611576612573955754349042329130631128234637924786466585703488460540228477440853493392086251021228087076124706778899179648655221663765993962724699135217212118535057766739392069738618682722216712319320435674779146070442",
  492. },
  493. }
  494. func TestExp(t *testing.T) {
  495. for i, test := range expTests {
  496. x, ok1 := new(Int).SetString(test.x, 0)
  497. y, ok2 := new(Int).SetString(test.y, 0)
  498. out, ok3 := new(Int).SetString(test.out, 0)
  499. var ok4 bool
  500. var m *Int
  501. if len(test.m) == 0 {
  502. m, ok4 = nil, true
  503. } else {
  504. m, ok4 = new(Int).SetString(test.m, 0)
  505. }
  506. if !ok1 || !ok2 || !ok3 || !ok4 {
  507. t.Errorf("#%d: error in input", i)
  508. continue
  509. }
  510. z1 := new(Int).Exp(x, y, m)
  511. if !isNormalized(z1) {
  512. t.Errorf("#%d: %v is not normalized", i, *z1)
  513. }
  514. if z1.Cmp(out) != 0 {
  515. t.Errorf("#%d: got %s want %s", i, z1, out)
  516. }
  517. if m == nil {
  518. // The result should be the same as for m == 0;
  519. // specifically, there should be no div-zero panic.
  520. m = &Int{abs: nat{}} // m != nil && len(m.abs) == 0
  521. z2 := new(Int).Exp(x, y, m)
  522. if z2.Cmp(z1) != 0 {
  523. t.Errorf("#%d: got %s want %s", i, z2, z1)
  524. }
  525. }
  526. }
  527. }
  528. func checkGcd(aBytes, bBytes []byte) bool {
  529. x := new(Int)
  530. y := new(Int)
  531. a := new(Int).SetBytes(aBytes)
  532. b := new(Int).SetBytes(bBytes)
  533. d := new(Int).GCD(x, y, a, b)
  534. x.Mul(x, a)
  535. y.Mul(y, b)
  536. x.Add(x, y)
  537. return x.Cmp(d) == 0
  538. }
  539. var gcdTests = []struct {
  540. d, x, y, a, b string
  541. }{
  542. // a <= 0 || b <= 0
  543. {"0", "0", "0", "0", "0"},
  544. {"0", "0", "0", "0", "7"},
  545. {"0", "0", "0", "11", "0"},
  546. {"0", "0", "0", "-77", "35"},
  547. {"0", "0", "0", "64515", "-24310"},
  548. {"0", "0", "0", "-64515", "-24310"},
  549. {"1", "-9", "47", "120", "23"},
  550. {"7", "1", "-2", "77", "35"},
  551. {"935", "-3", "8", "64515", "24310"},
  552. {"935000000000000000", "-3", "8", "64515000000000000000", "24310000000000000000"},
  553. {"1", "-221", "22059940471369027483332068679400581064239780177629666810348940098015901108344", "98920366548084643601728869055592650835572950932266967461790948584315647051443", "991"},
  554. // test early exit (after one Euclidean iteration) in binaryGCD
  555. {"1", "", "", "1", "98920366548084643601728869055592650835572950932266967461790948584315647051443"},
  556. }
  557. func testGcd(t *testing.T, d, x, y, a, b *Int) {
  558. var X *Int
  559. if x != nil {
  560. X = new(Int)
  561. }
  562. var Y *Int
  563. if y != nil {
  564. Y = new(Int)
  565. }
  566. D := new(Int).GCD(X, Y, a, b)
  567. if D.Cmp(d) != 0 {
  568. t.Errorf("GCD(%s, %s): got d = %s, want %s", a, b, D, d)
  569. }
  570. if x != nil && X.Cmp(x) != 0 {
  571. t.Errorf("GCD(%s, %s): got x = %s, want %s", a, b, X, x)
  572. }
  573. if y != nil && Y.Cmp(y) != 0 {
  574. t.Errorf("GCD(%s, %s): got y = %s, want %s", a, b, Y, y)
  575. }
  576. // binaryGCD requires a > 0 && b > 0
  577. if a.Sign() <= 0 || b.Sign() <= 0 {
  578. return
  579. }
  580. D.binaryGCD(a, b)
  581. if D.Cmp(d) != 0 {
  582. t.Errorf("binaryGcd(%s, %s): got d = %s, want %s", a, b, D, d)
  583. }
  584. // check results in presence of aliasing (issue #11284)
  585. a2 := new(Int).Set(a)
  586. b2 := new(Int).Set(b)
  587. a2.binaryGCD(a2, b2) // result is same as 1st argument
  588. if a2.Cmp(d) != 0 {
  589. t.Errorf("binaryGcd(%s, %s): got d = %s, want %s", a, b, a2, d)
  590. }
  591. a2 = new(Int).Set(a)
  592. b2 = new(Int).Set(b)
  593. b2.binaryGCD(a2, b2) // result is same as 2nd argument
  594. if b2.Cmp(d) != 0 {
  595. t.Errorf("binaryGcd(%s, %s): got d = %s, want %s", a, b, b2, d)
  596. }
  597. }
  598. func TestGcd(t *testing.T) {
  599. for _, test := range gcdTests {
  600. d, _ := new(Int).SetString(test.d, 0)
  601. x, _ := new(Int).SetString(test.x, 0)
  602. y, _ := new(Int).SetString(test.y, 0)
  603. a, _ := new(Int).SetString(test.a, 0)
  604. b, _ := new(Int).SetString(test.b, 0)
  605. testGcd(t, d, nil, nil, a, b)
  606. testGcd(t, d, x, nil, a, b)
  607. testGcd(t, d, nil, y, a, b)
  608. testGcd(t, d, x, y, a, b)
  609. }
  610. quick.Check(checkGcd, nil)
  611. }
  612. var primes = []string{
  613. "2",
  614. "3",
  615. "5",
  616. "7",
  617. "11",
  618. "13756265695458089029",
  619. "13496181268022124907",
  620. "10953742525620032441",
  621. "17908251027575790097",
  622. // https://golang.org/issue/638
  623. "18699199384836356663",
  624. "98920366548084643601728869055592650835572950932266967461790948584315647051443",
  625. "94560208308847015747498523884063394671606671904944666360068158221458669711639",
  626. // http://primes.utm.edu/lists/small/small3.html
  627. "449417999055441493994709297093108513015373787049558499205492347871729927573118262811508386655998299074566974373711472560655026288668094291699357843464363003144674940345912431129144354948751003607115263071543163",
  628. "230975859993204150666423538988557839555560243929065415434980904258310530753006723857139742334640122533598517597674807096648905501653461687601339782814316124971547968912893214002992086353183070342498989426570593",
  629. "5521712099665906221540423207019333379125265462121169655563495403888449493493629943498064604536961775110765377745550377067893607246020694972959780839151452457728855382113555867743022746090187341871655890805971735385789993",
  630. "203956878356401977405765866929034577280193993314348263094772646453283062722701277632936616063144088173312372882677123879538709400158306567338328279154499698366071906766440037074217117805690872792848149112022286332144876183376326512083574821647933992961249917319836219304274280243803104015000563790123",
  631. // ECC primes: http://tools.ietf.org/html/draft-ladd-safecurves-02
  632. "3618502788666131106986593281521497120414687020801267626233049500247285301239", // Curve1174: 2^251-9
  633. "57896044618658097711785492504343953926634992332820282019728792003956564819949", // Curve25519: 2^255-19
  634. "9850501549098619803069760025035903451269934817616361666987073351061430442874302652853566563721228910201656997576599", // E-382: 2^382-105
  635. "42307582002575910332922579714097346549017899709713998034217522897561970639123926132812109468141778230245837569601494931472367", // Curve41417: 2^414-17
  636. "6864797660130609714981900799081393217269435300143305409394463459185543183397656052122559640661454554977296311391480858037121987999716643812574028291115057151", // E-521: 2^521-1
  637. }
  638. var composites = []string{
  639. "0",
  640. "1",
  641. "21284175091214687912771199898307297748211672914763848041968395774954376176754",
  642. "6084766654921918907427900243509372380954290099172559290432744450051395395951",
  643. "84594350493221918389213352992032324280367711247940675652888030554255915464401",
  644. "82793403787388584738507275144194252681",
  645. }
  646. func TestProbablyPrime(t *testing.T) {
  647. nreps := 20
  648. if testing.Short() {
  649. nreps = 1
  650. }
  651. for i, s := range primes {
  652. p, _ := new(Int).SetString(s, 10)
  653. if !p.ProbablyPrime(nreps) {
  654. t.Errorf("#%d prime found to be non-prime (%s)", i, s)
  655. }
  656. }
  657. for i, s := range composites {
  658. c, _ := new(Int).SetString(s, 10)
  659. if c.ProbablyPrime(nreps) {
  660. t.Errorf("#%d composite found to be prime (%s)", i, s)
  661. }
  662. if testing.Short() {
  663. break
  664. }
  665. }
  666. // check that ProbablyPrime panics if n <= 0
  667. c := NewInt(11) // a prime
  668. for _, n := range []int{-1, 0, 1} {
  669. func() {
  670. defer func() {
  671. if n <= 0 && recover() == nil {
  672. t.Fatalf("expected panic from ProbablyPrime(%d)", n)
  673. }
  674. }()
  675. if !c.ProbablyPrime(n) {
  676. t.Fatalf("%v should be a prime", c)
  677. }
  678. }()
  679. }
  680. }
  681. type intShiftTest struct {
  682. in string
  683. shift uint
  684. out string
  685. }
  686. var rshTests = []intShiftTest{
  687. {"0", 0, "0"},
  688. {"-0", 0, "0"},
  689. {"0", 1, "0"},
  690. {"0", 2, "0"},
  691. {"1", 0, "1"},
  692. {"1", 1, "0"},
  693. {"1", 2, "0"},
  694. {"2", 0, "2"},
  695. {"2", 1, "1"},
  696. {"-1", 0, "-1"},
  697. {"-1", 1, "-1"},
  698. {"-1", 10, "-1"},
  699. {"-100", 2, "-25"},
  700. {"-100", 3, "-13"},
  701. {"-100", 100, "-1"},
  702. {"4294967296", 0, "4294967296"},
  703. {"4294967296", 1, "2147483648"},
  704. {"4294967296", 2, "1073741824"},
  705. {"18446744073709551616", 0, "18446744073709551616"},
  706. {"18446744073709551616", 1, "9223372036854775808"},
  707. {"18446744073709551616", 2, "4611686018427387904"},
  708. {"18446744073709551616", 64, "1"},
  709. {"340282366920938463463374607431768211456", 64, "18446744073709551616"},
  710. {"340282366920938463463374607431768211456", 128, "1"},
  711. }
  712. func TestRsh(t *testing.T) {
  713. for i, test := range rshTests {
  714. in, _ := new(Int).SetString(test.in, 10)
  715. expected, _ := new(Int).SetString(test.out, 10)
  716. out := new(Int).Rsh(in, test.shift)
  717. if !isNormalized(out) {
  718. t.Errorf("#%d: %v is not normalized", i, *out)
  719. }
  720. if out.Cmp(expected) != 0 {
  721. t.Errorf("#%d: got %s want %s", i, out, expected)
  722. }
  723. }
  724. }
  725. func TestRshSelf(t *testing.T) {
  726. for i, test := range rshTests {
  727. z, _ := new(Int).SetString(test.in, 10)
  728. expected, _ := new(Int).SetString(test.out, 10)
  729. z.Rsh(z, test.shift)
  730. if !isNormalized(z) {
  731. t.Errorf("#%d: %v is not normalized", i, *z)
  732. }
  733. if z.Cmp(expected) != 0 {
  734. t.Errorf("#%d: got %s want %s", i, z, expected)
  735. }
  736. }
  737. }
  738. var lshTests = []intShiftTest{
  739. {"0", 0, "0"},
  740. {"0", 1, "0"},
  741. {"0", 2, "0"},
  742. {"1", 0, "1"},
  743. {"1", 1, "2"},
  744. {"1", 2, "4"},
  745. {"2", 0, "2"},
  746. {"2", 1, "4"},
  747. {"2", 2, "8"},
  748. {"-87", 1, "-174"},
  749. {"4294967296", 0, "4294967296"},
  750. {"4294967296", 1, "8589934592"},
  751. {"4294967296", 2, "17179869184"},
  752. {"18446744073709551616", 0, "18446744073709551616"},
  753. {"9223372036854775808", 1, "18446744073709551616"},
  754. {"4611686018427387904", 2, "18446744073709551616"},
  755. {"1", 64, "18446744073709551616"},
  756. {"18446744073709551616", 64, "340282366920938463463374607431768211456"},
  757. {"1", 128, "340282366920938463463374607431768211456"},
  758. }
  759. func TestLsh(t *testing.T) {
  760. for i, test := range lshTests {
  761. in, _ := new(Int).SetString(test.in, 10)
  762. expected, _ := new(Int).SetString(test.out, 10)
  763. out := new(Int).Lsh(in, test.shift)
  764. if !isNormalized(out) {
  765. t.Errorf("#%d: %v is not normalized", i, *out)
  766. }
  767. if out.Cmp(expected) != 0 {
  768. t.Errorf("#%d: got %s want %s", i, out, expected)
  769. }
  770. }
  771. }
  772. func TestLshSelf(t *testing.T) {
  773. for i, test := range lshTests {
  774. z, _ := new(Int).SetString(test.in, 10)
  775. expected, _ := new(Int).SetString(test.out, 10)
  776. z.Lsh(z, test.shift)
  777. if !isNormalized(z) {
  778. t.Errorf("#%d: %v is not normalized", i, *z)
  779. }
  780. if z.Cmp(expected) != 0 {
  781. t.Errorf("#%d: got %s want %s", i, z, expected)
  782. }
  783. }
  784. }
  785. func TestLshRsh(t *testing.T) {
  786. for i, test := range rshTests {
  787. in, _ := new(Int).SetString(test.in, 10)
  788. out := new(Int).Lsh(in, test.shift)
  789. out = out.Rsh(out, test.shift)
  790. if !isNormalized(out) {
  791. t.Errorf("#%d: %v is not normalized", i, *out)
  792. }
  793. if in.Cmp(out) != 0 {
  794. t.Errorf("#%d: got %s want %s", i, out, in)
  795. }
  796. }
  797. for i, test := range lshTests {
  798. in, _ := new(Int).SetString(test.in, 10)
  799. out := new(Int).Lsh(in, test.shift)
  800. out.Rsh(out, test.shift)
  801. if !isNormalized(out) {
  802. t.Errorf("#%d: %v is not normalized", i, *out)
  803. }
  804. if in.Cmp(out) != 0 {
  805. t.Errorf("#%d: got %s want %s", i, out, in)
  806. }
  807. }
  808. }
  809. var int64Tests = []int64{
  810. 0,
  811. 1,
  812. -1,
  813. 4294967295,
  814. -4294967295,
  815. 4294967296,
  816. -4294967296,
  817. 9223372036854775807,
  818. -9223372036854775807,
  819. -9223372036854775808,
  820. }
  821. func TestInt64(t *testing.T) {
  822. for i, testVal := range int64Tests {
  823. in := NewInt(testVal)
  824. out := in.Int64()
  825. if out != testVal {
  826. t.Errorf("#%d got %d want %d", i, out, testVal)
  827. }
  828. }
  829. }
  830. var uint64Tests = []uint64{
  831. 0,
  832. 1,
  833. 4294967295,
  834. 4294967296,
  835. 8589934591,
  836. 8589934592,
  837. 9223372036854775807,
  838. 9223372036854775808,
  839. 18446744073709551615, // 1<<64 - 1
  840. }
  841. func TestUint64(t *testing.T) {
  842. in := new(Int)
  843. for i, testVal := range uint64Tests {
  844. in.SetUint64(testVal)
  845. out := in.Uint64()
  846. if out != testVal {
  847. t.Errorf("#%d got %d want %d", i, out, testVal)
  848. }
  849. str := fmt.Sprint(testVal)
  850. strOut := in.String()
  851. if strOut != str {
  852. t.Errorf("#%d.String got %s want %s", i, strOut, str)
  853. }
  854. }
  855. }
  856. var bitwiseTests = []struct {
  857. x, y string
  858. and, or, xor, andNot string
  859. }{
  860. {"0x00", "0x00", "0x00", "0x00", "0x00", "0x00"},
  861. {"0x00", "0x01", "0x00", "0x01", "0x01", "0x00"},
  862. {"0x01", "0x00", "0x00", "0x01", "0x01", "0x01"},
  863. {"-0x01", "0x00", "0x00", "-0x01", "-0x01", "-0x01"},
  864. {"-0xaf", "-0x50", "-0xf0", "-0x0f", "0xe1", "0x41"},
  865. {"0x00", "-0x01", "0x00", "-0x01", "-0x01", "0x00"},
  866. {"0x01", "0x01", "0x01", "0x01", "0x00", "0x00"},
  867. {"-0x01", "-0x01", "-0x01", "-0x01", "0x00", "0x00"},
  868. {"0x07", "0x08", "0x00", "0x0f", "0x0f", "0x07"},
  869. {"0x05", "0x0f", "0x05", "0x0f", "0x0a", "0x00"},
  870. {"0xff", "-0x0a", "0xf6", "-0x01", "-0xf7", "0x09"},
  871. {"0x013ff6", "0x9a4e", "0x1a46", "0x01bffe", "0x01a5b8", "0x0125b0"},
  872. {"-0x013ff6", "0x9a4e", "0x800a", "-0x0125b2", "-0x01a5bc", "-0x01c000"},
  873. {"-0x013ff6", "-0x9a4e", "-0x01bffe", "-0x1a46", "0x01a5b8", "0x8008"},
  874. {
  875. "0x1000009dc6e3d9822cba04129bcbe3401",
  876. "0xb9bd7d543685789d57cb918e833af352559021483cdb05cc21fd",
  877. "0x1000001186210100001000009048c2001",
  878. "0xb9bd7d543685789d57cb918e8bfeff7fddb2ebe87dfbbdfe35fd",
  879. "0xb9bd7d543685789d57ca918e8ae69d6fcdb2eae87df2b97215fc",
  880. "0x8c40c2d8822caa04120b8321400",
  881. },
  882. {
  883. "0x1000009dc6e3d9822cba04129bcbe3401",
  884. "-0xb9bd7d543685789d57cb918e833af352559021483cdb05cc21fd",
  885. "0x8c40c2d8822caa04120b8321401",
  886. "-0xb9bd7d543685789d57ca918e82229142459020483cd2014001fd",
  887. "-0xb9bd7d543685789d57ca918e8ae69d6fcdb2eae87df2b97215fe",
  888. "0x1000001186210100001000009048c2000",
  889. },
  890. {
  891. "-0x1000009dc6e3d9822cba04129bcbe3401",
  892. "-0xb9bd7d543685789d57cb918e833af352559021483cdb05cc21fd",
  893. "-0xb9bd7d543685789d57cb918e8bfeff7fddb2ebe87dfbbdfe35fd",
  894. "-0x1000001186210100001000009048c2001",
  895. "0xb9bd7d543685789d57ca918e8ae69d6fcdb2eae87df2b97215fc",
  896. "0xb9bd7d543685789d57ca918e82229142459020483cd2014001fc",
  897. },
  898. }
  899. type bitFun func(z, x, y *Int) *Int
  900. func testBitFun(t *testing.T, msg string, f bitFun, x, y *Int, exp string) {
  901. expected := new(Int)
  902. expected.SetString(exp, 0)
  903. out := f(new(Int), x, y)
  904. if out.Cmp(expected) != 0 {
  905. t.Errorf("%s: got %s want %s", msg, out, expected)
  906. }
  907. }
  908. func testBitFunSelf(t *testing.T, msg string, f bitFun, x, y *Int, exp string) {
  909. self := new(Int)
  910. self.Set(x)
  911. expected := new(Int)
  912. expected.SetString(exp, 0)
  913. self = f(self, self, y)
  914. if self.Cmp(expected) != 0 {
  915. t.Errorf("%s: got %s want %s", msg, self, expected)
  916. }
  917. }
  918. func altBit(x *Int, i int) uint {
  919. z := new(Int).Rsh(x, uint(i))
  920. z = z.And(z, NewInt(1))
  921. if z.Cmp(new(Int)) != 0 {
  922. return 1
  923. }
  924. return 0
  925. }
  926. func altSetBit(z *Int, x *Int, i int, b uint) *Int {
  927. one := NewInt(1)
  928. m := one.Lsh(one, uint(i))
  929. switch b {
  930. case 1:
  931. return z.Or(x, m)
  932. case 0:
  933. return z.AndNot(x, m)
  934. }
  935. panic("set bit is not 0 or 1")
  936. }
  937. func testBitset(t *testing.T, x *Int) {
  938. n := x.BitLen()
  939. z := new(Int).Set(x)
  940. z1 := new(Int).Set(x)
  941. for i := 0; i < n+10; i++ {
  942. old := z.Bit(i)
  943. old1 := altBit(z1, i)
  944. if old != old1 {
  945. t.Errorf("bitset: inconsistent value for Bit(%s, %d), got %v want %v", z1, i, old, old1)
  946. }
  947. z := new(Int).SetBit(z, i, 1)
  948. z1 := altSetBit(new(Int), z1, i, 1)
  949. if z.Bit(i) == 0 {
  950. t.Errorf("bitset: bit %d of %s got 0 want 1", i, x)
  951. }
  952. if z.Cmp(z1) != 0 {
  953. t.Errorf("bitset: inconsistent value after SetBit 1, got %s want %s", z, z1)
  954. }
  955. z.SetBit(z, i, 0)
  956. altSetBit(z1, z1, i, 0)
  957. if z.Bit(i) != 0 {
  958. t.Errorf("bitset: bit %d of %s got 1 want 0", i, x)
  959. }
  960. if z.Cmp(z1) != 0 {
  961. t.Errorf("bitset: inconsistent value after SetBit 0, got %s want %s", z, z1)
  962. }
  963. altSetBit(z1, z1, i, old)
  964. z.SetBit(z, i, old)
  965. if z.Cmp(z1) != 0 {
  966. t.Errorf("bitset: inconsistent value after SetBit old, got %s want %s", z, z1)
  967. }
  968. }
  969. if z.Cmp(x) != 0 {
  970. t.Errorf("bitset: got %s want %s", z, x)
  971. }
  972. }
  973. var bitsetTests = []struct {
  974. x string
  975. i int
  976. b uint
  977. }{
  978. {"0", 0, 0},
  979. {"0", 200, 0},
  980. {"1", 0, 1},
  981. {"1", 1, 0},
  982. {"-1", 0, 1},
  983. {"-1", 200, 1},
  984. {"0x2000000000000000000000000000", 108, 0},
  985. {"0x2000000000000000000000000000", 109, 1},
  986. {"0x2000000000000000000000000000", 110, 0},
  987. {"-0x2000000000000000000000000001", 108, 1},
  988. {"-0x2000000000000000000000000001", 109, 0},
  989. {"-0x2000000000000000000000000001", 110, 1},
  990. }
  991. func TestBitSet(t *testing.T) {
  992. for _, test := range bitwiseTests {
  993. x := new(Int)
  994. x.SetString(test.x, 0)
  995. testBitset(t, x)
  996. x = new(Int)
  997. x.SetString(test.y, 0)
  998. testBitset(t, x)
  999. }
  1000. for i, test := range bitsetTests {
  1001. x := new(Int)
  1002. x.SetString(test.x, 0)
  1003. b := x.Bit(test.i)
  1004. if b != test.b {
  1005. t.Errorf("#%d got %v want %v", i, b, test.b)
  1006. }
  1007. }
  1008. z := NewInt(1)
  1009. z.SetBit(NewInt(0), 2, 1)
  1010. if z.Cmp(NewInt(4)) != 0 {
  1011. t.Errorf("destination leaked into result; got %s want 4", z)
  1012. }
  1013. }
  1014. func BenchmarkBitset(b *testing.B) {
  1015. z := new(Int)
  1016. z.SetBit(z, 512, 1)
  1017. b.ResetTimer()
  1018. b.StartTimer()
  1019. for i := b.N - 1; i >= 0; i-- {
  1020. z.SetBit(z, i&512, 1)
  1021. }
  1022. }
  1023. func BenchmarkBitsetNeg(b *testing.B) {
  1024. z := NewInt(-1)
  1025. z.SetBit(z, 512, 0)
  1026. b.ResetTimer()
  1027. b.StartTimer()
  1028. for i := b.N - 1; i >= 0; i-- {
  1029. z.SetBit(z, i&512, 0)
  1030. }
  1031. }
  1032. func BenchmarkBitsetOrig(b *testing.B) {
  1033. z := new(Int)
  1034. altSetBit(z, z, 512, 1)
  1035. b.ResetTimer()
  1036. b.StartTimer()
  1037. for i := b.N - 1; i >= 0; i-- {
  1038. altSetBit(z, z, i&512, 1)
  1039. }
  1040. }
  1041. func BenchmarkBitsetNegOrig(b *testing.B) {
  1042. z := NewInt(-1)
  1043. altSetBit(z, z, 512, 0)
  1044. b.ResetTimer()
  1045. b.StartTimer()
  1046. for i := b.N - 1; i >= 0; i-- {
  1047. altSetBit(z, z, i&512, 0)
  1048. }
  1049. }
  1050. func TestBitwise(t *testing.T) {
  1051. x := new(Int)
  1052. y := new(Int)
  1053. for _, test := range bitwiseTests {
  1054. x.SetString(test.x, 0)
  1055. y.SetString(test.y, 0)
  1056. testBitFun(t, "and", (*Int).And, x, y, test.and)
  1057. testBitFunSelf(t, "and", (*Int).And, x, y, test.and)
  1058. testBitFun(t, "andNot", (*Int).AndNot, x, y, test.andNot)
  1059. testBitFunSelf(t, "andNot", (*Int).AndNot, x, y, test.andNot)
  1060. testBitFun(t, "or", (*Int).Or, x, y, test.or)
  1061. testBitFunSelf(t, "or", (*Int).Or, x, y, test.or)
  1062. testBitFun(t, "xor", (*Int).Xor, x, y, test.xor)
  1063. testBitFunSelf(t, "xor", (*Int).Xor, x, y, test.xor)
  1064. }
  1065. }
  1066. var notTests = []struct {
  1067. in string
  1068. out string
  1069. }{
  1070. {"0", "-1"},
  1071. {"1", "-2"},
  1072. {"7", "-8"},
  1073. {"0", "-1"},
  1074. {"-81910", "81909"},
  1075. {
  1076. "298472983472983471903246121093472394872319615612417471234712061",
  1077. "-298472983472983471903246121093472394872319615612417471234712062",
  1078. },
  1079. }
  1080. func TestNot(t *testing.T) {
  1081. in := new(Int)
  1082. out := new(Int)
  1083. expected := new(Int)
  1084. for i, test := range notTests {
  1085. in.SetString(test.in, 10)
  1086. expected.SetString(test.out, 10)
  1087. out = out.Not(in)
  1088. if out.Cmp(expected) != 0 {
  1089. t.Errorf("#%d: got %s want %s", i, out, expected)
  1090. }
  1091. out = out.Not(out)
  1092. if out.Cmp(in) != 0 {
  1093. t.Errorf("#%d: got %s want %s", i, out, in)
  1094. }
  1095. }
  1096. }
  1097. var modInverseTests = []struct {
  1098. element string
  1099. modulus string
  1100. }{
  1101. {"1234567", "458948883992"},
  1102. {"239487239847", "2410312426921032588552076022197566074856950548502459942654116941958108831682612228890093858261341614673227141477904012196503648957050582631942730706805009223062734745341073406696246014589361659774041027169249453200378729434170325843778659198143763193776859869524088940195577346119843545301547043747207749969763750084308926339295559968882457872412993810129130294592999947926365264059284647209730384947211681434464714438488520940127459844288859336526896320919633919"},
  1103. }
  1104. func TestModInverse(t *testing.T) {
  1105. var element, modulus, gcd, inverse Int
  1106. one := NewInt(1)
  1107. for i, test := range modInverseTests {
  1108. (&element).SetString(test.element, 10)
  1109. (&modulus).SetString(test.modulus, 10)
  1110. (&inverse).ModInverse(&element, &modulus)
  1111. (&inverse).Mul(&inverse, &element)
  1112. (&inverse).Mod(&inverse, &modulus)
  1113. if (&inverse).Cmp(one) != 0 {
  1114. t.Errorf("#%d: failed (e·e^(-1)=%s)", i, &inverse)
  1115. }
  1116. }
  1117. // exhaustive test for small values
  1118. for n := 2; n < 100; n++ {
  1119. (&modulus).SetInt64(int64(n))
  1120. for x := 1; x < n; x++ {
  1121. (&element).SetInt64(int64(x))
  1122. (&gcd).GCD(nil, nil, &element, &modulus)
  1123. if (&gcd).Cmp(one) != 0 {
  1124. continue
  1125. }
  1126. (&inverse).ModInverse(&element, &modulus)
  1127. (&inverse).Mul(&inverse, &element)
  1128. (&inverse).Mod(&inverse, &modulus)
  1129. if (&inverse).Cmp(one) != 0 {
  1130. t.Errorf("ModInverse(%d,%d)*%d%%%d=%d, not 1", &element, &modulus, &element, &modulus, &inverse)
  1131. }
  1132. }
  1133. }
  1134. }
  1135. // testModSqrt is a helper for TestModSqrt,
  1136. // which checks that ModSqrt can compute a square-root of elt^2.
  1137. func testModSqrt(t *testing.T, elt, mod, sq, sqrt *Int) bool {
  1138. var sqChk, sqrtChk, sqrtsq Int
  1139. sq.Mul(elt, elt)
  1140. sq.Mod(sq, mod)
  1141. z := sqrt.ModSqrt(sq, mod)
  1142. if z != sqrt {
  1143. t.Errorf("ModSqrt returned wrong value %s", z)
  1144. }
  1145. // test ModSqrt arguments outside the range [0,mod)
  1146. sqChk.Add(sq, mod)
  1147. z = sqrtChk.ModSqrt(&sqChk, mod)
  1148. if z != &sqrtChk || z.Cmp(sqrt) != 0 {
  1149. t.Errorf("ModSqrt returned inconsistent value %s", z)
  1150. }
  1151. sqChk.Sub(sq, mod)
  1152. z = sqrtChk.ModSqrt(&sqChk, mod)
  1153. if z != &sqrtChk || z.Cmp(sqrt) != 0 {
  1154. t.Errorf("ModSqrt returned inconsistent value %s", z)
  1155. }
  1156. // make sure we actually got a square root
  1157. if sqrt.Cmp(elt) == 0 {
  1158. return true // we found the "desired" square root
  1159. }
  1160. sqrtsq.Mul(sqrt, sqrt) // make sure we found the "other" one
  1161. sqrtsq.Mod(&sqrtsq, mod)
  1162. return sq.Cmp(&sqrtsq) == 0
  1163. }
  1164. func TestModSqrt(t *testing.T) {
  1165. var elt, mod, modx4, sq, sqrt Int
  1166. r := rand.New(rand.NewSource(9))
  1167. for i, s := range primes[1:] { // skip 2, use only odd primes
  1168. mod.SetString(s, 10)
  1169. modx4.Lsh(&mod, 2)
  1170. // test a few random elements per prime
  1171. for x := 1; x < 5; x++ {
  1172. elt.Rand(r, &modx4)
  1173. elt.Sub(&elt, &mod) // test range [-mod, 3*mod)
  1174. if !testModSqrt(t, &elt, &mod, &sq, &sqrt) {
  1175. t.Errorf("#%d: failed (sqrt(e) = %s)", i, &sqrt)
  1176. }
  1177. }
  1178. }
  1179. // exhaustive test for small values
  1180. for n := 3; n < 100; n++ {
  1181. mod.SetInt64(int64(n))
  1182. if !mod.ProbablyPrime(10) {
  1183. continue
  1184. }
  1185. isSquare := make([]bool, n)
  1186. // test all the squares
  1187. for x := 1; x < n; x++ {
  1188. elt.SetInt64(int64(x))
  1189. if !testModSqrt(t, &elt, &mod, &sq, &sqrt) {
  1190. t.Errorf("#%d: failed (sqrt(%d,%d) = %s)", x, &elt, &mod, &sqrt)
  1191. }
  1192. isSquare[sq.Uint64()] = true
  1193. }
  1194. // test all non-squares
  1195. for x := 1; x < n; x++ {
  1196. sq.SetInt64(int64(x))
  1197. z := sqrt.ModSqrt(&sq, &mod)
  1198. if !isSquare[x] && z != nil {
  1199. t.Errorf("#%d: failed (sqrt(%d,%d) = nil)", x, &sqrt, &mod)
  1200. }
  1201. }
  1202. }
  1203. }
  1204. func TestJacobi(t *testing.T) {
  1205. testCases := []struct {
  1206. x, y int64
  1207. result int
  1208. }{
  1209. {0, 1, 1},
  1210. {0, -1, 1},
  1211. {1, 1, 1},
  1212. {1, -1, 1},
  1213. {0, 5, 0},
  1214. {1, 5, 1},
  1215. {2, 5, -1},
  1216. {-2, 5, -1},
  1217. {2, -5, -1},
  1218. {-2, -5, 1},
  1219. {3, 5, -1},
  1220. {5, 5, 0},
  1221. {-5, 5, 0},
  1222. {6, 5, 1},
  1223. {6, -5, 1},
  1224. {-6, 5, 1},
  1225. {-6, -5, -1},
  1226. }
  1227. var x, y Int
  1228. for i, test := range testCases {
  1229. x.SetInt64(test.x)
  1230. y.SetInt64(test.y)
  1231. expected := test.result
  1232. actual := Jacobi(&x, &y)
  1233. if actual != expected {
  1234. t.Errorf("#%d: Jacobi(%d, %d) = %d, but expected %d", i, test.x, test.y, actual, expected)
  1235. }
  1236. }
  1237. }
  1238. func TestJacobiPanic(t *testing.T) {
  1239. const failureMsg = "test failure"
  1240. defer func() {
  1241. msg := recover()
  1242. if msg == nil || msg == failureMsg {
  1243. panic(msg)
  1244. }
  1245. t.Log(msg)
  1246. }()
  1247. x := NewInt(1)
  1248. y := NewInt(2)
  1249. // Jacobi should panic when the second argument is even.
  1250. Jacobi(x, y)
  1251. panic(failureMsg)
  1252. }
  1253. var encodingTests = []string{
  1254. "-539345864568634858364538753846587364875430589374589",
  1255. "-678645873",
  1256. "-100",
  1257. "-2",
  1258. "-1",
  1259. "0",
  1260. "1",
  1261. "2",
  1262. "10",
  1263. "42",
  1264. "1234567890",
  1265. "298472983472983471903246121093472394872319615612417471234712061",
  1266. }
  1267. func TestIntGobEncoding(t *testing.T) {
  1268. var medium bytes.Buffer
  1269. enc := gob.NewEncoder(&medium)
  1270. dec := gob.NewDecoder(&medium)
  1271. for _, test := range encodingTests {
  1272. medium.Reset() // empty buffer for each test case (in case of failures)
  1273. var tx Int
  1274. tx.SetString(test, 10)
  1275. if err := enc.Encode(&tx); err != nil {
  1276. t.Errorf("encoding of %s failed: %s", &tx, err)
  1277. }
  1278. var rx Int
  1279. if err := dec.Decode(&rx); err != nil {
  1280. t.Errorf("decoding of %s failed: %s", &tx, err)
  1281. }
  1282. if rx.Cmp(&tx) != 0 {
  1283. t.Errorf("transmission of %s failed: got %s want %s", &tx, &rx, &tx)
  1284. }
  1285. }
  1286. }
  1287. // Sending a nil Int pointer (inside a slice) on a round trip through gob should yield a zero.
  1288. // TODO: top-level nils.
  1289. func TestGobEncodingNilIntInSlice(t *testing.T) {
  1290. buf := new(bytes.Buffer)
  1291. enc := gob.NewEncoder(buf)
  1292. dec := gob.NewDecoder(buf)
  1293. var in = make([]*Int, 1)
  1294. err := enc.Encode(&in)
  1295. if err != nil {
  1296. t.Errorf("gob encode failed: %q", err)
  1297. }
  1298. var out []*Int
  1299. err = dec.Decode(&out)
  1300. if err != nil {
  1301. t.Fatalf("gob decode failed: %q", err)
  1302. }
  1303. if len(out) != 1 {
  1304. t.Fatalf("wrong len; want 1 got %d", len(out))
  1305. }
  1306. var zero Int
  1307. if out[0].Cmp(&zero) != 0 {
  1308. t.Errorf("transmission of (*Int)(nill) failed: got %s want 0", out)
  1309. }
  1310. }
  1311. func TestIntJSONEncoding(t *testing.T) {
  1312. for _, test := range encodingTests {
  1313. var tx Int
  1314. tx.SetString(test, 10)
  1315. b, err := json.Marshal(&tx)
  1316. if err != nil {
  1317. t.Errorf("marshaling of %s failed: %s", &tx, err)
  1318. }
  1319. var rx Int
  1320. if err := json.Unmarshal(b, &rx); err != nil {
  1321. t.Errorf("unmarshaling of %s failed: %s", &tx, err)
  1322. }
  1323. if rx.Cmp(&tx) != 0 {
  1324. t.Errorf("JSON encoding of %s failed: got %s want %s", &tx, &rx, &tx)
  1325. }
  1326. }
  1327. }
  1328. var intVals = []string{
  1329. "-141592653589793238462643383279502884197169399375105820974944592307816406286",
  1330. "-1415926535897932384626433832795028841971",
  1331. "-141592653589793",
  1332. "-1",
  1333. "0",
  1334. "1",
  1335. "141592653589793",
  1336. "1415926535897932384626433832795028841971",
  1337. "141592653589793238462643383279502884197169399375105820974944592307816406286",
  1338. }
  1339. func TestIntJSONEncodingTextMarshaller(t *testing.T) {
  1340. for _, num := range intVals {
  1341. var tx Int
  1342. tx.SetString(num, 0)
  1343. b, err := json.Marshal(&tx)
  1344. if err != nil {
  1345. t.Errorf("marshaling of %s failed: %s", &tx, err)
  1346. continue
  1347. }
  1348. var rx Int
  1349. if err := json.Unmarshal(b, &rx); err != nil {
  1350. t.Errorf("unmarshaling of %s failed: %s", &tx, err)
  1351. continue
  1352. }
  1353. if rx.Cmp(&tx) != 0 {
  1354. t.Errorf("JSON encoding of %s failed: got %s want %s", &tx, &rx, &tx)
  1355. }
  1356. }
  1357. }
  1358. func TestIntXMLEncodingTextMarshaller(t *testing.T) {
  1359. for _, num := range intVals {
  1360. var tx Int
  1361. tx.SetString(num, 0)
  1362. b, err := xml.Marshal(&tx)
  1363. if err != nil {
  1364. t.Errorf("marshaling of %s failed: %s", &tx, err)
  1365. continue
  1366. }
  1367. var rx Int
  1368. if err := xml.Unmarshal(b, &rx); err != nil {
  1369. t.Errorf("unmarshaling of %s failed: %s", &tx, err)
  1370. continue
  1371. }
  1372. if rx.Cmp(&tx) != 0 {
  1373. t.Errorf("XML encoding of %s failed: got %s want %s", &tx, &rx, &tx)
  1374. }
  1375. }
  1376. }
  1377. func TestIssue2607(t *testing.T) {
  1378. // This code sequence used to hang.
  1379. n := NewInt(10)
  1380. n.Rand(rand.New(rand.NewSource(9)), n)
  1381. }