prime.odin 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426
  1. /*
  2. Copyright 2021 Jeroen van Rijn <[email protected]>.
  3. Made available under Odin's BSD-3 license.
  4. An arbitrary precision mathematics implementation in Odin.
  5. For the theoretical underpinnings, see Knuth's The Art of Computer Programming, Volume 2, section 4.3.
  6. The code started out as an idiomatic source port of libTomMath, which is in the public domain, with thanks.
  7. This file contains prime finding operations.
  8. */
  9. package math_big
  10. /*
  11. Determines if an Integer is divisible by one of the _PRIME_TABLE primes.
  12. Returns true if it is, false if not.
  13. */
  14. internal_int_prime_is_divisible :: proc(a: ^Int, allocator := context.allocator) -> (res: bool, err: Error) {
  15. assert_if_nil(a)
  16. context.allocator = allocator
  17. internal_clear_if_uninitialized(a) or_return
  18. for prime in _private_prime_table {
  19. rem := #force_inline int_mod_digit(a, prime) or_return
  20. if rem == 0 {
  21. return true, nil
  22. }
  23. }
  24. /*
  25. Default to not divisible.
  26. */
  27. return false, nil
  28. }
  29. /*
  30. This is a shell function that calls either the normal or Montgomery exptmod functions.
  31. Originally the call to the Montgomery code was embedded in the normal function but that
  32. wasted alot of stack space for nothing (since 99% of the time the Montgomery code would be called).
  33. Computes res == G**X mod P.
  34. Assumes `res`, `G`, `X` and `P` to not be `nil` and for `G`, `X` and `P` to have been initialized.
  35. */
  36. internal_int_power_modulo :: proc(res, G, X, P: ^Int, allocator := context.allocator) -> (err: Error) {
  37. context.allocator = allocator
  38. dr: int
  39. /*
  40. Modulus P must be positive.
  41. */
  42. if internal_is_negative(P) { return .Invalid_Argument }
  43. /*
  44. If exponent X is negative we have to recurse.
  45. */
  46. if internal_is_negative(X) {
  47. tmpG, tmpX := &Int{}, &Int{}
  48. defer internal_destroy(tmpG, tmpX)
  49. internal_init_multi(tmpG, tmpX) or_return
  50. /*
  51. First compute 1/G mod P.
  52. */
  53. internal_invmod(tmpG, G, P) or_return
  54. /*
  55. now get |X|.
  56. */
  57. internal_abs(tmpX, X) or_return
  58. /*
  59. And now compute (1/G)**|X| instead of G**X [X < 0].
  60. */
  61. return internal_int_exponent_mod(res, tmpG, tmpX, P)
  62. }
  63. /*
  64. Modified diminished radix reduction.
  65. */
  66. can_reduce_2k_l := _private_int_reduce_is_2k_l(P) or_return
  67. if can_reduce_2k_l {
  68. return _private_int_exponent_mod(res, G, X, P, 1)
  69. }
  70. /*
  71. Is it a DR modulus? default to no.
  72. */
  73. dr = 1 if _private_dr_is_modulus(P) else 0
  74. /*
  75. If not, is it a unrestricted DR modulus?
  76. */
  77. if dr == 0 {
  78. reduce_is_2k := _private_int_reduce_is_2k(P) or_return
  79. dr = 2 if reduce_is_2k else 0
  80. }
  81. /*
  82. If the modulus is odd or dr != 0 use the montgomery method.
  83. */
  84. if internal_int_is_odd(P) || dr != 0 {
  85. return _private_int_exponent_mod(res, G, X, P, dr)
  86. }
  87. /*
  88. Otherwise use the generic Barrett reduction technique.
  89. */
  90. return _private_int_exponent_mod(res, G, X, P, 0)
  91. }
  92. internal_int_exponent_mod :: internal_int_power_modulo
  93. internal_int_powmod :: internal_int_power_modulo
  94. internal_powmod :: proc { internal_int_power_modulo, }
  95. /*
  96. Kronecker/Legendre symbol (a|p)
  97. Straightforward implementation of algorithm 1.4.10 in
  98. Henri Cohen: "A Course in Computational Algebraic Number Theory"
  99. @book{cohen2013course,
  100. title={A course in computational algebraic number theory},
  101. author={Cohen, Henri},
  102. volume={138},
  103. year={2013},
  104. publisher={Springer Science \& Business Media}
  105. }
  106. Assumes `a` and `p` to not be `nil` and to have been initialized.
  107. */
  108. internal_int_kronecker :: proc(a, p: ^Int, allocator := context.allocator) -> (kronecker: int, err: Error) {
  109. context.allocator = allocator
  110. a1, p1, r := &Int{}, &Int{}, &Int{}
  111. defer internal_destroy(a1, p1, r)
  112. table := []int{0, 1, 0, -1, 0, -1, 0, 1}
  113. if internal_int_is_zero(p) {
  114. if a.used == 1 && a.digit[0] == 1 {
  115. return 1, nil
  116. } else {
  117. return 0, nil
  118. }
  119. }
  120. if internal_is_even(a) && internal_is_even(p) {
  121. return 0, nil
  122. }
  123. internal_copy(a1, a) or_return
  124. internal_copy(p1, p) or_return
  125. v := internal_count_lsb(p1) or_return
  126. internal_shr(p1, p1, v) or_return
  127. k := 1 if v & 1 == 0 else table[a.digit[0] & 7]
  128. if internal_is_negative(p1) {
  129. p1.sign = .Zero_or_Positive
  130. if internal_is_negative(a1) {
  131. k = -k
  132. }
  133. }
  134. internal_zero(r) or_return
  135. for {
  136. if internal_is_zero(a1) {
  137. if internal_eq(p1, 1) {
  138. return k, nil
  139. } else {
  140. return 0, nil
  141. }
  142. }
  143. v = internal_count_lsb(a1) or_return
  144. internal_shr(a1, a1, v) or_return
  145. if v & 1 == 1 {
  146. k = k * table[p1.digit[0] & 7]
  147. }
  148. if internal_is_negative(a1) {
  149. /*
  150. Compute k = (-1)^((a1)*(p1-1)/4) * k.
  151. a1.digit[0] + 1 cannot overflow because the MSB
  152. of the DIGIT type is not set by definition.
  153. */
  154. if ((a1.digit[0] + 1) & p1.digit[0] & 2) != 0 {
  155. k = -k
  156. }
  157. } else {
  158. /*
  159. Compute k = (-1)^((a1-1)*(p1-1)/4) * k.
  160. */
  161. if (a1.digit[0] & p1.digit[0] & 2) != 0 {
  162. k = -k
  163. }
  164. }
  165. internal_copy(r, a1) or_return
  166. r.sign = .Zero_or_Positive
  167. internal_mod(a1, p1, r) or_return
  168. internal_copy(p1, r) or_return
  169. }
  170. return
  171. }
  172. internal_int_legendre :: internal_int_kronecker
  173. /*
  174. Miller-Rabin test of "a" to the base of "b" as described in HAC pp. 139 Algorithm 4.24.
  175. Sets result to `false` if definitely composite or `true` if probably prime.
  176. Randomly the chance of error is no more than 1/4 and often very much lower.
  177. Assumes `a` and `b` not to be `nil` and to have been initialized.
  178. */
  179. internal_int_prime_miller_rabin :: proc(a, b: ^Int, allocator := context.allocator) -> (probably_prime: bool, err: Error) {
  180. context.allocator = allocator
  181. n1, y, r := &Int{}, &Int{}, &Int{}
  182. defer internal_destroy(n1, y, r)
  183. /*
  184. Ensure `b` > 1.
  185. */
  186. if internal_lte(b, 1) { return false, nil }
  187. /*
  188. Get `n1` = `a` - 1.
  189. */
  190. internal_copy(n1, a) or_return
  191. internal_sub(n1, n1, 1) or_return
  192. /*
  193. Set `2`**`s` * `r` = `n1`
  194. */
  195. internal_copy(r, n1) or_return
  196. /*
  197. Count the number of least significant bits which are zero.
  198. */
  199. s := internal_count_lsb(r) or_return
  200. /*
  201. Now divide `n` - 1 by `2`**`s`.
  202. */
  203. internal_shr(r, r, s) or_return
  204. /*
  205. Compute `y` = `b`**`r` mod `a`.
  206. */
  207. internal_int_exponent_mod(y, b, r, a) or_return
  208. /*
  209. If `y` != 1 and `y` != `n1` do.
  210. */
  211. if !internal_eq(y, 1) && !internal_eq(y, n1) {
  212. j := 1
  213. /*
  214. While `j` <= `s` - 1 and `y` != `n1`.
  215. */
  216. for j <= (s - 1) && !internal_eq(y, n1) {
  217. internal_sqrmod(y, y, a) or_return
  218. /*
  219. If `y` == 1 then composite.
  220. */
  221. if internal_eq(y, 1) {
  222. return false, nil
  223. }
  224. j += 1
  225. }
  226. /*
  227. If `y` != `n1` then composite.
  228. */
  229. if !internal_eq(y, n1) {
  230. return false, nil
  231. }
  232. }
  233. /*
  234. Probably prime now.
  235. */
  236. return true, nil
  237. }
  238. /*
  239. `a` is the big Int to test for primality.
  240. `miller_rabin_trials` can be one of the following:
  241. `< 0`: For `a` up to 3_317_044_064_679_887_385_961_981, set `miller_rabin_trials` to negative to run a predetermined
  242. number of trials for a deterministic answer.
  243. `= 0`: Run Miller-Rabin with bases 2, 3 and one random base < `a`. Non-deterministic.
  244. `> 0`: Run Miller-Rabin with bases 2, 3 and `miller_rabin_trials` number of random bases. Non-deterministic.
  245. `miller_rabin_only`:
  246. `false` Also use either Frobenius-Underwood or Lucas-Selfridge, depending on the compile-time `MATH_BIG_USE_FROBENIUS_TEST` choice.
  247. `true` Run Rabin-Miller trials but skip Frobenius-Underwood / Lucas-Selfridge.
  248. `r` takes a pointer to an instance of `core:math/rand`'s `Rand` and may be `nil` to use the global one.
  249. Returns `is_prime` (bool), where:
  250. `false` Definitively composite.
  251. `true` Probably prime if `miller_rabin_trials` >= 0, with increasing certainty with more trials.
  252. Deterministically prime if `miller_rabin_trials` = 0 for `a` up to 3_317_044_064_679_887_385_961_981.
  253. Assumes `a` not to be `nil` and to have been initialized.
  254. */
  255. internal_int_is_prime :: proc(a: ^Int, miller_rabin_trials := int(-1), miller_rabin_only := USE_MILLER_RABIN_ONLY, allocator := context.allocator) -> (is_prime: bool, err: Error) {
  256. context.allocator = allocator
  257. miller_rabin_trials := miller_rabin_trials
  258. // Default to `no`.
  259. is_prime = false
  260. b, res := &Int{}, &Int{}
  261. defer internal_destroy(b, res)
  262. // Some shortcuts
  263. // `N` > 3
  264. if a.used == 1 {
  265. if a.digit[0] == 0 || a.digit[0] == 1 {
  266. return
  267. }
  268. if a.digit[0] == 2 {
  269. return true, nil
  270. }
  271. }
  272. // `N` must be odd.
  273. if internal_is_even(a) {
  274. return
  275. }
  276. // `N` is not a perfect square: floor(sqrt(`N`))^2 != `N`
  277. if internal_int_is_square(a) or_return { return }
  278. // Is the input equal to one of the primes in the table?
  279. for p in _private_prime_table {
  280. if internal_eq(a, p) {
  281. return true, nil
  282. }
  283. }
  284. // First perform trial division
  285. if internal_int_prime_is_divisible(a) or_return { return }
  286. // Run the Miller-Rabin test with base 2 for the BPSW test.
  287. internal_set(b, 2) or_return
  288. if !(internal_int_prime_miller_rabin(a, b) or_return) { return }
  289. // Rumours have it that Mathematica does a second M-R test with base 3.
  290. // Other rumours have it that their strong L-S test is slightly different.
  291. // It does not hurt, though, beside a bit of extra runtime.
  292. b.digit[0] += 1
  293. if !(internal_int_prime_miller_rabin(a, b) or_return) { return }
  294. // Both, the Frobenius-Underwood test and the the Lucas-Selfridge test are quite
  295. // slow so if speed is an issue, set `USE_MILLER_RABIN_ONLY` to use M-R tests with
  296. // bases 2, 3 and t random bases.
  297. if !miller_rabin_only {
  298. if miller_rabin_trials >= 0 {
  299. when MATH_BIG_USE_FROBENIUS_TEST {
  300. if !(internal_int_prime_frobenius_underwood(a) or_return) { return }
  301. } else {
  302. if !(internal_int_prime_strong_lucas_selfridge(a) or_return) { return }
  303. }
  304. }
  305. }
  306. // Run at least one Miller-Rabin test with a random base.
  307. // Don't replace this with `min`, because we try known deterministic bases
  308. // for certain sized inputs when `miller_rabin_trials` is negative.
  309. if miller_rabin_trials == 0 {
  310. miller_rabin_trials = 1
  311. }
  312. // Only recommended if the input range is known to be < 3_317_044_064_679_887_385_961_981
  313. // It uses the bases necessary for a deterministic M-R test if the input is smaller than 3_317_044_064_679_887_385_961_981
  314. // The caller has to check the size.
  315. // TODO: can be made a bit finer grained but comparing is not free.
  316. if miller_rabin_trials < 0 {
  317. p_max := 0
  318. // Sorenson, Jonathan; Webster, Jonathan (2015), "Strong Pseudoprimes to Twelve Prime Bases".
  319. // 0x437ae92817f9fc85b7e5 = 318_665_857_834_031_151_167_461
  320. atoi(b, "437ae92817f9fc85b7e5", 16) or_return
  321. if internal_lt(a, b) {
  322. p_max = 12
  323. } else {
  324. /* 0x2be6951adc5b22410a5fd = 3_317_044_064_679_887_385_961_981 */
  325. atoi(b, "2be6951adc5b22410a5fd", 16) or_return
  326. if internal_lt(a, b) {
  327. p_max = 13
  328. } else {
  329. return false, .Invalid_Argument
  330. }
  331. }
  332. // We did bases 2 and 3 already, skip them
  333. for ix := 2; ix < p_max; ix += 1 {
  334. internal_set(b, _private_prime_table[ix])
  335. if !(internal_int_prime_miller_rabin(a, b) or_return) { return }
  336. }
  337. } else if miller_rabin_trials > 0 {
  338. // Perform `miller_rabin_trials` M-R tests with random bases between 3 and "a".
  339. // See Fips 186.4 p. 126ff
  340. // The DIGITs have a defined bit-size but the size of a.digit is a simple 'int',
  341. // the size of which can depend on the platform.
  342. size_a := internal_count_bits(a)
  343. mask := (1 << uint(ilog2(size_a))) - 1
  344. /*
  345. Assuming the General Rieman hypothesis (never thought to write that in a
  346. comment) the upper bound can be lowered to 2*(log a)^2.
  347. E. Bach, "Explicit bounds for primality testing and related problems,"
  348. Math. Comp. 55 (1990), 355-380.
  349. size_a = (size_a/10) * 7;
  350. len = 2 * (size_a * size_a);
  351. E.g.: a number of size 2^2048 would be reduced to the upper limit
  352. floor(2048/10)*7 = 1428
  353. 2 * 1428^2 = 4078368
  354. (would have been ~4030331.9962 with floats and natural log instead)
  355. That number is smaller than 2^28, the default bit-size of DIGIT on 32-bit platforms.
  356. */
  357. /*
  358. How many tests, you might ask? Dana Jacobsen of Math::Prime::Util fame
  359. does exactly 1. In words: one. Look at the end of _GMP_is_prime() in
  360. Math-Prime-Util-GMP-0.50/primality.c if you do not believe it.
  361. The function rand() goes to some length to use a cryptographically
  362. good PRNG. That also means that the chance to always get the same base
  363. in the loop is non-zero, although very low.
  364. -- NOTE(Jeroen): This is not yet true in Odin, but I have some ideas.
  365. If the BPSW test and/or the additional Frobenious test have been
  366. performed instead of just the Miller-Rabin test with the bases 2 and 3,
  367. a single extra test should suffice, so such a very unlikely event will not do much harm.
  368. To preemptivly answer the dangling question: no, a witness does not need to be prime.
  369. */
  370. for ix := 0; ix < miller_rabin_trials; ix += 1 {
  371. // rand() guarantees the first digit to be non-zero
  372. internal_random(b, _DIGIT_TYPE_BITS) or_return
  373. // Reduce digit before casting because DIGIT might be bigger than
  374. // an unsigned int and "mask" on the other side is most probably not.
  375. l: int
  376. fips_rand := (uint)(b.digit[0] & DIGIT(mask))
  377. if fips_rand > (uint)(max(int) - _DIGIT_BITS) {
  378. l = max(int) / _DIGIT_BITS
  379. } else {
  380. l = (int(fips_rand) + _DIGIT_BITS) / _DIGIT_BITS
  381. }
  382. // Unlikely.
  383. if (l < 0) {
  384. ix -= 1
  385. continue
  386. }
  387. internal_random(b, l) or_return
  388. // That number might got too big and the witness has to be smaller than "a"
  389. l = internal_count_bits(b)
  390. if l >= size_a {
  391. l = (l - size_a) + 1
  392. internal_shr(b, b, l) or_return
  393. }
  394. // Although the chance for b <= 3 is miniscule, try again.
  395. if internal_lte(b, 3) {
  396. ix -= 1
  397. continue
  398. }
  399. if !(internal_int_prime_miller_rabin(a, b) or_return) { return }
  400. }
  401. }
  402. // Passed the test.
  403. return true, nil
  404. }
  405. /*
  406. * floor of positive solution of (2^16) - 1 = (a + 4) * (2 * a + 5)
  407. * TODO: Both values are smaller than N^(1/4), would have to use a bigint
  408. * for `a` instead, but any `a` bigger than about 120 are already so rare that
  409. * it is possible to ignore them and still get enough pseudoprimes.
  410. * But it is still a restriction of the set of available pseudoprimes
  411. * which makes this implementation less secure if used stand-alone.
  412. */
  413. _FROBENIUS_UNDERWOOD_A :: 32764
  414. internal_int_prime_frobenius_underwood :: proc(N: ^Int, allocator := context.allocator) -> (result: bool, err: Error) {
  415. context.allocator = allocator
  416. T1z, T2z, Np1z, sz, tz := &Int{}, &Int{}, &Int{}, &Int{}, &Int{}
  417. defer internal_destroy(T1z, T2z, Np1z, sz, tz)
  418. internal_init_multi(T1z, T2z, Np1z, sz, tz) or_return
  419. a, ap2: int
  420. frob: for a = 0; a < _FROBENIUS_UNDERWOOD_A; a += 1 {
  421. switch a {
  422. case 2, 4, 7, 8, 10, 14, 18, 23, 26, 28:
  423. continue frob
  424. }
  425. internal_set(T1z, i32((a * a) - 4))
  426. j := internal_int_kronecker(T1z, N) or_return
  427. switch j {
  428. case -1: break frob
  429. case 0: return false, nil
  430. }
  431. }
  432. // Tell it a composite and set return value accordingly.
  433. if a >= _FROBENIUS_UNDERWOOD_A { return false, .Max_Iterations_Reached }
  434. // Composite if N and (a+4)*(2*a+5) are not coprime.
  435. internal_set(T1z, u32((a + 4) * ((2 * a) + 5)))
  436. internal_int_gcd(T1z, T1z, N) or_return
  437. if !(T1z.used == 1 && T1z.digit[0] == 1) {
  438. // Composite.
  439. return false, nil
  440. }
  441. ap2 = a + 2
  442. internal_add(Np1z, N, 1) or_return
  443. internal_set(sz, 1) or_return
  444. internal_set(tz, 2) or_return
  445. for i := internal_count_bits(Np1z) - 2; i >= 0; i -= 1 {
  446. // temp = (sz * (a * sz + 2 * tz)) % N;
  447. // tz = ((tz - sz) * (tz + sz)) % N;
  448. // sz = temp;
  449. internal_int_shl1(T2z, tz) or_return
  450. // a = 0 at about 50% of the cases (non-square and odd input)
  451. if a != 0 {
  452. internal_mul(T1z, sz, DIGIT(a)) or_return
  453. internal_add(T2z, T2z, T1z) or_return
  454. }
  455. internal_mul(T1z, T2z, sz) or_return
  456. internal_sub(T2z, tz, sz) or_return
  457. internal_add(sz, sz, tz) or_return
  458. internal_mul(tz, sz, T2z) or_return
  459. internal_mod(tz, tz, N) or_return
  460. internal_mod(sz, T1z, N) or_return
  461. if bit, _ := internal_int_bitfield_extract_bool(Np1z, i); bit {
  462. // temp = (a+2) * sz + tz
  463. // tz = 2 * tz - sz
  464. // sz = temp
  465. if a == 0 {
  466. internal_int_shl1(T1z, sz) or_return
  467. } else {
  468. internal_mul(T1z, sz, DIGIT(ap2)) or_return
  469. }
  470. internal_add(T1z, T1z, tz) or_return
  471. internal_int_shl1(T2z, tz) or_return
  472. internal_sub(tz, T2z, sz)
  473. internal_swap(sz, T1z)
  474. }
  475. }
  476. internal_set(T1z, u32((2 * a) + 5)) or_return
  477. internal_mod(T1z, T1z, N) or_return
  478. result = internal_is_zero(sz) && internal_eq(tz, T1z)
  479. return
  480. }
  481. /*
  482. Strong Lucas-Selfridge test.
  483. returns true if it is a strong L-S prime, false if it is composite
  484. Code ported from Thomas Ray Nicely's implementation of the BPSW test at http://www.trnicely.net/misc/bpsw.html
  485. Freeware copyright (C) 2016 Thomas R. Nicely <http://www.trnicely.net>.
  486. Released into the public domain by the author, who disclaims any legal liability arising from its use.
  487. The multi-line comments are made by Thomas R. Nicely and are copied verbatim.
  488. (If that name sounds familiar, he is the guy who found the fdiv bug in the Pentium CPU.)
  489. */
  490. internal_int_prime_strong_lucas_selfridge :: proc(a: ^Int, allocator := context.allocator) -> (lucas_selfridge: bool, err: Error) {
  491. // TODO: choose better variable names!
  492. Dz, gcd, Np1, Uz, Vz, U2mz, V2mz, Qmz, Q2mz, Qkdz, T1z, T2z, T3z, T4z, Q2kdz := &Int{}, &Int{}, &Int{}, &Int{}, &Int{}, &Int{}, &Int{}, &Int{}, &Int{}, &Int{}, &Int{}, &Int{}, &Int{}, &Int{}, &Int{}
  493. defer internal_destroy(Dz, gcd, Np1, Uz, Vz, U2mz, V2mz, Qmz, Q2mz, Qkdz, T1z, T2z, T3z, T4z, Q2kdz)
  494. /*
  495. Find the first element D in the sequence {5, -7, 9, -11, 13, ...}
  496. such that Jacobi(D,N) = -1 (Selfridge's algorithm). Theory
  497. indicates that, if N is not a perfect square, D will "nearly
  498. always" be "small." Just in case, an overflow trap for D is included.
  499. */
  500. internal_init_multi(Dz, gcd, Np1, Uz, Vz, U2mz, V2mz, Qmz, Q2mz, Qkdz, T1z, T2z, T3z, T4z, Q2kdz) or_return
  501. D := 5
  502. sign := 1
  503. Ds : int
  504. for {
  505. Ds = sign * D
  506. sign = -sign
  507. internal_set(Dz, D) or_return
  508. internal_int_gcd(gcd, a, Dz) or_return
  509. /*
  510. If 1 < GCD < `N` then `N` is composite with factor "D", and
  511. Jacobi(D, N) is technically undefined (but often returned as zero).
  512. */
  513. if internal_gt(gcd, 1) && internal_lt(gcd, a) { return }
  514. if Ds < 0 { Dz.sign = .Negative }
  515. j := internal_int_kronecker(Dz, a) or_return
  516. if j == -1 { break }
  517. D += 2
  518. if D > max(int) - 2 { return false, .Invalid_Argument }
  519. }
  520. Q := (1 - Ds) / 4 /* Required so D = P*P - 4*Q */
  521. /*
  522. NOTE: The conditions (a) N does not divide Q, and
  523. (b) D is square-free or not a perfect square, are included by
  524. some authors; e.g., "Prime numbers and computer methods for
  525. factorization," Hans Riesel (2nd ed., 1994, Birkhauser, Boston),
  526. p. 130. For this particular application of Lucas sequences,
  527. these conditions were found to be immaterial.
  528. */
  529. /*
  530. Now calculate N - Jacobi(D,N) = N + 1 (even), and calculate the
  531. odd positive integer d and positive integer s for which
  532. N + 1 = 2^s*d (similar to the step for N - 1 in Miller's test).
  533. The strong Lucas-Selfridge test then returns N as a strong
  534. Lucas probable prime (slprp) if any of the following
  535. conditions is met: U_d=0, V_d=0, V_2d=0, V_4d=0, V_8d=0,
  536. V_16d=0, ..., etc., ending with V_{2^(s-1)*d}=V_{(N+1)/2}=0
  537. (all equalities mod N). Thus d is the highest index of U that
  538. must be computed (since V_2m is independent of U), compared
  539. to U_{N+1} for the standard Lucas-Selfridge test; and no
  540. index of V beyond (N+1)/2 is required, just as in the
  541. standard Lucas-Selfridge test. However, the quantity Q^d must
  542. be computed for use (if necessary) in the latter stages of
  543. the test. The result is that the strong Lucas-Selfridge test
  544. has a running time only slightly greater (order of 10 %) than
  545. that of the standard Lucas-Selfridge test, while producing
  546. only (roughly) 30 % as many pseudoprimes (and every strong
  547. Lucas pseudoprime is also a standard Lucas pseudoprime). Thus
  548. the evidence indicates that the strong Lucas-Selfridge test is
  549. more effective than the standard Lucas-Selfridge test, and a
  550. Baillie-PSW test based on the strong Lucas-Selfridge test
  551. should be more reliable.
  552. */
  553. internal_add(Np1, a, 1) or_return
  554. s := internal_count_lsb(Np1) or_return
  555. /*
  556. This should round towards zero because Thomas R. Nicely used GMP's mpz_tdiv_q_2exp()
  557. and mp_div_2d() is equivalent. Additionally: dividing an even number by two does not produce
  558. any leftovers.
  559. */
  560. internal_int_shr(Dz, Np1, s) or_return
  561. /*
  562. We must now compute U_d and V_d. Since d is odd, the accumulated
  563. values U and V are initialized to U_1 and V_1 (if the target
  564. index were even, U and V would be initialized instead to U_0=0
  565. and V_0=2). The values of U_2m and V_2m are also initialized to
  566. U_1 and V_1; the FOR loop calculates in succession U_2 and V_2,
  567. U_4 and V_4, U_8 and V_8, etc. If the corresponding bits
  568. (1, 2, 3, ...) of t are on (the zero bit having been accounted
  569. for in the initialization of U and V), these values are then
  570. combined with the previous totals for U and V, using the
  571. composition formulas for addition of indices.
  572. */
  573. internal_set(Uz, 1) or_return
  574. internal_set(Vz, 1) or_return // P := 1; /* Selfridge's choice */
  575. internal_set(U2mz, 1) or_return
  576. internal_set(V2mz, 1) or_return // P := 1; /* Selfridge's choice */
  577. internal_set(Qmz, Q) or_return
  578. internal_int_shl1(Q2mz, Qmz) or_return
  579. /*
  580. Initializes calculation of Q^d.
  581. */
  582. internal_set(Qkdz, Q) or_return
  583. Nbits := internal_count_bits(Dz)
  584. for u := 1; u < Nbits; u += 1 { /* zero bit off, already accounted for */
  585. /*
  586. Formulas for doubling of indices (carried out mod N). Note that
  587. the indices denoted as "2m" are actually powers of 2, specifically
  588. 2^(ul-1) beginning each loop and 2^ul ending each loop.
  589. U_2m = U_m*V_m
  590. V_2m = V_m*V_m - 2*Q^m
  591. */
  592. internal_mul(U2mz, U2mz, V2mz) or_return
  593. internal_mod(U2mz, U2mz, a) or_return
  594. internal_sqr(V2mz, V2mz) or_return
  595. internal_sub(V2mz, V2mz, Q2mz) or_return
  596. internal_mod(V2mz, V2mz, a) or_return
  597. /*
  598. Must calculate powers of Q for use in V_2m, also for Q^d later.
  599. */
  600. internal_sqr(Qmz, Qmz) or_return
  601. /* Prevents overflow. Still necessary without a fixed prealloc'd mem.? */
  602. internal_mod(Qmz, Qmz, a) or_return
  603. internal_int_shl1(Q2mz, Qmz) or_return
  604. if internal_int_bitfield_extract_bool(Dz, u) or_return {
  605. /*
  606. Formulas for addition of indices (carried out mod N);
  607. U_(m+n) = (U_m*V_n + U_n*V_m)/2
  608. V_(m+n) = (V_m*V_n + D*U_m*U_n)/2
  609. Be careful with division by 2 (mod N)!
  610. */
  611. internal_mul(T1z, U2mz, Vz) or_return
  612. internal_mul(T2z, Uz, V2mz) or_return
  613. internal_mul(T3z, V2mz, Vz) or_return
  614. internal_mul(T4z, U2mz, Uz) or_return
  615. internal_mul(T4z, T4z, Ds) or_return
  616. internal_add(Uz, T1z, T2z) or_return
  617. if internal_is_odd(Uz) {
  618. internal_add(Uz, Uz, a) or_return
  619. }
  620. /*
  621. This should round towards negative infinity because Thomas R. Nicely used GMP's mpz_fdiv_q_2exp().
  622. But `internal_shr1` does not do so, it is truncating instead.
  623. */
  624. oddness := internal_is_odd(Uz)
  625. internal_int_shr1(Uz, Uz) or_return
  626. if internal_is_negative(Uz) && oddness {
  627. internal_sub(Uz, Uz, 1) or_return
  628. }
  629. internal_add(Vz, T3z, T4z) or_return
  630. if internal_is_odd(Vz) {
  631. internal_add(Vz, Vz, a) or_return
  632. }
  633. oddness = internal_is_odd(Vz)
  634. internal_int_shr1(Vz, Vz) or_return
  635. if internal_is_negative(Vz) && oddness {
  636. internal_sub(Vz, Vz, 1) or_return
  637. }
  638. internal_mod(Uz, Uz, a) or_return
  639. internal_mod(Vz, Vz, a) or_return
  640. /* Calculating Q^d for later use */
  641. internal_mul(Qkdz, Qkdz, Qmz) or_return
  642. internal_mod(Qkdz, Qkdz, a) or_return
  643. }
  644. }
  645. /*
  646. If U_d or V_d is congruent to 0 mod N, then N is a prime or a strong Lucas pseudoprime. */
  647. if internal_is_zero(Uz) || internal_is_zero(Vz) {
  648. return true, nil
  649. }
  650. /*
  651. NOTE: Ribenboim ("The new book of prime number records," 3rd ed.,
  652. 1995/6) omits the condition V0 on p.142, but includes it on
  653. p. 130. The condition is NECESSARY; otherwise the test will
  654. return false negatives---e.g., the primes 29 and 2000029 will be
  655. returned as composite.
  656. */
  657. /*
  658. Otherwise, we must compute V_2d, V_4d, V_8d, ..., V_{2^(s-1)*d}
  659. by repeated use of the formula V_2m = V_m*V_m - 2*Q^m. If any of
  660. these are congruent to 0 mod N, then N is a prime or a strong
  661. Lucas pseudoprime.
  662. */
  663. /* Initialize 2*Q^(d*2^r) for V_2m */
  664. internal_int_shr1(Q2kdz, Qkdz) or_return
  665. for r := 1; r < s; r += 1 {
  666. internal_sqr(Vz, Vz) or_return
  667. internal_sub(Vz, Vz, Q2kdz) or_return
  668. internal_mod(Vz, Vz, a) or_return
  669. if internal_is_zero(Vz) {
  670. return true, nil
  671. }
  672. /* Calculate Q^{d*2^r} for next r (final iteration irrelevant). */
  673. if r < (s - 1) {
  674. internal_sqr(Qkdz, Qkdz) or_return
  675. internal_mod(Qkdz, Qkdz, a) or_return
  676. internal_int_shl1(Q2kdz, Qkdz) or_return
  677. }
  678. }
  679. return false, nil
  680. }
  681. /*
  682. Performs one Fermat test.
  683. If "a" were prime then b**a == b (mod a) since the order of
  684. the multiplicative sub-group would be phi(a) = a-1. That means
  685. it would be the same as b**(a mod (a-1)) == b**1 == b (mod a).
  686. Returns `true` if the congruence holds, or `false` otherwise.
  687. Assumes `a` and `b` not to be `nil` and to have been initialized.
  688. */
  689. internal_prime_fermat :: proc(a, b: ^Int, allocator := context.allocator) -> (fermat: bool, err: Error) {
  690. t := &Int{}
  691. defer internal_destroy(t)
  692. /*
  693. Ensure `b` > 1.
  694. */
  695. if !internal_gt(b, 1) { return false, .Invalid_Argument }
  696. /*
  697. Compute `t` = `b`**`a` mod `a`
  698. */
  699. internal_int_exponent_mod(t, b, a, a) or_return
  700. /*
  701. Is it equal to b?
  702. */
  703. fermat = internal_eq(t, b)
  704. return
  705. }
  706. /*
  707. Tonelli-Shanks algorithm
  708. https://en.wikipedia.org/wiki/Tonelli%E2%80%93Shanks_algorithm
  709. https://gmplib.org/list-archives/gmp-discuss/2013-April/005300.html
  710. */
  711. internal_int_sqrtmod_prime :: proc(res, n, prime: ^Int, allocator := context.allocator) -> (err: Error) {
  712. context.allocator = allocator
  713. /*
  714. The type is "int" because of the types in the mp_int struct.
  715. Don't forget to change them here when you change them there!
  716. */
  717. S, M, i: int
  718. t1, C, Q, Z, T, R, two := &Int{}, &Int{}, &Int{}, &Int{}, &Int{}, &Int{}, &Int{}
  719. defer internal_destroy(t1, C, Q, Z, T, R, two)
  720. /*
  721. First handle the simple cases.
  722. */
  723. if internal_is_zero(n) { return internal_zero(res) }
  724. /*
  725. "prime" must be odd and > 2
  726. */
  727. if internal_is_even(prime) || internal_lt(prime, 3) { return .Invalid_Argument }
  728. legendre := internal_int_kronecker(n, prime) or_return
  729. /*
  730. n \not\cong 0 (mod p) and n \cong r^2 (mod p) for some r \in N^+
  731. */
  732. if legendre != 1 { return .Invalid_Argument }
  733. internal_init_multi(t1, C, Q, Z, T, R, two) or_return
  734. /*
  735. SPECIAL CASE: if prime mod 4 == 3
  736. compute directly: err = n^(prime+1)/4 mod prime
  737. Handbook of Applied Cryptography algorithm 3.36
  738. x%4 == x&3 for x in N and x>0
  739. */
  740. if prime.digit[0] & 3 == 3 {
  741. internal_add(t1, prime, 1) or_return
  742. internal_shr(t1, t1, 2) or_return
  743. internal_int_exponent_mod(res, n, t1, prime) or_return
  744. return
  745. }
  746. /*
  747. NOW: Tonelli-Shanks algorithm
  748. Factor out powers of 2 from prime-1, defining Q and S as: prime-1 = Q*2^S
  749. Q = prime - 1
  750. */
  751. internal_copy(Q, prime) or_return
  752. internal_sub(Q, Q, 1) or_return
  753. /*
  754. S = 0
  755. */
  756. S = 0
  757. for internal_is_even(Q) {
  758. /*
  759. Q = Q / 2
  760. */
  761. internal_int_shr1(Q, Q) or_return
  762. /*
  763. S = S + 1
  764. */
  765. S += 1
  766. }
  767. /*
  768. Find a `Z` such that the Legendre symbol (Z|prime) == -1.
  769. Z = 2.
  770. */
  771. internal_set(Z, 2) or_return
  772. for {
  773. legendre = internal_int_kronecker(Z, prime) or_return
  774. /*
  775. If "prime" (p) is an odd prime Jacobi(k|p) = 0 for k \cong 0 (mod p)
  776. but there is at least one non-quadratic residue before k>=p if p is an odd prime.
  777. */
  778. if legendre == 0 { return .Invalid_Argument }
  779. if legendre == -1 { break }
  780. /*
  781. Z = Z + 1
  782. */
  783. internal_add(Z, Z, 1) or_return
  784. }
  785. /*
  786. C = Z ^ Q mod prime
  787. */
  788. internal_int_exponent_mod(C, Z, Q, prime) or_return
  789. /*
  790. t1 = (Q + 1) / 2
  791. */
  792. internal_add(t1, Q, 1) or_return
  793. internal_int_shr1(t1, t1) or_return
  794. /*
  795. R = n ^ ((Q + 1) / 2) mod prime
  796. */
  797. internal_int_exponent_mod(R, n, t1, prime) or_return
  798. /*
  799. T = n ^ Q mod prime
  800. */
  801. internal_int_exponent_mod(T, n, Q, prime) or_return
  802. /*
  803. M = S
  804. */
  805. M = S
  806. internal_set(two, 2)
  807. for {
  808. internal_copy(t1, T) or_return
  809. i = 0
  810. for {
  811. if internal_eq(T, 1) { break }
  812. /*
  813. No exponent in the range 0 < i < M found.
  814. (M is at least 1 in the first round because "prime" > 2)
  815. */
  816. if M == i { return .Invalid_Argument }
  817. internal_int_exponent_mod(t1, t1, two, prime) or_return
  818. i += 1
  819. }
  820. if i == 0 {
  821. internal_copy(res, R) or_return
  822. }
  823. /*
  824. t1 = 2 ^ (M - i - 1)
  825. */
  826. internal_set(t1, M - i - 1) or_return
  827. internal_int_exponent_mod(t1, two, t1, prime) or_return
  828. /*
  829. t1 = C ^ (2 ^ (M - i - 1)) mod prime
  830. */
  831. internal_int_exponent_mod(t1, C, t1, prime) or_return
  832. /*
  833. C = (t1 * t1) mod prime
  834. */
  835. internal_sqrmod(C, t1, prime) or_return
  836. /*
  837. R = (R * t1) mod prime
  838. */
  839. internal_mulmod(R, R, t1, prime) or_return
  840. /*
  841. T = (T * C) mod prime
  842. */
  843. mulmod(T, T, C, prime) or_return
  844. /*
  845. M = i
  846. */
  847. M = i
  848. }
  849. return
  850. }
  851. /*
  852. Finds the next prime after the number `a` using `t` trials of Miller-Rabin,
  853. in place: It sets `a` to the prime found.
  854. `bbs_style` = true means the prime must be congruent to 3 mod 4
  855. */
  856. internal_int_prime_next_prime :: proc(a: ^Int, trials: int, bbs_style: bool, allocator := context.allocator) -> (err: Error) {
  857. context.allocator = allocator
  858. res_tab := [_PRIME_TAB_SIZE]DIGIT{}
  859. /*
  860. Force positive.
  861. */
  862. a.sign = .Zero_or_Positive
  863. /*
  864. Simple algo if `a` is less than the largest prime in the table.
  865. */
  866. if internal_lt(a, _private_prime_table[_PRIME_TAB_SIZE - 1]) {
  867. /*
  868. Find which prime it is bigger than `a`
  869. */
  870. for p in _private_prime_table {
  871. cmp := internal_cmp(a, p)
  872. if cmp == 0 { continue }
  873. if cmp != 1 {
  874. if bbs_style && (p & 3 != 3) {
  875. /*
  876. Try again until we get a prime congruent to 3 mod 4.
  877. */
  878. continue
  879. } else {
  880. return internal_set(a, p)
  881. }
  882. }
  883. }
  884. /*
  885. Fall through to the sieve.
  886. */
  887. }
  888. /*
  889. Generate a prime congruent to 3 mod 4 or 1/3 mod 4?
  890. */
  891. kstep: DIGIT = 4 if bbs_style else 2
  892. /*
  893. At this point we will use a combination of a sieve and Miller-Rabin.
  894. */
  895. if bbs_style {
  896. /*
  897. If `a` mod 4 != 3 subtract the correct value to make it so.
  898. */
  899. if a.digit[0] & 3 != 3 {
  900. internal_sub(a, a, (a.digit[0] & 3) + 1) or_return
  901. }
  902. } else {
  903. if internal_is_even(a) {
  904. /*
  905. Force odd.
  906. */
  907. internal_sub(a, a, 1) or_return
  908. }
  909. }
  910. /*
  911. Generate the restable.
  912. */
  913. for x := 1; x < _PRIME_TAB_SIZE; x += 1 {
  914. res_tab = cast(type_of(res_tab))(internal_mod(a, _private_prime_table[x]) or_return)
  915. }
  916. for {
  917. step := DIGIT(0)
  918. y: bool
  919. /*
  920. Skip to the next non-trivially divisible candidate.
  921. */
  922. for {
  923. /*
  924. y == true if any residue was zero [e.g. cannot be prime]
  925. */
  926. y = false
  927. /*
  928. Increase step to next candidate.
  929. */
  930. step += kstep
  931. /*
  932. Compute the new residue without using division.
  933. */
  934. for x := 1; x < _PRIME_TAB_SIZE; x += 1 {
  935. /*
  936. Add the step to each residue.
  937. */
  938. res_tab[x] += kstep
  939. /*
  940. Subtract the modulus [instead of using division].
  941. */
  942. if res_tab[x] >= _private_prime_table[x] {
  943. res_tab[x] -= _private_prime_table[x]
  944. }
  945. /*
  946. Set flag if zero.
  947. */
  948. if res_tab[x] == 0 {
  949. y = true
  950. }
  951. }
  952. if !(y && (step < (((1 << _DIGIT_BITS) - kstep)))) { break }
  953. }
  954. /*
  955. Add the step.
  956. */
  957. internal_add(a, a, step) or_return
  958. /*
  959. If we didn't pass the sieve and step == MP_MAX then skip test */
  960. if y && (step >= ((1 << _DIGIT_BITS) - kstep)) { continue }
  961. if internal_int_is_prime(a, trials) or_return { break }
  962. }
  963. return
  964. }
  965. /*
  966. Makes a truly random prime of a given size (bits),
  967. Flags are as follows:
  968. Blum_Blum_Shub - Make prime congruent to 3 mod 4
  969. Safe - Make sure (p-1)/2 is prime as well (implies .Blum_Blum_Shub)
  970. Second_MSB_On - Make the 2nd highest bit one
  971. This is possibly the mother of all prime generation functions, muahahahahaha!
  972. */
  973. internal_random_prime :: proc(a: ^Int, size_in_bits: int, trials: int, flags := Primality_Flags{}, allocator := context.allocator) -> (err: Error) {
  974. context.allocator = allocator
  975. flags := flags
  976. trials := trials
  977. /*
  978. Sanity check the input.
  979. */
  980. if size_in_bits <= 1 || trials < -1 { return .Invalid_Argument }
  981. /*
  982. `.Safe` implies `.Blum_Blum_Shub`.
  983. */
  984. if .Safe in flags {
  985. if size_in_bits < 3 {
  986. /*
  987. The smallest safe prime is 5, which takes 3 bits.
  988. We early out now, else we'd be locked in an infinite loop trying to generate a 2-bit Safe Prime.
  989. */
  990. return .Invalid_Argument
  991. }
  992. flags += { .Blum_Blum_Shub, }
  993. }
  994. /*
  995. Automatically choose the number of Rabin-Miller trials?
  996. */
  997. if trials == -1 {
  998. trials = number_of_rabin_miller_trials(size_in_bits)
  999. }
  1000. RANDOM_PRIME_ITERATIONS_USED = 0
  1001. for {
  1002. if MAX_ITERATIONS_RANDOM_PRIME > 0 {
  1003. RANDOM_PRIME_ITERATIONS_USED += 1
  1004. if RANDOM_PRIME_ITERATIONS_USED > MAX_ITERATIONS_RANDOM_PRIME {
  1005. return .Max_Iterations_Reached
  1006. }
  1007. }
  1008. internal_int_random(a, size_in_bits) or_return
  1009. /*
  1010. Make sure it's odd.
  1011. */
  1012. if size_in_bits > 2 {
  1013. a.digit[0] |= 1
  1014. } else {
  1015. /*
  1016. A 2-bit prime can be either 2 (0b10) or 3 (0b11).
  1017. So, let's force the top bit to 1 and return early.
  1018. */
  1019. a.digit[0] |= 2
  1020. return nil
  1021. }
  1022. if .Blum_Blum_Shub in flags {
  1023. a.digit[0] |= 3
  1024. }
  1025. if .Second_MSB_On in flags {
  1026. /*
  1027. Ensure there's enough space for the bit to be set.
  1028. */
  1029. if a.used * _DIGIT_BITS < size_in_bits - 1 {
  1030. new_size := (size_in_bits - 1) / _DIGIT_BITS
  1031. if new_size % _DIGIT_BITS > 0 {
  1032. new_size += 1
  1033. }
  1034. internal_grow(a, new_size) or_return
  1035. a.used = new_size
  1036. }
  1037. internal_int_bitfield_set_single(a, size_in_bits - 2) or_return
  1038. }
  1039. /*
  1040. Is it prime?
  1041. */
  1042. res := internal_int_is_prime(a, trials) or_return
  1043. if !res {
  1044. continue
  1045. }
  1046. if .Safe in flags {
  1047. /*
  1048. See if (a-1)/2 is prime.
  1049. */
  1050. internal_sub(a, a, 1) or_return
  1051. internal_int_shr1(a, a) or_return
  1052. /*
  1053. Is it prime?
  1054. */
  1055. res = internal_int_is_prime(a, trials) or_return
  1056. }
  1057. if res {
  1058. break
  1059. }
  1060. }
  1061. if .Safe in flags {
  1062. /*
  1063. Restore a to the original value.
  1064. */
  1065. internal_int_shl1(a, a) or_return
  1066. internal_add(a, a, 1) or_return
  1067. }
  1068. return
  1069. }
  1070. /*
  1071. Extended Euclidean algorithm of (a, b) produces `a * u1` + `b * u2` = `u3`.
  1072. */
  1073. internal_int_extended_euclidean :: proc(a, b, U1, U2, U3: ^Int, allocator := context.allocator) -> (err: Error) {
  1074. context.allocator = allocator
  1075. u1, u2, u3, v1, v2, v3, t1, t2, t3, q, tmp := &Int{}, &Int{}, &Int{}, &Int{}, &Int{}, &Int{}, &Int{}, &Int{}, &Int{}, &Int{}, &Int{}
  1076. defer internal_destroy(u1, u2, u3, v1, v2, v3, t1, t2, t3, q, tmp)
  1077. internal_init_multi(u1, u2, u3, v1, v2, v3, t1, t2, t3, q, tmp) or_return
  1078. /*
  1079. Initialize, (u1, u2, u3) = (1, 0, a).
  1080. */
  1081. internal_set(u1, 1) or_return
  1082. internal_set(u3, a) or_return
  1083. /*
  1084. Initialize, (v1, v2, v3) = (0, 1, b).
  1085. */
  1086. internal_set(v2, 1) or_return
  1087. internal_set(v3, b) or_return
  1088. /*
  1089. Loop while v3 != 0
  1090. */
  1091. for !internal_is_zero(v3) {
  1092. /*
  1093. q = u3 / v3
  1094. */
  1095. internal_div(q, u3, v3) or_return
  1096. /*
  1097. (t1, t2, t3) = (u1, u2, u3) - (v1, v2, v3)q
  1098. */
  1099. internal_mul(tmp, v1, q) or_return
  1100. internal_sub( t1, u1, tmp) or_return
  1101. internal_mul(tmp, v2, q) or_return
  1102. internal_sub( t2, u2, tmp) or_return
  1103. internal_mul(tmp, v3, q) or_return
  1104. internal_sub( t3, u3, tmp) or_return
  1105. /*
  1106. (u1, u2, u3) = (v1, v2, v3)
  1107. */
  1108. internal_set(u1, v1) or_return
  1109. internal_set(u2, v2) or_return
  1110. internal_set(u3, v3) or_return
  1111. /*
  1112. (v1, v2, v3) = (t1, t2, t3)
  1113. */
  1114. internal_set(v1, t1) or_return
  1115. internal_set(v2, t2) or_return
  1116. internal_set(v3, t3) or_return
  1117. }
  1118. /*
  1119. Make sure U3 >= 0.
  1120. */
  1121. if internal_is_negative(u3) {
  1122. internal_neg(u1, u1) or_return
  1123. internal_neg(u2, u2) or_return
  1124. internal_neg(u3, u3) or_return
  1125. }
  1126. /*
  1127. Copy result out.
  1128. */
  1129. if U1 != nil {
  1130. internal_swap(u1, U1)
  1131. }
  1132. if U2 != nil {
  1133. internal_swap(u2, U2)
  1134. }
  1135. if U3 != nil {
  1136. internal_swap(u3, U3)
  1137. }
  1138. return
  1139. }
  1140. /*
  1141. Returns the number of Rabin-Miller trials needed for a given bit size.
  1142. */
  1143. number_of_rabin_miller_trials :: proc(bit_size: int) -> (number_of_trials: int) {
  1144. switch {
  1145. case bit_size <= 80:
  1146. return -1 /* Use deterministic algorithm for size <= 80 bits */
  1147. case bit_size >= 81 && bit_size < 96:
  1148. return 37 /* max. error = 2^(-96) */
  1149. case bit_size >= 96 && bit_size < 128:
  1150. return 32 /* max. error = 2^(-96) */
  1151. case bit_size >= 128 && bit_size < 160:
  1152. return 40 /* max. error = 2^(-112) */
  1153. case bit_size >= 160 && bit_size < 256:
  1154. return 35 /* max. error = 2^(-112) */
  1155. case bit_size >= 256 && bit_size < 384:
  1156. return 27 /* max. error = 2^(-128) */
  1157. case bit_size >= 384 && bit_size < 512:
  1158. return 16 /* max. error = 2^(-128) */
  1159. case bit_size >= 512 && bit_size < 768:
  1160. return 18 /* max. error = 2^(-160) */
  1161. case bit_size >= 768 && bit_size < 896:
  1162. return 11 /* max. error = 2^(-160) */
  1163. case bit_size >= 896 && bit_size < 1_024:
  1164. return 10 /* max. error = 2^(-160) */
  1165. case bit_size >= 1_024 && bit_size < 1_536:
  1166. return 12 /* max. error = 2^(-192) */
  1167. case bit_size >= 1_536 && bit_size < 2_048:
  1168. return 8 /* max. error = 2^(-192) */
  1169. case bit_size >= 2_048 && bit_size < 3_072:
  1170. return 6 /* max. error = 2^(-192) */
  1171. case bit_size >= 3_072 && bit_size < 4_096:
  1172. return 4 /* max. error = 2^(-192) */
  1173. case bit_size >= 4_096 && bit_size < 5_120:
  1174. return 5 /* max. error = 2^(-256) */
  1175. case bit_size >= 5_120 && bit_size < 6_144:
  1176. return 4 /* max. error = 2^(-256) */
  1177. case bit_size >= 6_144 && bit_size < 8_192:
  1178. return 4 /* max. error = 2^(-256) */
  1179. case bit_size >= 8_192 && bit_size < 9_216:
  1180. return 3 /* max. error = 2^(-256) */
  1181. case bit_size >= 9_216 && bit_size < 10_240:
  1182. return 3 /* max. error = 2^(-256) */
  1183. case:
  1184. return 2 /* For keysizes bigger than 10_240 use always at least 2 Rounds */
  1185. }
  1186. }