biginteger.h 8.1 KB

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