common.odin 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  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. */
  8. package math_big
  9. import "core:intrinsics"
  10. /*
  11. TODO: Make the tunables runtime adjustable where practical.
  12. This allows to benchmark and/or setting optimized values for a certain CPU without recompiling.
  13. */
  14. /*
  15. ========================== TUNABLES ==========================
  16. `initialize_constants` returns `#config(MUL_KARATSUBA_CUTOFF, _DEFAULT_MUL_KARATSUBA_CUTOFF)`
  17. and we initialize this cutoff that way so that the procedure is used and called,
  18. because it handles initializing the constants ONE, ZERO, MINUS_ONE, NAN and INF.
  19. `initialize_constants` also replaces the other `_DEFAULT_*` cutoffs with custom compile-time values if so `#config`ured.
  20. */
  21. /*
  22. There is a bug with DLL globals. They don't get set.
  23. To allow tests to run we add `-define:MATH_BIG_EXE=false` to hardcode the cutoffs for now.
  24. */
  25. when #config(MATH_BIG_EXE, true) {
  26. MUL_KARATSUBA_CUTOFF := initialize_constants()
  27. SQR_KARATSUBA_CUTOFF := _DEFAULT_SQR_KARATSUBA_CUTOFF
  28. MUL_TOOM_CUTOFF := _DEFAULT_MUL_TOOM_CUTOFF
  29. SQR_TOOM_CUTOFF := _DEFAULT_SQR_TOOM_CUTOFF
  30. } else {
  31. MUL_KARATSUBA_CUTOFF := _DEFAULT_MUL_KARATSUBA_CUTOFF
  32. SQR_KARATSUBA_CUTOFF := _DEFAULT_SQR_KARATSUBA_CUTOFF
  33. MUL_TOOM_CUTOFF := _DEFAULT_MUL_TOOM_CUTOFF
  34. SQR_TOOM_CUTOFF := _DEFAULT_SQR_TOOM_CUTOFF
  35. }
  36. /*
  37. These defaults were tuned on an AMD A8-6600K (64-bit) using libTomMath's `make tune`.
  38. TODO(Jeroen): Port this tuning algorithm and tune them for more modern processors.
  39. It would also be cool if we collected some data across various processor families.
  40. This would let uss set reasonable defaults at runtime as this library initializes
  41. itself by using `cpuid` or the ARM equivalent.
  42. IMPORTANT: The 32_BIT path has largely gone untested. It needs to be tested and
  43. debugged where necessary.
  44. */
  45. _DEFAULT_MUL_KARATSUBA_CUTOFF :: #config(MATH_BIG_MUL_KARATSUBA_CUTOFF, 80)
  46. _DEFAULT_SQR_KARATSUBA_CUTOFF :: #config(MATH_BIG_SQR_KARATSUBA_CUTOFF, 120)
  47. _DEFAULT_MUL_TOOM_CUTOFF :: #config(MATH_BIG_MUL_TOOM_CUTOFF, 350)
  48. _DEFAULT_SQR_TOOM_CUTOFF :: #config(MATH_BIG_SQR_TOOM_CUTOFF, 400)
  49. MAX_ITERATIONS_ROOT_N := 500
  50. /*
  51. Largest `N` for which we'll compute `N!`
  52. */
  53. FACTORIAL_MAX_N := 1_000_000
  54. /*
  55. Cutoff to switch to int_factorial_binary_split, and its max recursion level.
  56. */
  57. FACTORIAL_BINARY_SPLIT_CUTOFF := 6100
  58. FACTORIAL_BINARY_SPLIT_MAX_RECURSIONS := 100
  59. /*
  60. `internal_int_is_prime` switchables.
  61. Use Frobenius-Underwood for primality testing, or use Lucas-Selfridge (default).
  62. */
  63. MATH_BIG_USE_LUCAS_SELFRIDGE_TEST :: #config(MATH_BIG_USE_LUCAS_SELFRIDGE_TEST, false)
  64. MATH_BIG_USE_FROBENIUS_TEST :: !MATH_BIG_USE_LUCAS_SELFRIDGE_TEST
  65. /*
  66. Runtime tunable to use Miller-Rabin primality testing only and skip the above.
  67. */
  68. USE_MILLER_RABIN_ONLY := false
  69. /*
  70. How many times we'll call `internal_int_random` during random prime generation before we bail out.
  71. Set to 0 or less to try indefinitely.
  72. */
  73. MAX_ITERATIONS_RANDOM_PRIME := 1_000_000
  74. /*
  75. How many iterations we used for the last random prime.
  76. */
  77. @thread_local RANDOM_PRIME_ITERATIONS_USED: int
  78. /*
  79. We don't allow these to be switched at runtime for two reasons:
  80. 1) 32-bit and 64-bit versions of procedures use different types for their storage,
  81. so we'd have to double the number of procedures, and they couldn't interact.
  82. 2) Optimizations thanks to precomputed masks wouldn't work.
  83. */
  84. MATH_BIG_FORCE_64_BIT :: #config(MATH_BIG_FORCE_64_BIT, false)
  85. MATH_BIG_FORCE_32_BIT :: #config(MATH_BIG_FORCE_32_BIT, false)
  86. when (MATH_BIG_FORCE_32_BIT && MATH_BIG_FORCE_64_BIT) { #panic("Cannot force 32-bit and 64-bit big backend simultaneously.") }
  87. /*
  88. Trade a smaller memory footprint for more processing overhead?
  89. */
  90. _LOW_MEMORY :: #config(MATH_BIG_SMALL_MEMORY, false)
  91. when _LOW_MEMORY {
  92. _DEFAULT_DIGIT_COUNT :: 8
  93. _TAB_SIZE :: 32
  94. _MAX_WIN_SIZE :: 5
  95. } else {
  96. _DEFAULT_DIGIT_COUNT :: 32
  97. _TAB_SIZE :: 256
  98. _MAX_WIN_SIZE :: 0
  99. }
  100. /*
  101. ======================= END OF TUNABLES =======================
  102. */
  103. Sign :: enum u8 {
  104. Zero_or_Positive = 0,
  105. Negative = 1,
  106. }
  107. Int :: struct {
  108. used: int,
  109. digit: [dynamic]DIGIT,
  110. sign: Sign,
  111. flags: Flags,
  112. }
  113. Flag :: enum u8 {
  114. NaN,
  115. Inf,
  116. Immutable,
  117. }
  118. Flags :: bit_set[Flag; u8]
  119. /*
  120. Errors are a strict superset of runtime.Allocation_Error.
  121. */
  122. Error :: enum int {
  123. Okay = 0,
  124. Out_Of_Memory = 1,
  125. Invalid_Pointer = 2,
  126. Invalid_Argument = 3,
  127. Assignment_To_Immutable = 4,
  128. Max_Iterations_Reached = 5,
  129. Buffer_Overflow = 6,
  130. Integer_Overflow = 7,
  131. Division_by_Zero = 8,
  132. Math_Domain_Error = 9,
  133. Cannot_Open_File = 50,
  134. Cannot_Read_File = 51,
  135. Cannot_Write_File = 52,
  136. Unimplemented = 127,
  137. }
  138. Error_String :: #partial [Error]string{
  139. .Okay = "Okay",
  140. .Out_Of_Memory = "Out of memory",
  141. .Invalid_Pointer = "Invalid pointer",
  142. .Invalid_Argument = "Invalid argument",
  143. .Assignment_To_Immutable = "Assignment to immutable",
  144. .Max_Iterations_Reached = "Max iterations reached",
  145. .Buffer_Overflow = "Buffer overflow",
  146. .Integer_Overflow = "Integer overflow",
  147. .Division_by_Zero = "Division by zero",
  148. .Math_Domain_Error = "Math domain error",
  149. .Cannot_Open_File = "Cannot_Open_File",
  150. .Cannot_Read_File = "Cannot_Read_File",
  151. .Cannot_Write_File = "Cannot_Write_File",
  152. .Unimplemented = "Unimplemented",
  153. }
  154. Primality_Flag :: enum u8 {
  155. Blum_Blum_Shub = 0, // Make prime congruent to 3 mod 4
  156. Safe = 1, // Make sure (p-1)/2 is prime as well (implies .Blum_Blum_Shub)
  157. Second_MSB_On = 3, // Make the 2nd highest bit one
  158. }
  159. Primality_Flags :: bit_set[Primality_Flag; u8]
  160. /*
  161. How do we store the Ints?
  162. Minimum number of available digits in `Int`, `_DEFAULT_DIGIT_COUNT` >= `_MIN_DIGIT_COUNT`
  163. - Must be at least 3 for `_div_school`.
  164. - Must be large enough such that `init_integer` can store `u128` in the `Int` without growing.
  165. */
  166. _MIN_DIGIT_COUNT :: max(3, ((size_of(u128) + _DIGIT_BITS) - 1) / _DIGIT_BITS)
  167. #assert(_DEFAULT_DIGIT_COUNT >= _MIN_DIGIT_COUNT)
  168. /*
  169. Maximum number of digits.
  170. - Must be small enough such that `_bit_count` does not overflow.
  171. - Must be small enough such that `_radix_size` for base 2 does not overflow.
  172. `_radix_size` needs two additional bytes for zero termination and sign.
  173. */
  174. _MAX_BIT_COUNT :: (max(int) - 2)
  175. _MAX_DIGIT_COUNT :: _MAX_BIT_COUNT / _DIGIT_BITS
  176. when MATH_BIG_FORCE_64_BIT || (!MATH_BIG_FORCE_32_BIT && size_of(rawptr) == 8) {
  177. /*
  178. We can use u128 as an intermediary.
  179. */
  180. DIGIT :: distinct u64
  181. _WORD :: distinct u128
  182. } else {
  183. DIGIT :: distinct u32
  184. _WORD :: distinct u64
  185. }
  186. #assert(size_of(_WORD) == 2 * size_of(DIGIT))
  187. _DIGIT_TYPE_BITS :: 8 * size_of(DIGIT)
  188. _WORD_TYPE_BITS :: 8 * size_of(_WORD)
  189. _DIGIT_NAILS :: 4
  190. _DIGIT_BITS :: _DIGIT_TYPE_BITS - _DIGIT_NAILS
  191. _WORD_BITS :: 2 * _DIGIT_BITS
  192. _MASK :: (DIGIT(1) << DIGIT(_DIGIT_BITS)) - DIGIT(1)
  193. _DIGIT_MAX :: _MASK
  194. _MAX_COMBA :: 1 << (_WORD_TYPE_BITS - (2 * _DIGIT_BITS))
  195. _WARRAY :: 1 << ((_WORD_TYPE_BITS - (2 * _DIGIT_BITS)) + 1)
  196. Order :: enum i8 {
  197. LSB_First = -1,
  198. MSB_First = 1,
  199. }
  200. Endianness :: enum i8 {
  201. Little = -1,
  202. Platform = 0,
  203. Big = 1,
  204. };