biginteger.h 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  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) && !__INTEL_COMPILER && defined(_M_AMD64)
  18. #include <intrin.h> // for _umul128
  19. #pragma intrinsic(_umul128)
  20. #endif
  21. RAPIDJSON_NAMESPACE_BEGIN
  22. namespace internal {
  23. class BigInteger {
  24. public:
  25. typedef uint64_t Type;
  26. BigInteger(const BigInteger& rhs) : count_(rhs.count_) {
  27. std::memcpy(digits_, rhs.digits_, count_ * sizeof(Type));
  28. }
  29. explicit BigInteger(uint64_t u) : count_(1) {
  30. digits_[0] = u;
  31. }
  32. BigInteger(const char* decimals, size_t length) : count_(1) {
  33. RAPIDJSON_ASSERT(length > 0);
  34. digits_[0] = 0;
  35. size_t i = 0;
  36. const size_t kMaxDigitPerIteration = 19; // 2^64 = 18446744073709551616 > 10^19
  37. while (length >= kMaxDigitPerIteration) {
  38. AppendDecimal64(decimals + i, decimals + i + kMaxDigitPerIteration);
  39. length -= kMaxDigitPerIteration;
  40. i += kMaxDigitPerIteration;
  41. }
  42. if (length > 0)
  43. AppendDecimal64(decimals + i, decimals + i + length);
  44. }
  45. BigInteger& operator=(const BigInteger &rhs)
  46. {
  47. if (this != &rhs) {
  48. count_ = rhs.count_;
  49. std::memcpy(digits_, rhs.digits_, count_ * sizeof(Type));
  50. }
  51. return *this;
  52. }
  53. BigInteger& operator=(uint64_t u) {
  54. digits_[0] = u;
  55. count_ = 1;
  56. return *this;
  57. }
  58. BigInteger& operator+=(uint64_t u) {
  59. Type backup = digits_[0];
  60. digits_[0] += u;
  61. for (size_t i = 0; i < count_ - 1; i++) {
  62. if (digits_[i] >= backup)
  63. return *this; // no carry
  64. backup = digits_[i + 1];
  65. digits_[i + 1] += 1;
  66. }
  67. // Last carry
  68. if (digits_[count_ - 1] < backup)
  69. PushBack(1);
  70. return *this;
  71. }
  72. BigInteger& operator*=(uint64_t u) {
  73. if (u == 0) return *this = 0;
  74. if (u == 1) return *this;
  75. if (*this == 1) return *this = u;
  76. uint64_t k = 0;
  77. for (size_t i = 0; i < count_; i++) {
  78. uint64_t hi;
  79. digits_[i] = MulAdd64(digits_[i], u, k, &hi);
  80. k = hi;
  81. }
  82. if (k > 0)
  83. PushBack(k);
  84. return *this;
  85. }
  86. BigInteger& operator*=(uint32_t u) {
  87. if (u == 0) return *this = 0;
  88. if (u == 1) return *this;
  89. if (*this == 1) return *this = u;
  90. uint64_t k = 0;
  91. for (size_t i = 0; i < count_; i++) {
  92. const uint64_t c = digits_[i] >> 32;
  93. const uint64_t d = digits_[i] & 0xFFFFFFFF;
  94. const uint64_t uc = u * c;
  95. const uint64_t ud = u * d;
  96. const uint64_t p0 = ud + k;
  97. const uint64_t p1 = uc + (p0 >> 32);
  98. digits_[i] = (p0 & 0xFFFFFFFF) | (p1 << 32);
  99. k = p1 >> 32;
  100. }
  101. if (k > 0)
  102. PushBack(k);
  103. return *this;
  104. }
  105. BigInteger& operator<<=(size_t shift) {
  106. if (IsZero() || shift == 0) return *this;
  107. size_t offset = shift / kTypeBit;
  108. size_t interShift = shift % kTypeBit;
  109. RAPIDJSON_ASSERT(count_ + offset <= kCapacity);
  110. if (interShift == 0) {
  111. std::memmove(digits_ + offset, digits_, count_ * sizeof(Type));
  112. count_ += offset;
  113. }
  114. else {
  115. digits_[count_] = 0;
  116. for (size_t i = count_; i > 0; i--)
  117. digits_[i + offset] = (digits_[i] << interShift) | (digits_[i - 1] >> (kTypeBit - interShift));
  118. digits_[offset] = digits_[0] << interShift;
  119. count_ += offset;
  120. if (digits_[count_])
  121. count_++;
  122. }
  123. std::memset(digits_, 0, offset * sizeof(Type));
  124. return *this;
  125. }
  126. bool operator==(const BigInteger& rhs) const {
  127. return count_ == rhs.count_ && std::memcmp(digits_, rhs.digits_, count_ * sizeof(Type)) == 0;
  128. }
  129. bool operator==(const Type rhs) const {
  130. return count_ == 1 && digits_[0] == rhs;
  131. }
  132. BigInteger& MultiplyPow5(unsigned exp) {
  133. static const uint32_t kPow5[12] = {
  134. 5,
  135. 5 * 5,
  136. 5 * 5 * 5,
  137. 5 * 5 * 5 * 5,
  138. 5 * 5 * 5 * 5 * 5,
  139. 5 * 5 * 5 * 5 * 5 * 5,
  140. 5 * 5 * 5 * 5 * 5 * 5 * 5,
  141. 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5,
  142. 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5,
  143. 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5,
  144. 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5,
  145. 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5
  146. };
  147. if (exp == 0) return *this;
  148. for (; exp >= 27; exp -= 27) *this *= RAPIDJSON_UINT64_C2(0X6765C793, 0XFA10079D); // 5^27
  149. for (; exp >= 13; exp -= 13) *this *= static_cast<uint32_t>(1220703125u); // 5^13
  150. if (exp > 0) *this *= kPow5[exp - 1];
  151. return *this;
  152. }
  153. // Compute absolute difference of this and rhs.
  154. // Assume this != rhs
  155. bool Difference(const BigInteger& rhs, BigInteger* out) const {
  156. int cmp = Compare(rhs);
  157. RAPIDJSON_ASSERT(cmp != 0);
  158. const BigInteger *a, *b; // Makes a > b
  159. bool ret;
  160. if (cmp < 0) { a = &rhs; b = this; ret = true; }
  161. else { a = this; b = &rhs; ret = false; }
  162. Type borrow = 0;
  163. for (size_t i = 0; i < a->count_; i++) {
  164. Type d = a->digits_[i] - borrow;
  165. if (i < b->count_)
  166. d -= b->digits_[i];
  167. borrow = (d > a->digits_[i]) ? 1 : 0;
  168. out->digits_[i] = d;
  169. if (d != 0)
  170. out->count_ = i + 1;
  171. }
  172. return ret;
  173. }
  174. int Compare(const BigInteger& rhs) const {
  175. if (count_ != rhs.count_)
  176. return count_ < rhs.count_ ? -1 : 1;
  177. for (size_t i = count_; i-- > 0;)
  178. if (digits_[i] != rhs.digits_[i])
  179. return digits_[i] < rhs.digits_[i] ? -1 : 1;
  180. return 0;
  181. }
  182. size_t GetCount() const { return count_; }
  183. Type GetDigit(size_t index) const { RAPIDJSON_ASSERT(index < count_); return digits_[index]; }
  184. bool IsZero() const { return count_ == 1 && digits_[0] == 0; }
  185. private:
  186. void AppendDecimal64(const char* begin, const char* end) {
  187. uint64_t u = ParseUint64(begin, end);
  188. if (IsZero())
  189. *this = u;
  190. else {
  191. unsigned exp = static_cast<unsigned>(end - begin);
  192. (MultiplyPow5(exp) <<= exp) += u; // *this = *this * 10^exp + u
  193. }
  194. }
  195. void PushBack(Type digit) {
  196. RAPIDJSON_ASSERT(count_ < kCapacity);
  197. digits_[count_++] = digit;
  198. }
  199. static uint64_t ParseUint64(const char* begin, const char* end) {
  200. uint64_t r = 0;
  201. for (const char* p = begin; p != end; ++p) {
  202. RAPIDJSON_ASSERT(*p >= '0' && *p <= '9');
  203. r = r * 10u + static_cast<unsigned>(*p - '0');
  204. }
  205. return r;
  206. }
  207. // Assume a * b + k < 2^128
  208. static uint64_t MulAdd64(uint64_t a, uint64_t b, uint64_t k, uint64_t* outHigh) {
  209. #if defined(_MSC_VER) && defined(_M_AMD64)
  210. uint64_t low = _umul128(a, b, outHigh) + k;
  211. if (low < k)
  212. (*outHigh)++;
  213. return low;
  214. #elif (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)) && defined(__x86_64__)
  215. __extension__ typedef unsigned __int128 uint128;
  216. uint128 p = static_cast<uint128>(a) * static_cast<uint128>(b);
  217. p += k;
  218. *outHigh = static_cast<uint64_t>(p >> 64);
  219. return static_cast<uint64_t>(p);
  220. #else
  221. const uint64_t a0 = a & 0xFFFFFFFF, a1 = a >> 32, b0 = b & 0xFFFFFFFF, b1 = b >> 32;
  222. uint64_t x0 = a0 * b0, x1 = a0 * b1, x2 = a1 * b0, x3 = a1 * b1;
  223. x1 += (x0 >> 32); // can't give carry
  224. x1 += x2;
  225. if (x1 < x2)
  226. x3 += (static_cast<uint64_t>(1) << 32);
  227. uint64_t lo = (x1 << 32) + (x0 & 0xFFFFFFFF);
  228. uint64_t hi = x3 + (x1 >> 32);
  229. lo += k;
  230. if (lo < k)
  231. hi++;
  232. *outHigh = hi;
  233. return lo;
  234. #endif
  235. }
  236. static const size_t kBitCount = 3328; // 64bit * 54 > 10^1000
  237. static const size_t kCapacity = kBitCount / sizeof(Type);
  238. static const size_t kTypeBit = sizeof(Type) * 8;
  239. Type digits_[kCapacity];
  240. size_t count_;
  241. };
  242. } // namespace internal
  243. RAPIDJSON_NAMESPACE_END
  244. #endif // RAPIDJSON_BIGINTEGER_H_