biginteger.h 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  1. // Tencent is pleased to support the open source community by making RapidJSON available.
  2. //
  3. // Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved.
  4. //
  5. // Licensed under the MIT License (the "License"); you may not use this file except
  6. // in compliance with the License. You may obtain a copy of the License at
  7. //
  8. // http://opensource.org/licenses/MIT
  9. //
  10. // Unless required by applicable law or agreed to in writing, software distributed
  11. // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
  12. // CONDITIONS OF ANY KIND, either express or implied. See the License for the
  13. // specific language governing permissions and limitations under the License.
  14. #ifndef RAPIDJSON_BIGINTEGER_H_
  15. #define RAPIDJSON_BIGINTEGER_H_
  16. #include "../rapidjson.h"
  17. #if defined(_MSC_VER) && defined(_M_AMD64)
  18. #include <intrin.h> // for _umul128
  19. #endif
  20. RAPIDJSON_NAMESPACE_BEGIN
  21. namespace internal {
  22. class BigInteger {
  23. public:
  24. typedef uint64_t Type;
  25. BigInteger(const BigInteger& rhs) : count_(rhs.count_) {
  26. std::memcpy(digits_, rhs.digits_, count_ * sizeof(Type));
  27. }
  28. explicit BigInteger(uint64_t u) : count_(1) {
  29. digits_[0] = u;
  30. }
  31. BigInteger(const char* decimals, size_t length) : count_(1) {
  32. RAPIDJSON_ASSERT(length > 0);
  33. digits_[0] = 0;
  34. size_t i = 0;
  35. const size_t kMaxDigitPerIteration = 19; // 2^64 = 18446744073709551616 > 10^19
  36. while (length >= kMaxDigitPerIteration) {
  37. AppendDecimal64(decimals + i, decimals + i + kMaxDigitPerIteration);
  38. length -= kMaxDigitPerIteration;
  39. i += kMaxDigitPerIteration;
  40. }
  41. if (length > 0)
  42. AppendDecimal64(decimals + i, decimals + i + length);
  43. }
  44. BigInteger& operator=(uint64_t u) {
  45. digits_[0] = u;
  46. count_ = 1;
  47. return *this;
  48. }
  49. BigInteger& operator+=(uint64_t u) {
  50. Type backup = digits_[0];
  51. digits_[0] += u;
  52. for (size_t i = 0; i < count_ - 1; i++) {
  53. if (digits_[i] >= backup)
  54. return *this; // no carry
  55. backup = digits_[i + 1];
  56. digits_[i + 1] += 1;
  57. }
  58. // Last carry
  59. if (digits_[count_ - 1] < backup)
  60. PushBack(1);
  61. return *this;
  62. }
  63. BigInteger& operator*=(uint64_t u) {
  64. if (u == 0) return *this = 0;
  65. if (u == 1) return *this;
  66. if (*this == 1) return *this = u;
  67. uint64_t k = 0;
  68. for (size_t i = 0; i < count_; i++) {
  69. uint64_t hi;
  70. digits_[i] = MulAdd64(digits_[i], u, k, &hi);
  71. k = hi;
  72. }
  73. if (k > 0)
  74. PushBack(k);
  75. return *this;
  76. }
  77. BigInteger& operator*=(uint32_t u) {
  78. if (u == 0) return *this = 0;
  79. if (u == 1) return *this;
  80. if (*this == 1) return *this = u;
  81. uint64_t k = 0;
  82. for (size_t i = 0; i < count_; i++) {
  83. const uint64_t c = digits_[i] >> 32;
  84. const uint64_t d = digits_[i] & 0xFFFFFFFF;
  85. const uint64_t uc = u * c;
  86. const uint64_t ud = u * d;
  87. const uint64_t p0 = ud + k;
  88. const uint64_t p1 = uc + (p0 >> 32);
  89. digits_[i] = (p0 & 0xFFFFFFFF) | (p1 << 32);
  90. k = p1 >> 32;
  91. }
  92. if (k > 0)
  93. PushBack(k);
  94. return *this;
  95. }
  96. BigInteger& operator<<=(size_t shift) {
  97. if (IsZero() || shift == 0) return *this;
  98. size_t offset = shift / kTypeBit;
  99. size_t interShift = shift % kTypeBit;
  100. RAPIDJSON_ASSERT(count_ + offset <= kCapacity);
  101. if (interShift == 0) {
  102. std::memmove(&digits_[count_ - 1 + offset], &digits_[count_ - 1], count_ * sizeof(Type));
  103. count_ += offset;
  104. }
  105. else {
  106. digits_[count_] = 0;
  107. for (size_t i = count_; i > 0; i--)
  108. digits_[i + offset] = (digits_[i] << interShift) | (digits_[i - 1] >> (kTypeBit - interShift));
  109. digits_[offset] = digits_[0] << interShift;
  110. count_ += offset;
  111. if (digits_[count_])
  112. count_++;
  113. }
  114. std::memset(digits_, 0, offset * sizeof(Type));
  115. return *this;
  116. }
  117. bool operator==(const BigInteger& rhs) const {
  118. return count_ == rhs.count_ && std::memcmp(digits_, rhs.digits_, count_ * sizeof(Type)) == 0;
  119. }
  120. bool operator==(const Type rhs) const {
  121. return count_ == 1 && digits_[0] == rhs;
  122. }
  123. BigInteger& MultiplyPow5(unsigned exp) {
  124. static const uint32_t kPow5[12] = {
  125. 5,
  126. 5 * 5,
  127. 5 * 5 * 5,
  128. 5 * 5 * 5 * 5,
  129. 5 * 5 * 5 * 5 * 5,
  130. 5 * 5 * 5 * 5 * 5 * 5,
  131. 5 * 5 * 5 * 5 * 5 * 5 * 5,
  132. 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5,
  133. 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5,
  134. 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5,
  135. 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5,
  136. 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5
  137. };
  138. if (exp == 0) return *this;
  139. for (; exp >= 27; exp -= 27) *this *= RAPIDJSON_UINT64_C2(0X6765C793, 0XFA10079D); // 5^27
  140. for (; exp >= 13; exp -= 13) *this *= static_cast<uint32_t>(1220703125u); // 5^13
  141. if (exp > 0) *this *= kPow5[exp - 1];
  142. return *this;
  143. }
  144. // Compute absolute difference of this and rhs.
  145. // Assume this != rhs
  146. bool Difference(const BigInteger& rhs, BigInteger* out) const {
  147. int cmp = Compare(rhs);
  148. RAPIDJSON_ASSERT(cmp != 0);
  149. const BigInteger *a, *b; // Makes a > b
  150. bool ret;
  151. if (cmp < 0) { a = &rhs; b = this; ret = true; }
  152. else { a = this; b = &rhs; ret = false; }
  153. Type borrow = 0;
  154. for (size_t i = 0; i < a->count_; i++) {
  155. Type d = a->digits_[i] - borrow;
  156. if (i < b->count_)
  157. d -= b->digits_[i];
  158. borrow = (d > a->digits_[i]) ? 1 : 0;
  159. out->digits_[i] = d;
  160. if (d != 0)
  161. out->count_ = i + 1;
  162. }
  163. return ret;
  164. }
  165. int Compare(const BigInteger& rhs) const {
  166. if (count_ != rhs.count_)
  167. return count_ < rhs.count_ ? -1 : 1;
  168. for (size_t i = count_; i-- > 0;)
  169. if (digits_[i] != rhs.digits_[i])
  170. return digits_[i] < rhs.digits_[i] ? -1 : 1;
  171. return 0;
  172. }
  173. size_t GetCount() const { return count_; }
  174. Type GetDigit(size_t index) const { RAPIDJSON_ASSERT(index < count_); return digits_[index]; }
  175. bool IsZero() const { return count_ == 1 && digits_[0] == 0; }
  176. private:
  177. void AppendDecimal64(const char* begin, const char* end) {
  178. uint64_t u = ParseUint64(begin, end);
  179. if (IsZero())
  180. *this = u;
  181. else {
  182. unsigned exp = static_cast<unsigned>(end - begin);
  183. (MultiplyPow5(exp) <<= exp) += u; // *this = *this * 10^exp + u
  184. }
  185. }
  186. void PushBack(Type digit) {
  187. RAPIDJSON_ASSERT(count_ < kCapacity);
  188. digits_[count_++] = digit;
  189. }
  190. static uint64_t ParseUint64(const char* begin, const char* end) {
  191. uint64_t r = 0;
  192. for (const char* p = begin; p != end; ++p) {
  193. RAPIDJSON_ASSERT(*p >= '0' && *p <= '9');
  194. r = r * 10 + (*p - '0');
  195. }
  196. return r;
  197. }
  198. // Assume a * b + k < 2^128
  199. static uint64_t MulAdd64(uint64_t a, uint64_t b, uint64_t k, uint64_t* outHigh) {
  200. #if defined(_MSC_VER) && defined(_M_AMD64)
  201. uint64_t low = _umul128(a, b, outHigh) + k;
  202. if (low < k)
  203. (*outHigh)++;
  204. return low;
  205. #elif (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)) && defined(__x86_64__)
  206. __extension__ typedef unsigned __int128 uint128;
  207. uint128 p = static_cast<uint128>(a) * static_cast<uint128>(b);
  208. p += k;
  209. *outHigh = static_cast<uint64_t>(p >> 64);
  210. return static_cast<uint64_t>(p);
  211. #else
  212. const uint64_t a0 = a & 0xFFFFFFFF, a1 = a >> 32, b0 = b & 0xFFFFFFFF, b1 = b >> 32;
  213. uint64_t x0 = a0 * b0, x1 = a0 * b1, x2 = a1 * b0, x3 = a1 * b1;
  214. x1 += (x0 >> 32); // can't give carry
  215. x1 += x2;
  216. if (x1 < x2)
  217. x3 += (static_cast<uint64_t>(1) << 32);
  218. uint64_t lo = (x1 << 32) + (x0 & 0xFFFFFFFF);
  219. uint64_t hi = x3 + (x1 >> 32);
  220. lo += k;
  221. if (lo < k)
  222. hi++;
  223. *outHigh = hi;
  224. return lo;
  225. #endif
  226. }
  227. static const size_t kBitCount = 3328; // 64bit * 54 > 10^1000
  228. static const size_t kCapacity = kBitCount / sizeof(Type);
  229. static const size_t kTypeBit = sizeof(Type) * 8;
  230. Type digits_[kCapacity];
  231. size_t count_;
  232. };
  233. } // namespace internal
  234. RAPIDJSON_NAMESPACE_END
  235. #endif // RAPIDJSON_BIGINTEGER_H_