common.odin 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  1. package math_big
  2. /*
  3. Copyright 2021 Jeroen van Rijn <[email protected]>.
  4. Made available under Odin's BSD-3 license.
  5. An arbitrary precision mathematics implementation in Odin.
  6. For the theoretical underpinnings, see Knuth's The Art of Computer Programming, Volume 2, section 4.3.
  7. The code started out as an idiomatic source port of libTomMath, which is in the public domain, with thanks.
  8. */
  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(MUL_KARATSUBA_CUTOFF, 80);
  46. _DEFAULT_SQR_KARATSUBA_CUTOFF :: #config(SQR_KARATSUBA_CUTOFF, 120);
  47. _DEFAULT_MUL_TOOM_CUTOFF :: #config(MUL_TOOM_CUTOFF, 350);
  48. _DEFAULT_SQR_TOOM_CUTOFF :: #config(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. We don't allow these to be switched at runtime for two reasons:
  61. 1) 32-bit and 64-bit versions of procedures use different types for their storage,
  62. so we'd have to double the number of procedures, and they couldn't interact.
  63. 2) Optimizations thanks to precomputed masks wouldn't work.
  64. */
  65. MATH_BIG_FORCE_64_BIT :: #config(MATH_BIG_FORCE_64_BIT, false);
  66. MATH_BIG_FORCE_32_BIT :: #config(MATH_BIG_FORCE_32_BIT, false);
  67. when (MATH_BIG_FORCE_32_BIT && MATH_BIG_FORCE_64_BIT) { #panic("Cannot force 32-bit and 64-bit big backend simultaneously."); };
  68. _LOW_MEMORY :: #config(BIGINT_SMALL_MEMORY, false);
  69. when _LOW_MEMORY {
  70. _DEFAULT_DIGIT_COUNT :: 8;
  71. } else {
  72. _DEFAULT_DIGIT_COUNT :: 32;
  73. }
  74. /*
  75. ======================= END OF TUNABLES =======================
  76. */
  77. Sign :: enum u8 {
  78. Zero_or_Positive = 0,
  79. Negative = 1,
  80. };
  81. Int :: struct {
  82. used: int,
  83. digit: [dynamic]DIGIT,
  84. sign: Sign,
  85. flags: Flags,
  86. };
  87. Flag :: enum u8 {
  88. NaN,
  89. Inf,
  90. Immutable,
  91. };
  92. Flags :: bit_set[Flag; u8];
  93. /*
  94. Errors are a strict superset of runtime.Allocation_Error.
  95. */
  96. Error :: enum int {
  97. Okay = 0,
  98. Out_Of_Memory = 1,
  99. Invalid_Pointer = 2,
  100. Invalid_Argument = 3,
  101. Assignment_To_Immutable = 4,
  102. Max_Iterations_Reached = 5,
  103. Buffer_Overflow = 6,
  104. Integer_Overflow = 7,
  105. Division_by_Zero = 8,
  106. Math_Domain_Error = 9,
  107. Unimplemented = 127,
  108. };
  109. Error_String :: #partial [Error]string{
  110. .Out_Of_Memory = "Out of memory",
  111. .Invalid_Pointer = "Invalid pointer",
  112. .Invalid_Argument = "Invalid argument",
  113. .Assignment_To_Immutable = "Assignment to immutable",
  114. .Max_Iterations_Reached = "Max iterations reached",
  115. .Buffer_Overflow = "Buffer overflow",
  116. .Integer_Overflow = "Integer overflow",
  117. .Division_by_Zero = "Division by zero",
  118. .Math_Domain_Error = "Math domain error",
  119. .Unimplemented = "Unimplemented",
  120. };
  121. Primality_Flag :: enum u8 {
  122. Blum_Blum_Shub = 0, /* BBS style prime */
  123. Safe = 1, /* Safe prime (p-1)/2 == prime */
  124. Second_MSB_On = 3, /* force 2nd MSB to 1 */
  125. };
  126. Primality_Flags :: bit_set[Primality_Flag; u8];
  127. /*
  128. How do we store the Ints?
  129. Minimum number of available digits in `Int`, `_DEFAULT_DIGIT_COUNT` >= `_MIN_DIGIT_COUNT`
  130. - Must be at least 3 for `_div_school`.
  131. - Must be large enough such that `init_integer` can store `u128` in the `Int` without growing.
  132. */
  133. _MIN_DIGIT_COUNT :: max(3, ((size_of(u128) + _DIGIT_BITS) - 1) / _DIGIT_BITS);
  134. #assert(_DEFAULT_DIGIT_COUNT >= _MIN_DIGIT_COUNT);
  135. /*
  136. Maximum number of digits.
  137. - Must be small enough such that `_bit_count` does not overflow.
  138. - Must be small enough such that `_radix_size` for base 2 does not overflow.
  139. `_radix_size` needs two additional bytes for zero termination and sign.
  140. */
  141. _MAX_BIT_COUNT :: (max(int) - 2);
  142. _MAX_DIGIT_COUNT :: _MAX_BIT_COUNT / _DIGIT_BITS;
  143. when MATH_BIG_FORCE_64_BIT || (!MATH_BIG_FORCE_32_BIT && size_of(rawptr) == 8) {
  144. /*
  145. We can use u128 as an intermediary.
  146. */
  147. DIGIT :: distinct u64;
  148. _WORD :: distinct u128;
  149. } else {
  150. DIGIT :: distinct u32;
  151. _WORD :: distinct u64;
  152. }
  153. #assert(size_of(_WORD) == 2 * size_of(DIGIT));
  154. _DIGIT_TYPE_BITS :: 8 * size_of(DIGIT);
  155. _WORD_TYPE_BITS :: 8 * size_of(_WORD);
  156. _DIGIT_BITS :: _DIGIT_TYPE_BITS - 4;
  157. _WORD_BITS :: 2 * _DIGIT_BITS;
  158. _MASK :: (DIGIT(1) << DIGIT(_DIGIT_BITS)) - DIGIT(1);
  159. _DIGIT_MAX :: _MASK;
  160. _MAX_COMBA :: 1 << (_WORD_TYPE_BITS - (2 * _DIGIT_BITS)) ;
  161. _WARRAY :: 1 << ((_WORD_TYPE_BITS - (2 * _DIGIT_BITS)) + 1);
  162. Order :: enum i8 {
  163. LSB_First = -1,
  164. MSB_First = 1,
  165. };
  166. Endianness :: enum i8 {
  167. Little = -1,
  168. Platform = 0,
  169. Big = 1,
  170. };