├── BigInt.hpp ├── BigInt ├── BigIntInput.hpp └── BigIntOutput.hpp ├── BigNum.hpp ├── LICENSE.BSD3c ├── LICENSE.GPLv2 ├── LICENSE.LGPLv3 ├── LICENSE.MIT ├── Libs ├── BigNumFFT.hpp ├── BigNumGenerics.hpp ├── BigNumMemory.hpp ├── BigNumModularRing.hpp └── BigNumTypeTrait.hpp └── README.md /BigInt/BigIntInput.hpp: -------------------------------------------------------------------------------- 1 | #ifndef _BIG_NUM_HPP_ 2 | #error "This header must be included through BigNum.hpp" 3 | #endif // _BIG_NUM_HPP_ 4 | 5 | #ifndef _BIG_INT_INPUT_HPP_ 6 | #define _BIG_INT_INPUT_HPP_ 7 | 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include 15 | #include 16 | #include 17 | 18 | #include "../Libs/BigNumTypeTrait.hpp" 19 | #include "../Libs/BigNumMemory.hpp" 20 | #include "../Libs/BigNumGenerics.hpp" 21 | 22 | namespace bignum{ 23 | 24 | template 25 | class _GenericAutomatic; 26 | template 27 | class _DecimalAutomatic; 28 | template 29 | class _SmallPower2RadixAutomatic; 30 | template 31 | class _ExactDigitAutomatic; 32 | template 33 | class _LargePower2RadixAutomatic; 34 | 35 | namespace _type{ 36 | 37 | template 38 | class DigitReceiver{ 39 | public: 40 | //virtual DigitReceiver *clone() const = 0; 41 | virtual void _readDigit(Digit) = 0; 42 | virtual BI _finish() && = 0; 43 | virtual BI _finish() const & = 0; 44 | 45 | virtual ~DigitReceiver(){} 46 | }; 47 | 48 | template 49 | class DigitReceiverCRTP:public DigitReceiver{ 50 | public: 51 | /*virtual DigitReceiver *clone() const{ 52 | return new Derived(static_cast(*this)); 53 | }*/ 54 | }; 55 | 56 | // uses an ostream-iterator-like prototype 57 | template 58 | class DigitRecvIterator 59 | :public std::iterator< 60 | std::output_iterator_tag, // iterator_category 61 | void, // value_type 62 | void, // difference_type 63 | void, // pointer 64 | void>{ // reference 65 | public: 66 | using iterator_category = std::output_iterator_tag; 67 | using value_type = void; 68 | using difference_type = void; 69 | using pointer = void; 70 | using reference = void; 71 | private: 72 | using Receiver = DigitReceiver; 73 | 74 | using SizeT = typename BI::SizeT; 75 | using LogSizeT = typename BI::LogSizeT; 76 | 77 | constexpr static LogSizeT ENTRY_SIZE = BI::ENTRY_SIZE; 78 | public: 79 | template 80 | explicit DigitRecvIterator(Derived *_receiver) 81 | :receiver(_receiver){} 82 | 83 | DigitRecvIterator(const DigitRecvIterator &) = default; 84 | DigitRecvIterator(DigitRecvIterator &&) = default; 85 | 86 | DigitRecvIterator(Digit radix):receiver(nullptr){ 87 | if(radix == 10){ 88 | receiver = std::make_shared<_DecimalAutomatic>(); 89 | return ; 90 | } 91 | if((radix & ((~radix) + 1)) == radix){ 92 | SizeT exp = static_cast(std::ceil(std::log2(radix))); 93 | if(exp < ENTRY_SIZE){ 94 | receiver = std::make_shared<_SmallPower2RadixAutomatic>(exp); 96 | return ; 97 | } 98 | if(exp == ENTRY_SIZE){ 99 | receiver = std::make_shared<_ExactDigitAutomatic>(exp); 101 | return ; 102 | } 103 | if(exp > ENTRY_SIZE){ 104 | receiver = std::make_shared<_LargePower2RadixAutomatic>(exp); 106 | return ; 107 | } 108 | } 109 | receiver = std::make_shared<_GenericAutomatic>(radix); 110 | } 111 | 112 | DigitRecvIterator &operator=(const DigitRecvIterator &) = default; 113 | DigitRecvIterator &operator=(DigitRecvIterator &&) = default; 114 | 115 | ~DigitRecvIterator() = default; 116 | 117 | DigitRecvIterator &operator=(Digit digit){ 118 | receiver->_readDigit(digit); 119 | return *this; 120 | } 121 | 122 | DigitRecvIterator &operator*() noexcept{ 123 | return *this; 124 | } 125 | 126 | DigitRecvIterator &operator++() noexcept{ 127 | return *this; 128 | } 129 | 130 | DigitRecvIterator &operator++(int) noexcept{ 131 | return *this; 132 | } 133 | private: 134 | std::shared_ptr receiver; 135 | }; 136 | 137 | }; // namespace _type 138 | 139 | using _type::isSigned; 140 | 141 | template 142 | class _ThousandSepParser{ 143 | private: 144 | using Stream = std::basic_istream; 145 | using Tr = typename Stream::traits_type; 146 | using Int = typename Stream::int_type; 147 | 148 | using Finder = _utility::CharFindHelper; 149 | public: 150 | _ThousandSepParser(const _ThousandSepParser &) = delete; 151 | _ThousandSepParser(_ThousandSepParser &&) = delete; 152 | 153 | explicit _ThousandSepParser(Stream &_is, const Char *_digit, const Char *_digitend, 154 | const std::ctype &_cF, const std::numpunct &_npF) 155 | :is(_is), ctypeFacet(_cF), npFacet(_npF), digit(_digit), digitend(_digitend), 156 | gp(npFacet.grouping()), firstGpLen(0), gpCnt(0), curGpIdx(gp.size()){} 157 | 158 | _ThousandSepParser &operator=(const _ThousandSepParser &) = delete; 159 | _ThousandSepParser &operator=(_ThousandSepParser &&) = delete; 160 | 161 | ~_ThousandSepParser() = default; 162 | 163 | const Char *checkInput(Int _ch){ 164 | if(Tr::eq_int_type(Tr::eof(), _ch)){ 165 | is.setstate(std::ios_base::eofbit); 166 | return digitend; 167 | } 168 | 169 | const Char *ptr = Finder::find(digit, digitend, _ch); 170 | if((ptr >= digit) && (ptr < digitend)){ 171 | ++gpCnt; 172 | return ptr; 173 | } 174 | if(ctypeFacet.is(std::ctype::space, Tr::to_char_type(_ch))){ 175 | if(!gp.empty()){ 176 | if(firstGpLen == 0){ 177 | if(firstGpLen > gp[gp.size() - 1]){ 178 | is.setstate(std::ios_base::failbit); 179 | return nullptr; 180 | } 181 | return digitend; 182 | } 183 | bool flag = true; 184 | if(gpCnt != gp[gp.size() - 1]){ 185 | flag = false; 186 | } 187 | if(gp.size() > 1){ 188 | if(curGpIdx + 1 != gp.size() - 1){ 189 | flag = false; 190 | } 191 | } 192 | if(!flag){ 193 | is.setstate(std::ios_base::failbit); 194 | return nullptr; 195 | } 196 | } 197 | return digitend; 198 | } 199 | if(Tr::eq_int_type(Tr::to_int_type(npFacet.thousands_sep()), _ch)){ 200 | if(gp.empty()){ 201 | is.setstate(std::ios_base::failbit); 202 | return nullptr; 203 | } 204 | if(gpCnt == 0){ 205 | // ",," or ",......" 206 | is.setstate(std::ios_base::failbit); 207 | return nullptr; 208 | } 209 | if(firstGpLen != 0){ 210 | if(curGpIdx == gp.size()){ 211 | if(firstGpLen > gpCnt){ 212 | is.setstate(std::ios_base::failbit); 213 | return nullptr; 214 | } 215 | curGpIdx = gp.find(gpCnt); 216 | if(curGpIdx == std::string::npos){ 217 | is.setstate(std::ios_base::failbit); 218 | return nullptr; 219 | } 220 | } 221 | else{ 222 | if(curGpIdx == 0){ 223 | bool flag = gp[0] == gpCnt; 224 | if(gp.size() > 1){ 225 | if(gp[1] == gpCnt){ 226 | flag = true; 227 | curGpIdx = 1; 228 | } 229 | } 230 | if(!flag){ 231 | is.setstate(std::ios_base::failbit); 232 | return nullptr; 233 | } 234 | } 235 | else{ 236 | if(curGpIdx + 1 == gp.size()){ 237 | is.setstate(std::ios_base::failbit); 238 | return nullptr; 239 | } 240 | if(gp[curGpIdx + 1] != gpCnt){ 241 | is.setstate(std::ios_base::failbit); 242 | return nullptr; 243 | } 244 | ++curGpIdx; 245 | } 246 | } 247 | } 248 | else{ 249 | firstGpLen = gpCnt; 250 | curGpIdx = 0; 251 | } 252 | return digitend; 253 | } 254 | is.setstate(std::ios_base::failbit); 255 | return nullptr; 256 | } 257 | 258 | const Char *tryNextDigit(){ 259 | Int _ch = is.peek(); 260 | const Char *digitPtr = checkInput(_ch); 261 | while((digitPtr < digit) || (digitPtr > digitend)){ 262 | if(digitPtr == nullptr){ 263 | return nullptr; 264 | } 265 | if(!is){ 266 | return digitPtr; 267 | } 268 | is.ignore(); 269 | _ch = is.peek(); 270 | digitPtr = checkInput(_ch); 271 | } 272 | is.ignore(); 273 | return digitPtr; 274 | } 275 | private: 276 | Stream &is; 277 | const std::ctype &ctypeFacet; 278 | const std::numpunct &npFacet; 279 | const Char *digit, *digitend; 280 | 281 | std::string gp; 282 | char firstGpLen, gpCnt; 283 | std::string::size_type curGpIdx; 284 | }; 285 | 286 | using _type::DigitReceiverCRTP; 287 | 288 | template 289 | class _GenericAutomatic 290 | :public DigitReceiverCRTP>{ 291 | private: 292 | using SizeT = Diff; 293 | using VSize = typename std::vector::size_type; 294 | public: 295 | explicit _GenericAutomatic(Digit _radix) 296 | :count(0), baseCap(0), radix(_radix){} 297 | 298 | _GenericAutomatic(const _GenericAutomatic &) = delete; 299 | _GenericAutomatic(_GenericAutomatic &&) = delete; 300 | 301 | _GenericAutomatic &operator=(const _GenericAutomatic &) = delete; 302 | _GenericAutomatic &operator=(_GenericAutomatic &&) = delete; 303 | 304 | ~_GenericAutomatic() = default; 305 | 306 | void _readDigit(Digit digit){ 307 | asset(digit < radix); 308 | 309 | numStack.emplace_back(digit); 310 | ++count; 311 | SizeT _lowbit = count & ((~count) + 1); 312 | VSize i = 0; 313 | for(;(1 << i) < _lowbit;++i){ 314 | assert(numStack.size() >= 2); 315 | BI top1 = std::move(numStack.back()); 316 | numStack.pop_back(); 317 | 318 | assert(i <= base.size()); 319 | if(i == base.size()){ 320 | if(i == 0){ 321 | base.emplace_back(radix); 322 | } 323 | else{ 324 | BI next = base.back(); 325 | next.selfMultiply(); 326 | base.push_back(std::move(next)); 327 | } 328 | } 329 | numStack.back().multiplyMedium(base[i]); 330 | numStack.back().add(std::move(top1)); 331 | } 332 | 333 | if(baseCap + 1 < i){ 334 | baseCap = i - 1; 335 | } 336 | } 337 | 338 | BI _finish() &&{ 339 | if(numStack.empty()){ 340 | return BI(static_cast(0)); 341 | } 342 | 343 | BI res = std::move(numStack.front()); 344 | numStack.pop_front(); 345 | if(numStack.empty()){ 346 | return res; 347 | } 348 | 349 | VSize i = baseCap; 350 | //assert((count & (1 << i)) != 0); 351 | SizeT _lowbit = count & ((~count) + 1); 352 | assert(_lowbit > 0); 353 | assert(_lowbit < count); 354 | assert((1 << i) < count); 355 | for(SizeT mask = (1 << i);mask >= _lowbit;mask >>= 1, --i){ 356 | assert(!numStack.empty()); 357 | if((mask & count) == 0){ 358 | continue; 359 | } 360 | res.multiply(base[i]); 361 | res.add(std::move(numStack.front())); 362 | numStack.pop_front(); 363 | } 364 | assert(numStack.empty()); 365 | return res; 366 | } 367 | BI _finish() const &{ 368 | if(numStack.empty()){ 369 | return BI(static_cast(0)); 370 | } 371 | 372 | using ConstIter = typename std::deque::const_iterator; 373 | ConstIter iter = numStack.cbegin(); 374 | BI res = *iter; 375 | ++iter; 376 | if(iter == numStack.cend()){ 377 | return res; 378 | } 379 | 380 | VSize i = baseCap; 381 | SizeT _lowbit = count & ((~count) + 1); 382 | assert(_lowbit > 0); 383 | assert(_lowbit < count); 384 | assert((1 << i) < count); 385 | for(SizeT mask = (1 << i);mask >= _lowbit;mask >>= 1, --i){ 386 | assert(iter != numStack.end()); 387 | if((mask & count) == 0){ 388 | continue; 389 | } 390 | res.multiply(base[i]); 391 | res.add(*iter); 392 | ++iter; 393 | } 394 | assert(iter == numStack.end()); 395 | return res; 396 | } 397 | private: 398 | std::vector base; 399 | std::deque numStack; 400 | 401 | SizeT count; 402 | VSize baseCap; 403 | 404 | Digit radix; 405 | }; 406 | 407 | template 408 | class _DecimalAutomatic 409 | :public DigitReceiverCRTP>{ 410 | private: 411 | using SizeT = Diff; 412 | using VSize = typename std::vector::size_type; 413 | 414 | constexpr static Digit radix = 10; 415 | public: 416 | explicit _DecimalAutomatic() 417 | :decimalBase(BI::getDecimalBase()), count(0), baseCap(0){} 418 | 419 | _DecimalAutomatic(const _DecimalAutomatic &) = delete; 420 | _DecimalAutomatic(_DecimalAutomatic &&) = delete; 421 | 422 | _DecimalAutomatic &operator=(const _DecimalAutomatic &) = delete; 423 | _DecimalAutomatic &operator=(_DecimalAutomatic &&) = delete; 424 | 425 | ~_DecimalAutomatic() = default; 426 | 427 | void _readDigit(Digit digit){ 428 | assert(digit < radix); 429 | 430 | numStack.emplace_back(digit); 431 | ++count; 432 | SizeT _lowbit = count & ((~count) + 1); 433 | VSize i = 0; 434 | for(;(1 << i) < _lowbit;++i){ 435 | assert(numStack.size() >= 2); 436 | BI top1 = std::move(numStack.back()); 437 | numStack.pop_back(); 438 | 439 | assert(i <= decimalBase.size()); 440 | if(i == decimalBase.size()){ 441 | if(i == 0){ 442 | decimalBase.emplace_back(10); 443 | } 444 | else{ 445 | BI next = decimalBase.back(); 446 | next.selfMultiply(); 447 | decimalBase.push_back(std::move(next)); 448 | } 449 | } 450 | numStack.back().multiplyMedium(decimalBase[i]); 451 | //numStack.back().buf.addRaw(std::move(top1.buf)); 452 | numStack.back().add(std::move(top1)); 453 | } 454 | 455 | if(baseCap + 1 < i){ 456 | baseCap = i - 1; 457 | } 458 | } 459 | 460 | BI _finish() &&{ 461 | // elinimate "baseCap==0 && i==0" case 462 | if(numStack.empty()){ 463 | return BI(static_cast(0)); 464 | } 465 | 466 | BI res = std::move(numStack.front()); 467 | numStack.pop_front(); 468 | if(numStack.empty()){ 469 | return res; 470 | } 471 | 472 | VSize i = baseCap; 473 | //assert((count & (1 << i)) != 0); 474 | SizeT _lowbit = count & ((~count) + 1); 475 | assert(_lowbit > 0); 476 | assert(_lowbit < count); 477 | assert((1 << i) < count); 478 | for(SizeT mask = (1 << i);mask >= _lowbit;mask >>= 1, --i){ 479 | assert(!numStack.empty()); 480 | if((mask & count) == 0){ 481 | continue; 482 | } 483 | res.multiply(decimalBase[i]); 484 | //res.multiplySmall(decimalBase[i]); 485 | res.add(std::move(numStack.front())); 486 | numStack.pop_front(); 487 | } 488 | assert(numStack.empty()); 489 | return res; 490 | } 491 | BI _finish() const &{ 492 | if(numStack.empty()){ 493 | return BI(static_cast(0)); 494 | } 495 | 496 | using ConstIter = typename std::deque::const_iterator; 497 | ConstIter iter = numStack.cbegin(); 498 | BI res = *iter; 499 | ++iter; 500 | if(iter == numStack.cend()){ 501 | return res; 502 | } 503 | 504 | VSize i = baseCap; 505 | SizeT _lowbit = count & ((~count) + 1); 506 | assert(_lowbit > 0); 507 | assert(_lowbit < count); 508 | assert((1 << i) < count); 509 | for(SizeT mask = (1 << i);mask >= _lowbit;mask >>= 1, --i){ 510 | assert(iter != numStack.end()); 511 | if((mask & count) == 0){ 512 | continue; 513 | } 514 | res.multiply(decimalBase[i]); 515 | res.add(*iter); 516 | ++iter; 517 | } 518 | assert(iter == numStack.end()); 519 | return res; 520 | } 521 | private: 522 | // not thread-safe 523 | std::vector &decimalBase; 524 | std::deque numStack; 525 | 526 | SizeT count; 527 | VSize baseCap; 528 | }; 529 | 530 | template 531 | class _SmallPower2RadixAutomatic; 532 | 533 | template 534 | class _SmallPower2RadixAutomatic 535 | :public DigitReceiverCRTP>{ 537 | private: 538 | using SizeT = typename BI::SizeT; 539 | using LogSizeT = typename BI::LogSizeT; 540 | 541 | static constexpr LogSizeT ENTRY_SIZE = BI::ENTRY_SIZE; 542 | public: 543 | explicit _SmallPower2RadixAutomatic(Diff _dist, SizeT _exp) 544 | :num(typename BI::NullTag{}), dist(_dist), exp(_exp){ 545 | assert(dist > 0); 546 | assert(exp < ENTRY_SIZE); 547 | 548 | SizeT _len = (exp * _dist + ENTRY_SIZE - 1) / ENTRY_SIZE; 549 | num.buf.setLen(_len); 550 | num.allocator.allocate(num.buf.data, static_cast(num.buf.cap)); 551 | SizeT i = 0; 552 | try{ 553 | for(;i < num.buf.len;++i){ 554 | num.allocator.construct(num.buf.data + i, 0); 555 | } 556 | } 557 | catch(...){ 558 | _utility::destroyAll(num.buf.data, num.buf.data + i, num.allocator); 559 | num.allocator.deallocate(num.buf.data, static_cast(num.buf.cap)); 560 | num.buf.data = nullptr; 561 | num.buf.zeroLen(); 562 | throw; 563 | } 564 | } 565 | 566 | _SmallPower2RadixAutomatic(const _SmallPower2RadixAutomatic &) = delete; 567 | _SmallPower2RadixAutomatic(_SmallPower2RadixAutomatic &&) = delete; 568 | 569 | _SmallPower2RadixAutomatic &operator=(const _SmallPower2RadixAutomatic &) = delete; 570 | _SmallPower2RadixAutomatic &operator=(_SmallPower2RadixAutomatic &&) = delete; 571 | 572 | ~_SmallPower2RadixAutomatic() = default; 573 | 574 | void _setDigit(Digit digit, Diff count){ 575 | assert(digit < (1 << exp)); 576 | 577 | assert(count < dist); 578 | SizeT curI = ((dist - 1 - count) * exp) / ENTRY_SIZE; 579 | LogSizeT curBit = ((dist - 1 - count) * exp) % ENTRY_SIZE; 580 | 581 | if(curBit + exp <= ENTRY_SIZE){ 582 | num.buf.data[curI] |= digit << curBit; 583 | } 584 | else{ 585 | assert(curI + 1 < num.buf.len); 586 | num.buf.data[curI] |= (digit & ((1 << (ENTRY_SIZE - curBit)) - 1)) << curBit; 587 | num.buf.data[curI + 1] |= digit >> (ENTRY_SIZE - curBit); 588 | } 589 | } 590 | 591 | void _readDigit(Digit digit){ 592 | assert(digit < (1 << exp)); 593 | _setDigit(digit, count); 594 | ++count; 595 | } 596 | 597 | BI _finish() &&{ 598 | return std::move(num); 599 | } 600 | BI _finish() &{ 601 | return num; 602 | } 603 | private: 604 | Diff dist; 605 | SizeT exp; 606 | 607 | Diff count; 608 | BI num; 609 | }; 610 | 611 | template 612 | class _SmallPower2RadixAutomatic 613 | :public DigitReceiverCRTP>{ 615 | private: 616 | using SizeT = typename BI::SizeT; 617 | using LogSizeT = typename BI::LogSizeT; 618 | using DB = typename BI::DigitBuffer; 619 | using Ele = typename BI::Ele; 620 | 621 | static constexpr LogSizeT ENTRY_SIZE = BI::ENTRY_SIZE; 622 | public: 623 | explicit _SmallPower2RadixAutomatic(SizeT _exp) 624 | :exp(_exp), num(), curI(0), curBit(ENTRY_SIZE){ 625 | assert(exp < ENTRY_SIZE); 626 | } 627 | 628 | _SmallPower2RadixAutomatic(const _SmallPower2RadixAutomatic &) = delete; 629 | _SmallPower2RadixAutomatic(_SmallPower2RadixAutomatic &&) = delete; 630 | 631 | _SmallPower2RadixAutomatic &operator=(const _SmallPower2RadixAutomatic &) = delete; 632 | _SmallPower2RadixAutomatic &operator=(_SmallPower2RadixAutomatic &&) = delete; 633 | 634 | ~_SmallPower2RadixAutomatic() = default; 635 | 636 | void _readDigit(Digit digit){ 637 | assert(digit < (1 << exp)); 638 | 639 | if(curBit >= exp){ 640 | num.buf.data[curI] |= digit << (curBit - exp); 641 | curBit -= exp; 642 | return ; 643 | } 644 | 645 | if((curI == 0) && (curBit < exp)){ 646 | DB tmp(&num.allocator, nullptr); 647 | tmp.setLen(num.buf.len * 2); 648 | tmp.data = num.allocator.allocate(static_cast(tmp.cap)); 649 | SizeT i = tmp.len; 650 | try{ 651 | for(;i > num.buf.len;--i){ 652 | num.allocator.construct(tmp.data + i - 1, num.buf.data[i - num.buf.len - 1]); 653 | } 654 | for(i = num.buf.len;i > 0;--i){ 655 | num.allocator.construct(tmp.data + i - 1, 0); 656 | } 657 | } 658 | catch(...){ 659 | _utility::destroyAll(tmp.data + i, tmp.data + tmp.len, num.allocator); 660 | num.allocator.deallocate(tmp.data, static_cast(tmp.cap)); 661 | tmp.data = nullptr; 662 | tmp.zeroLen(); 663 | throw; 664 | } 665 | 666 | curI = num.buf.len; 667 | 668 | _utility::destroyAll(num.buf.data, num.buf.data + num.buf.len, num.allocator); 669 | num.allocator.deallocate(num.buf.data, static_cast(num.buf.cap)); 670 | num.buf.data = tmp.data; 671 | num.buf.len = tmp.len; 672 | num.buf.cap = tmp.cap; 673 | tmp.data = nullptr; 674 | tmp.zeroLen(); 675 | } 676 | 677 | assert(curI > 0); 678 | num.buf.data[curI] |= digit >> (exp - curBit); 679 | num.buf.data[curI - 1] |= (digit & ((1 << (exp - curBit)) - 1)) << (ENTRY_SIZE + curBit - exp); 680 | curBit = ENTRY_SIZE + curBit - exp; 681 | --curI; 682 | 683 | return ; 684 | } 685 | 686 | BI _finish() &&{ 687 | assert(num.buf.len == num.buf.cap); 688 | //assert((curI + curBit / ENTRY_SIZE) * 2 < num.buf.len); 689 | if((curI == 0) && (curBit == 0)){ 690 | return std::move(num); 691 | } 692 | for(SizeT i = 0;i + curI < num.buf.len - 1;++i){ 693 | num.buf.data[i] = (num.buf.data[i + curI] >> curBit) | ((num.buf.data[i + curI + 1] & ((1 << curBit) - 1)) << (ENTRY_SIZE - curBit)); 694 | } 695 | num.buf.data[num.buf.len - curI - 1] = num.buf.data[num.buf.len - 1] >> curBit; 696 | 697 | _utility::destroyAll(num.buf.data + num.buf.len - curI, num.buf.data + num.buf.len, num.allocator); 698 | num.buf.len -= curI; 699 | 700 | return std::move(num); 701 | } 702 | BI _finish() const &{ 703 | assert(num.buf.len == num.buf.cap); 704 | if((curI == 0) && (curBit == 0)){ 705 | return num; 706 | } 707 | 708 | Ele leftover = num.buf.data[num.buf.len - 1] >> curBit; 709 | assert((leftover == 0) || (num.buf.len > curI)); 710 | assert((leftover > 0) || (num.buf.len > curI + 1)); 711 | SizeT _len = (leftover > 0)? (num.buf.len - curI): (num.buf.len - curI - 1); 712 | 713 | BI res(typename BI::NullTag{}); 714 | res.buf.setLen(_len); 715 | res.buf.data = res.allocator.allocate(static_cast(res.buf.cap)); 716 | SizeT i = 0; 717 | try{ 718 | for(;i + curI < num.buf.len - 1;++i){ 719 | res.allocator.construct(res.buf.data + i, (num.buf.data[i + curI] >> curBit) | ((num.buf.data[i + curI + 1] & ((1 << curBit) - 1)) << (ENTRY_SIZE - curBit))); 720 | } 721 | if(leftover > 0){ 722 | i = res.buf.len - 1; 723 | res.allocator.construct(res.buf.data + i, leftover); 724 | } 725 | } 726 | catch(...){ 727 | _utility::destroyAll(res.buf.data, res.buf.data + i, res.allocator); 728 | res.allocator.deallocate(res.buf.data, static_cast(res.buf.cap)); 729 | res.buf.data = nullptr; 730 | res.buf.zeroLen(); 731 | throw ; 732 | } 733 | 734 | return res; 735 | } 736 | private: 737 | SizeT exp; 738 | BI num; 739 | 740 | SizeT curI; 741 | LogSizeT curBit; 742 | }; 743 | 744 | template 745 | class _LargePower2RadixAutomatic; 746 | 747 | template 748 | class _LargePower2RadixAutomatic 749 | :public DigitReceiverCRTP>{ 751 | private: 752 | using SizeT = typename BI::SizeT; 753 | using LogSizeT = typename BI::LogSizeT; 754 | using Ele = typename BI::Ele; 755 | 756 | static constexpr LogSizeT ENTRY_SIZE = BI::ENTRY_SIZE; 757 | public: 758 | explicit _LargePower2RadixAutomatic(Diff _dist, SizeT _exp) 759 | :dist(_dist), exp(_exp), count(0), num(typename BI::NullTag{}){ 760 | assert(dist > 0); 761 | assert(exp > ENTRY_SIZE); 762 | 763 | SizeT _len = (exp * _dist + ENTRY_SIZE - 1) / ENTRY_SIZE; 764 | num.buf.setLen(_len); 765 | num.buf.data = num.allocator.allocate(static_cast(num.buf.cap)); 766 | SizeT i = 0; 767 | try{ 768 | for(;i < num.buf.len;++i){ 769 | num.allocator.construct(num.buf.data + i, 0); 770 | } 771 | } 772 | catch(...){ 773 | _utility::destroyAll(num.buf.data, num.buf.data + i, num.allocator); 774 | num.allocator.deallocate(num.buf.data, static_cast(num.buf.cap)); 775 | num.buf.data = nullptr; 776 | num.buf.zeroLen(); 777 | throw; 778 | } 779 | } 780 | 781 | _LargePower2RadixAutomatic(const _LargePower2RadixAutomatic &) = delete; 782 | _LargePower2RadixAutomatic(_LargePower2RadixAutomatic &&) = delete; 783 | 784 | _LargePower2RadixAutomatic &operator=(const _LargePower2RadixAutomatic &) = delete; 785 | _LargePower2RadixAutomatic &operator=(_LargePower2RadixAutomatic &&) = delete; 786 | 787 | ~_LargePower2RadixAutomatic() = default; 788 | 789 | void _setDigit(Digit digit, Diff count){ 790 | assert(digit < (1 << exp)); 791 | 792 | assert(count < dist); 793 | SizeT curI = ((dist - 1 - count) * exp) / ENTRY_SIZE; 794 | LogSizeT curBit = ((dist - 1 - count) * exp) % ENTRY_SIZE; 795 | 796 | assert(curI + 1 < num.buf.len); 797 | SizeT stepI = (exp + curBit - ENTRY_SIZE) / ENTRY_SIZE; 798 | LogSizeT leftStep = (exp + curBit - ENTRY_SIZE) % ENTRY_SIZE; 799 | num.buf.data[curI] |= static_cast((digit & ((1 << (ENTRY_SIZE - curBit)) - 1)) << curBit); 800 | digit >>= ENTRY_SIZE - curBit; 801 | for(SizeT i = 1;i <= stepI;++i){ 802 | num.buf.data[curI + i] |= static_cast(digit & ((1 << ENTRY_SIZE) - 1)); 803 | digit >>= ENTRY_SIZE; 804 | } 805 | assert(digit < (1 << leftStep)); 806 | if(leftStep > 0){ 807 | num.buf.data[curI + stepI + 1] |= static_cast(digit); 808 | } 809 | } 810 | 811 | void _readDigit(Digit digit){ 812 | assert(digit < (1 << exp)); 813 | _setDigit(digit, count); 814 | ++count; 815 | } 816 | 817 | BI _finish() &&{ 818 | return std::move(num); 819 | } 820 | BI _finish() &{ 821 | return num; 822 | } 823 | private: 824 | Diff dist; 825 | SizeT exp; 826 | 827 | Diff count; 828 | BI num; 829 | }; 830 | 831 | template 832 | class _LargePower2RadixAutomatic 833 | :public DigitReceiverCRTP>{ 835 | private: 836 | using SizeT = typename BI::SizeT; 837 | using LogSizeT = typename BI::LogSizeT; 838 | using DB = typename BI::DigitBuffer; 839 | using Ele = typename BI::Ele; 840 | 841 | static constexpr LogSizeT ENTRY_SIZE = BI::ENTRY_SIZE; 842 | public: 843 | explicit _LargePower2RadixAutomatic(SizeT _exp) 844 | :exp(_exp), num(), curI(0), curBit(ENTRY_SIZE){ 845 | assert(exp > ENTRY_SIZE); 846 | } 847 | 848 | _LargePower2RadixAutomatic(const _LargePower2RadixAutomatic &) = delete; 849 | _LargePower2RadixAutomatic(_LargePower2RadixAutomatic &&) = delete; 850 | 851 | _LargePower2RadixAutomatic &operator=(const _LargePower2RadixAutomatic &) = delete; 852 | _LargePower2RadixAutomatic &operator=(_LargePower2RadixAutomatic &&) = delete; 853 | 854 | ~_LargePower2RadixAutomatic() = default; 855 | 856 | void _readDigit(Digit digit){ 857 | assert(digit < (1 << exp)); 858 | 859 | SizeT resLen = num.buf.len, space = 0; 860 | while((curI + space) * ENTRY_SIZE + curBit < exp){ 861 | space += resLen; 862 | resLen <<= 1; 863 | } 864 | 865 | if(space != 0){ 866 | DB tmp(&num.allocator, nullptr); 867 | tmp.setLen(resLen); 868 | tmp.data = num.allocator.allocate(static_cast(tmp.cap)); 869 | SizeT i = tmp.len; 870 | try{ 871 | for(;i > space;--i){ 872 | num.allocator.allocate(tmp.data + i - 1, num.buf.data[i - num.buf.len - 1]); 873 | } 874 | for(i = space;i > 0;--i){ 875 | num.allocator.allocate(tmp.data + i - 1, 0); 876 | } 877 | } 878 | catch(...){ 879 | _utility::destroyAll(tmp.data + i, tmp.data + tmp.len, num.allocator); 880 | num.allocator.deallocate(tmp.data, static_cast(tmp.cap)); 881 | tmp.data = nullptr; 882 | tmp.zeroLen(); 883 | throw; 884 | } 885 | 886 | curI += space; 887 | 888 | _utility::destroyAll(num.buf.data, num.buf.data + num.buf.len, num.allocator); 889 | num.allocator.deallocate(num.buf.data, static_cast(num.buf.cap)); 890 | num.buf.data = tmp.data; 891 | num.buf.len = tmp.len; 892 | num.buf.cap = tmp.cap; 893 | tmp.data = nullptr; 894 | tmp.zeroLen(); 895 | } 896 | 897 | SizeT stepI = (exp - curBit) / ENTRY_SIZE; 898 | LogSizeT leftStep = (exp - curBit) % ENTRY_SIZE; 899 | if(leftStep > 0){ 900 | assert(curI > stepI); 901 | num.buf.data[curI - stepI - 1] |= static_cast(digit & ((1 << leftStep) - 1)) << (ENTRY_SIZE - leftStep); 902 | digit >>= leftStep; 903 | } 904 | else{ 905 | assert(curI >= stepI); 906 | } 907 | for(SizeT i = stepI;i > 0;--i){ 908 | num.buf.data[curI - stepI] |= static_cast(digit & ((1 << ENTRY_SIZE) - 1)); 909 | digit >>= ENTRY_SIZE; 910 | } 911 | assert(digit < (1 << curBit)); 912 | num.buf.data[curI] |= static_cast(digit); 913 | 914 | if(leftStep > 0){ 915 | curI -= stepI + 1; 916 | curBit = ENTRY_SIZE - leftStep; 917 | } 918 | else{ 919 | curI -=stepI; 920 | curBit = 0; 921 | } 922 | } 923 | 924 | BI _finish() &&{ 925 | assert(num.buf.len == num.buf.cap); 926 | assert((curI + curBit / ENTRY_SIZE) * 2 < num.buf.len); 927 | if((curI == 0) && (curBit == 0)){ 928 | return std::move(num); 929 | } 930 | for(SizeT i = 0;i + curI < num.buf.len - 1;++i){ 931 | num.buf.data[i] = (num.buf.data[i + curI] >> curBit) | ((num.buf.data[i + curI + 1] & ((1 << curBit) - 1)) << (ENTRY_SIZE - curBit)); 932 | } 933 | num.buf.data[num.buf.len - curI - 1] = num.buf.data[num.buf.len - 1] >> curBit; 934 | 935 | _utility::destroyAll(num.buf.data + num.buf.len - curI, num.buf.data + num.buf.len, num.allocator); 936 | num.buf.len -= curI; 937 | 938 | return std::move(num); 939 | } 940 | BI _finish() const &{ 941 | assert(num.buf.len == num.buf.cap); 942 | assert((curI + curBit / ENTRY_SIZE) * 2 < num.buf.len); 943 | if((curI == 0) && (curBit == 0)){ 944 | return num; 945 | } 946 | 947 | Ele leftover = num.buf.data[num.buf.len - 1] >> curBit; 948 | assert((leftover == 0) || (num.buf.len > curI)); 949 | assert((leftover > 0) || (num.buf.len > curI + 1)); 950 | SizeT _len = (leftover > 0)? (num.buf.len - curI): (num.buf.len - curI - 1); 951 | 952 | BI res(typename BI::NullTag{}); 953 | res.buf.setLen(_len); 954 | res.buf.data = res.allocator.allocate(static_cast(res.buf.cap)); 955 | SizeT i = 0; 956 | try{ 957 | for(;i + curI < num.buf.len - 1;++i){ 958 | res.allocator.construct(res.buf.data + i, (num.buf.data[i + curI] >> curBit) | ((num.buf.data[i + curI + 1] & ((1 << curBit) - 1)) << (ENTRY_SIZE - curBit))); 959 | } 960 | if(leftover > 0){ 961 | i = res.buf.len - 1; 962 | res.allocator.construct(res.buf.data + i, leftover); 963 | } 964 | } 965 | catch(...){ 966 | _utility::destroyAll(res.buf.data, res.buf.data + i, res.allocator); 967 | res.allocator.deallocate(res.buf.data, static_cast(res.buf.cap)); 968 | res.buf.data = nullptr; 969 | res.buf.zeroLen(); 970 | throw ; 971 | } 972 | return res; 973 | } 974 | private: 975 | SizeT exp; 976 | BI num; 977 | 978 | SizeT curI; 979 | LogSizeT curBit; 980 | }; 981 | 982 | template 983 | class _ExactDigitAutomatic; 984 | 985 | template 986 | class _ExactDigitAutomatic 987 | :public DigitReceiverCRTP>{ 989 | private: 990 | using SizeT = typename BI::SizeT; 991 | using Ele = typename BI::Ele; 992 | using LogSizeT = typename BI::LogSizeT; 993 | 994 | static constexpr LogSizeT ENTRY_SIZE = BI::ENTRY_SIZE; 995 | public: 996 | explicit _ExactDigitAutomatic(Diff _dist) 997 | :dist(_dist), count(0), num(typename BI::NullTag{}){ 998 | assert(_dist > 0); 999 | 1000 | num.buf.setLen(dist); 1001 | num.buf.data = num.allocator.allocate(static_cast(num.buf.cap)); 1002 | SizeT i = 0; 1003 | try{ 1004 | for(;i < num.buf.len;++i){ 1005 | num.allocator.construct(num.buf.data + i, 0); 1006 | } 1007 | } 1008 | catch(...){ 1009 | _utility::destroyAll(num.buf.data, num.buf.data + i, num.allocator); 1010 | num.allocator.deallocate(num.buf.data, static_cast(num.buf.cap)); 1011 | num.buf.data = nullptr; 1012 | num.buf.zeroLen(); 1013 | throw; 1014 | } 1015 | } 1016 | 1017 | _ExactDigitAutomatic(const _ExactDigitAutomatic &) = delete; 1018 | _ExactDigitAutomatic(_ExactDigitAutomatic &&) = delete; 1019 | 1020 | _ExactDigitAutomatic &operator=(const _ExactDigitAutomatic &) = delete; 1021 | _ExactDigitAutomatic &operator=(_ExactDigitAutomatic &&) = delete; 1022 | 1023 | ~_ExactDigitAutomatic() = default; 1024 | 1025 | void _setDigit(Digit digit, Diff count){ 1026 | assert(digit < (1 << ENTRY_SIZE)); 1027 | num.buf.data[count] = digit; 1028 | } 1029 | 1030 | void _readDigit(Digit digit){ 1031 | assert(digit < (1 << ENTRY_SIZE)); 1032 | _setDigit(digit, count); 1033 | ++count; 1034 | } 1035 | 1036 | BI _finish() &&{ 1037 | return std::move(num); 1038 | } 1039 | BI _finish() &{ 1040 | return num; 1041 | } 1042 | private: 1043 | Diff dist, count; 1044 | BI num; 1045 | }; 1046 | 1047 | template 1048 | class _ExactDigitAutomatic 1049 | :public DigitReceiverCRTP>{ 1051 | private: 1052 | using SizeT = typename BI::SizeT; 1053 | using Ele = typename BI::Ele; 1054 | using DB = typename BI::DigitBuffer; 1055 | using LogSizeT = typename BI::LogSizeT; 1056 | 1057 | static constexpr LogSizeT ENTRY_SIZE = BI::ENTRY_SIZE; 1058 | public: 1059 | explicit _ExactDigitAutomatic() 1060 | :num(0), curI(1){} 1061 | 1062 | _ExactDigitAutomatic(const _ExactDigitAutomatic &) = delete; 1063 | _ExactDigitAutomatic(_ExactDigitAutomatic &&) = delete; 1064 | 1065 | _ExactDigitAutomatic &operator=(const _ExactDigitAutomatic &) = delete; 1066 | _ExactDigitAutomatic &operator=(_ExactDigitAutomatic &&) = delete; 1067 | 1068 | ~_ExactDigitAutomatic() = default; 1069 | 1070 | void _readDigit(Digit digit){ 1071 | assert(digit < (1 << ENTRY_SIZE)); 1072 | 1073 | if(curI == 0){ 1074 | DB tmp(&num.allocator, nullptr); 1075 | tmp.setLen(num.buf.len * 2); 1076 | tmp.data = num.allocator.allocate(static_cast(tmp.cap)); 1077 | SizeT i = tmp.len; 1078 | try{ 1079 | for(;i > num.buf.len;--i){ 1080 | num.allocator.allocate(tmp.data + i - 1, num.buf.data[i - num.buf.len - 1]); 1081 | } 1082 | for(i = num.buf.len;i > 0;--i){ 1083 | num.allocator.allocate(tmp.data + i - 1, 0); 1084 | } 1085 | } 1086 | catch(...){ 1087 | _utility::destroyAll(tmp.data + i, tmp.data + tmp.len, num.allocator); 1088 | num.allocator.deallocate(tmp.data, static_cast(tmp.cap)); 1089 | tmp.data = nullptr; 1090 | tmp.zeroLen(); 1091 | throw; 1092 | } 1093 | 1094 | curI = num.buf.len; 1095 | 1096 | _utility::destroyAll(num.buf.data, num.buf.data + num.buf.len, num.allocator); 1097 | num.allocator.deallocate(num.buf.data, static_cast(num.buf.cap)); 1098 | num.buf.data = tmp.data; 1099 | num.buf.len = tmp.len; 1100 | num.buf.cap = tmp.cap; 1101 | tmp.data = nullptr; 1102 | tmp.zeroLen(); 1103 | } 1104 | 1105 | assert(curI > 0); 1106 | num.buf.data[curI - 1] = digit; 1107 | --curI; 1108 | } 1109 | 1110 | BI _finish() &&{ 1111 | assert(num.buf.len == num.buf.cap); 1112 | if(curI == 0){ 1113 | return std::move(num); 1114 | } 1115 | for(SizeT i = 0;i + curI < num.buf.len;++i){ 1116 | num.buf.data[i] = num.buf.data[i + curI]; 1117 | } 1118 | 1119 | _utility::destroyAll(num.buf.data + num.buf.len - curI, num.buf.data + num.buf.len, num.allocator); 1120 | num.buf.len -= curI; 1121 | 1122 | return std::move(num); 1123 | } 1124 | BI _finish() const &{ 1125 | assert(num.buf.len == num.buf.cap); 1126 | if(curI == 0){ 1127 | return num; 1128 | } 1129 | 1130 | BI res(typename BI::NullTag{}); 1131 | res.buf.setLen(num.buf.len - curI); 1132 | res.buf.data = res.allocator.allocate(static_cast(res.buf.cap)); 1133 | SizeT i = 0; 1134 | try{ 1135 | for(;i + curI < num.buf.len;++i){ 1136 | res.buf.data[i] = num.buf.data[i + curI]; 1137 | } 1138 | } 1139 | catch(...){ 1140 | _utility::destroyAll(res.buf.data, res.buf.data + i, res.allocator); 1141 | res.allocator.deallocate(res.buf.data, static_cast(res.buf.cap)); 1142 | res.buf.data = nullptr; 1143 | res.buf.zeroLen(); 1144 | throw ; 1145 | } 1146 | 1147 | return res; 1148 | } 1149 | private: 1150 | BI num; 1151 | SizeT curI; 1152 | }; 1153 | 1154 | template 1155 | class RadixConvertRecver{ 1156 | public: 1157 | //using iterator = _type::DigitRecvIterator; 1158 | using Unsigned = typename std::make_unsigned::type; 1159 | using SizeT = typename BI::SizeT; 1160 | using LogSizeT = typename BI::LogSizeT; 1161 | 1162 | static constexpr LogSizeT ENTRY_SIZE = BI::ENTRY_SIZE; 1163 | public: 1164 | explicit RadixConvertRecver(Digit _radix) 1165 | :radix(_radix){} 1166 | 1167 | RadixConvertRecver(const RadixConvertRecver &) = default; 1168 | RadixConvertRecver(RadixConvertRecver &&) = default; 1169 | 1170 | RadixConvertRecver &operator=(const RadixConvertRecver &) = default; 1171 | RadixConvertRecver &operator=(RadixConvertRecver &&) = default; 1172 | 1173 | ~RadixConvertRecver() = default; 1174 | 1175 | template 1176 | BI readDigits(Iter _begin, Iter _end){ 1177 | if(radix == 10){ 1178 | return readDigitsDecimal(_begin, _end); 1179 | } 1180 | if((radix & ((~radix) + 1)) == radix){ 1181 | SizeT exp = static_cast(std::ceil(std::log2(radix))); 1182 | using iterTag = typename std::iterator_traits::iterator_category; 1183 | if(exp < ENTRY_SIZE){ 1184 | return readDigitsSmallPowerOf2(exp, _begin, _end, iterTag{}); 1185 | } 1186 | if(exp == ENTRY_SIZE){ 1187 | return readDigitsExact(exp, _begin, _end, iterTag{}); 1188 | } 1189 | if(exp > ENTRY_SIZE){ 1190 | return readDigitsLargePowerOf2(exp, _begin, _end, iterTag{}); 1191 | } 1192 | } 1193 | 1194 | return readDigitsGeneric(radix, _begin, _end); 1195 | } 1196 | 1197 | /*iterator getIterator() const{ 1198 | 1199 | }*/ 1200 | private: 1201 | template 1202 | BI readDigitsDecimal(Iter _begin, Iter _end){ 1203 | using Diff = typename std::iterator_traits::difference_type; 1204 | _DecimalAutomatic automatic; 1205 | for(Iter iter = _begin;iter != _end;++iter){ 1206 | automatic._readDigit(static_cast(*iter)); 1207 | } 1208 | return std::move(automatic)._finish(); 1209 | } 1210 | 1211 | template 1212 | BI readDigitsSmallPowerOf2(SizeT exp, Iter _begin, Iter _end, std::random_access_iterator_tag){ 1213 | using Diff = typename std::iterator_traits::difference_type; 1214 | Diff dist = std::distance(_begin, _end); 1215 | _SmallPower2RadixAutomatic automatic(dist, exp); 1216 | for(Iter iter = _begin;iter != _end;++iter){ 1217 | automatic._readDigit(static_cast(*iter)); 1218 | } 1219 | return std::move(automatic)._finish(); 1220 | } 1221 | template 1222 | BI readDigitsSmallPowerOf2(SizeT exp, Iter _begin, Iter _end, std::input_iterator_tag){ 1223 | using Diff = typename std::iterator_traits::difference_type; 1224 | _SmallPower2RadixAutomatic automatic(exp); 1225 | for(Iter iter = _begin;iter != end;++iter){ 1226 | automatic._readDigit(static_cast(*iter)); 1227 | } 1228 | return std::move(automatic)._finish(); 1229 | } 1230 | 1231 | template 1232 | BI readDigitsExact(Iter _begin, Iter _end, std::random_access_iterator_tag){ 1233 | using Diff = typename std::iterator_traits::difference_type; 1234 | Diff dist = std::distance(_begin, _end); 1235 | _ExactDigitAutomatic automatic(dist); 1236 | for(Iter iter = _begin;iter != _end;++iter){ 1237 | automatic._readDigit(static_cast(*iter)); 1238 | } 1239 | return std::move(automatic)._finish(); 1240 | } 1241 | template 1242 | BI readDigitsExact(Iter _begin, Iter _end, std::input_iterator_tag){ 1243 | using Diff = typename std::iterator_traits::difference_type; 1244 | _ExactDigitAutomatic automatic; 1245 | for(Iter iter = _begin;iter != _end;++iter){ 1246 | automatic._readDigit(static_cast(*iter)); 1247 | } 1248 | return std::move(automatic)._finish(); 1249 | } 1250 | 1251 | template 1252 | BI readDigitsLargePowerOf2(SizeT exp, Iter _begin, Iter _end, std::random_access_iterator_tag){ 1253 | using Diff = typename std::iterator_traits::difference_type; 1254 | Diff dist = std::distance(_begin, _end); 1255 | _LargePower2RadixAutomatic automatic(dist, exp); 1256 | for(Iter iter = _begin;iter != _end;++iter){ 1257 | automatic._readDigit(static_cast(*iter)); 1258 | } 1259 | return std::move(automatic)._finish(); 1260 | } 1261 | template 1262 | BI readDigitsLargePowerOf2(SizeT exp, Iter _begin, Iter _end, std::input_iterator_tag){ 1263 | using Diff = typename std::iterator_traits::difference_type; 1264 | _LargePower2RadixAutomatic automatic(exp); 1265 | for(Iter iter = _begin;iter != _end;++iter){ 1266 | automatic._readDigit(static_cast(*iter)); 1267 | } 1268 | return std::move(automatic)._finish(); 1269 | } 1270 | 1271 | template 1272 | BI readDigitsGeneric(Digit radix, Iter _begin, Iter _end){ 1273 | using Diff = typename std::iterator_traits::difference_type; 1274 | _GenericAutomatic automatic(radix); 1275 | for(Iter iter = _begin;iter != _end;++iter){ 1276 | automatic._readDigit(static_cast(*iter)); 1277 | } 1278 | return std::move(automatic)._finish(); 1279 | } 1280 | 1281 | Digit radix; 1282 | }; 1283 | 1284 | namespace _type{ 1285 | 1286 | template 1287 | inline void inputDigitImpl(Automatic &automatic, StaticList...>){ 1288 | PackExpandHelper helper({0, (automatic._readDigit(Args), 0)...}); 1289 | } 1290 | 1291 | template 1292 | struct NotSep; 1293 | template 1294 | struct NotSep> 1295 | :public std::true_type{}; 1296 | template <> 1297 | struct NotSep> 1298 | :public std::false_type{}; 1299 | 1300 | template 1301 | struct IsBin; 1302 | template 1303 | struct IsBin> 1304 | :public std::integral_constant '0' && Ch <= '1')>{}; 1305 | 1306 | template 1307 | struct IsOct; 1308 | template 1309 | struct IsOct> 1310 | :public std::integral_constant '0' && Ch <= '7')>{}; 1311 | 1312 | template 1313 | struct IsDec; 1314 | template 1315 | struct IsDec> 1316 | :public std::integral_constant '0' && Ch <= '9')>{}; 1317 | 1318 | template 1319 | struct IsHex; 1320 | template 1321 | struct IsHex> 1322 | :public std::integral_constant '0' && Ch <= '9') || 1323 | (Ch > 'a' && Ch <= 'f') || (Ch > 'A' && Ch <= 'F'))>{}; 1324 | 1325 | template 1326 | struct ToBin; 1327 | template 1328 | struct ToBin>{ 1329 | using type = std::integral_constant; 1330 | }; 1331 | 1332 | template 1333 | struct ToOct; 1334 | template 1335 | struct ToOct>{ 1336 | using type = std::integral_constant; 1337 | }; 1338 | 1339 | template 1340 | struct ToDec; 1341 | template 1342 | struct ToDec>{ 1343 | using type = std::integral_constant; 1344 | }; 1345 | 1346 | template 1347 | struct ToHex; 1348 | template 1349 | struct ToHex>{ 1350 | using type = std::integral_constant '0' && Ch <= '9')? (Ch - '0'): 1351 | ((Ch > 'a' && Ch <= 'f')? (Ch - 'a'): (Ch - 'A'))>; 1352 | }; 1353 | 1354 | template 1355 | struct LiteralParser{}; 1356 | // hex 1357 | template 1358 | struct LiteralParser, 1359 | std::integral_constant, 1360 | std::integral_constant...>>{ 1361 | private: 1362 | using CharSeq = typename Filter...>>::type; 1363 | using DigitSeq = typename Map::type>::type; 1364 | 1365 | using Automatic = typename CompareCond, 1367 | _ExactDigitAutomatic, 1368 | _SmallPower2RadixAutomatic>::type; 1369 | public: 1370 | inline static BI getBI(){ 1371 | Automatic automatic(sizeof...(Args), 4); 1372 | inputDigitImpl(automatic, DigitSeq{}); 1373 | return std::move(automatic)._finish(); 1374 | } 1375 | }; 1376 | template 1377 | struct LiteralParser, 1378 | std::integral_constant, 1379 | std::integral_constant...>> 1380 | :public LiteralParser, 1381 | std::integral_constant, 1382 | std::integral_constant...>>{}; 1383 | // oct 1384 | template 1385 | struct LiteralParser, 1386 | std::integral_constant...>>{ 1387 | private: 1388 | using CharSeq = typename Filter...>>::type; 1389 | using DigitSeq = typename Map::type>::type; 1390 | 1391 | using Automatic = typename CompareCond, 1393 | _ExactDigitAutomatic, 1394 | _SmallPower2RadixAutomatic>::type; 1395 | public: 1396 | inline static BI getBI(){ 1397 | Automatic automatic(sizeof...(Args), 3); 1398 | inputDigitImpl(automatic, DigitSeq{}); 1399 | return std::move(automatic)._finish(); 1400 | } 1401 | }; 1402 | // bin 1403 | template 1404 | struct LiteralParser, 1405 | std::integral_constant, 1406 | std::integral_constant...>>{ 1407 | private: 1408 | using CharSeq = typename Filter...>>::type; 1409 | using DigitSeq = typename Map::type>::type; 1410 | 1411 | using Automatic = typename CompareCond, 1413 | _ExactDigitAutomatic, 1414 | _SmallPower2RadixAutomatic>::type; 1415 | public: 1416 | inline static BI getBI(){ 1417 | Automatic automatic(sizeof...(Args), 1); 1418 | inputDigitImpl(automatic, DigitSeq{}); 1419 | return std::move(automatic)._finish(); 1420 | } 1421 | }; 1422 | template 1423 | struct LiteralParser, 1424 | std::integral_constant, 1425 | std::integral_constant...>> 1426 | :public LiteralParser, 1427 | std::integral_constant, 1428 | std::integral_constant...>>{}; 1429 | // dec 1430 | template 1431 | struct LiteralParser...>>{ 1432 | using CharSeq = typename Filter...>>::type; 1433 | using DigitSeq = typename Map::type>::type; 1434 | 1435 | using Automatic = _DecimalAutomatic; 1436 | inline static BI getBI(){ 1437 | Automatic automatic; 1438 | inputDigitImpl(automatic, DigitSeq{}); 1439 | return std::move(automatic)._finish(); 1440 | } 1441 | }; 1442 | 1443 | }; // namespace _type 1444 | 1445 | }; // namespace bignum 1446 | #endif // _BIG_INT_INPUT_HPP_ -------------------------------------------------------------------------------- /BigInt/BigIntOutput.hpp: -------------------------------------------------------------------------------- 1 | #ifndef _BIG_NUM_HPP_ 2 | #error "This header must be included through BigNum.hpp" 3 | #endif // _BIG_NUM_HPP_ 4 | 5 | #ifndef _BIG_INT_OUTPUT_HPP_ 6 | #define _BIG_INT_OUTPUT_HPP_ 7 | 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include 15 | #include 16 | #include 17 | 18 | #include "../Libs/BigNumTypeTrait.hpp" 19 | 20 | namespace bignum{ 21 | 22 | namespace _type{ 23 | 24 | template 25 | class DigitProducer{ 26 | public: 27 | //virtual DigitProducer *clone() const = 0; 28 | virtual Digit _start() = 0; 29 | virtual Digit _next() = 0; 30 | virtual bool _hasNext() const = 0; 31 | // destructors must have a function body to reference even though 32 | // they are pure virtual 33 | virtual ~DigitProducer(){} 34 | }; 35 | 36 | template 37 | class DigitProducerCRTP:public DigitProducer{ 38 | /*public: 39 | virtual DigitProducer *clone() const{ 40 | return new Derived(static_cast(*this)); 41 | }*/ 42 | }; 43 | 44 | template 45 | class DigitEnumIterator 46 | :public std::iterator< 47 | std::input_iterator_tag, // iterator_category 48 | Digit, // value_type 49 | std::ptrdiff_t, // difference_type 50 | const Digit *, // pointer 51 | const Digit &>{ // reference 52 | private: 53 | using Producer = DigitProducer; 54 | public: 55 | using iterator_category = std::input_iterator_tag; 56 | using value_type = Digit; 57 | using difference_type = std::ptrdiff_t; 58 | using pointer = const Digit *; 59 | using reference = const Digit &; 60 | private: 61 | class ValueProxy{ 62 | public: 63 | explicit ValueProxy(Digit &_value): value(_value){} 64 | 65 | ValueProxy(const ValueProxy &) = delete; 66 | ValueProxy(ValueProxy &&) = default; 67 | 68 | ValueProxy &operator=(const ValueProxy &) = delete; 69 | ValueProxy &operator=(ValueProxy &&) = delete; 70 | 71 | ~ValueProxy() = default; 72 | 73 | value_type operator*() const{ 74 | return value; 75 | } 76 | private: 77 | Digit value; 78 | }; 79 | public: 80 | DigitEnumIterator(const DigitEnumIterator &_rhs) = default; 81 | DigitEnumIterator(DigitEnumIterator &&_rhs) noexcept 82 | :producer(std::move(_rhs.producer)), digit(_rhs.digit){ 83 | _rhs.producer = nullptr; 84 | } 85 | 86 | // we must ensure all the _producer arguments in all instances contain 87 | // different addresses or we are f**ked. 88 | template ::value>::type * = nullptr> 90 | explicit DigitEnumIterator(Derived *_producer) 91 | :producer(_producer), digit(producer->_start()){} 92 | 93 | explicit DigitEnumIterator(std::nullptr_t) 94 | :producer(nullptr), digit(){} 95 | 96 | DigitEnumIterator &operator=(const DigitEnumIterator &_rhs) = default; 97 | DigitEnumIterator &operator=(DigitEnumIterator &&_rhs) = default; 98 | 99 | ~DigitEnumIterator() = default; 100 | 101 | void swap(DigitEnumIterator &_rhs){ 102 | using std::swap; 103 | swap(producer, _rhs.producer); 104 | swap(digit, _rhs.digit); 105 | } 106 | 107 | // only a proxy, since it takes some RTTI support to truly determine equality 108 | // for subtyping 109 | // in C++17 it is allowed to compare an iterator with a complete different type 110 | // in range-for loops. I hope this will be implemented widely soon 111 | friend bool operator==(const DigitEnumIterator &i, const DigitEnumIterator &j){ 112 | return (i.producer == j.producer) && (i.digit == j.digit); 113 | } 114 | friend bool operator!=(const DigitEnumIterator &i, const DigitEnumIterator &j){ 115 | return (i.producer != j.producer) || (i.digit != j.digit); 116 | } 117 | 118 | reference operator*() const{ 119 | return digit; 120 | } 121 | 122 | // pre-increment 123 | DigitEnumIterator &operator++(){ 124 | if(!producer->_hasNext()){ 125 | digit = Digit(); 126 | producer = nullptr; 127 | } 128 | else{ 129 | digit = producer->_next(); 130 | } 131 | return *this; 132 | } 133 | // post-increment 134 | ValueProxy operator++(int){ 135 | ValueProxy tmp(digit); 136 | if(!producer->_hasNext()){ 137 | digit = Digit(); 138 | producer = nullptr; 139 | } 140 | else{ 141 | digit = producer->_next(); 142 | } 143 | return tmp; 144 | } 145 | private: 146 | std::shared_ptr producer; 147 | Digit digit; 148 | }; 149 | 150 | template 151 | inline void swap(DigitEnumIterator &_lhs, DigitEnumIterator &_rhs){ 152 | _lhs.swap(_rhs); 153 | } 154 | 155 | }; // namespace _type 156 | 157 | // assume coroutine parameters are non-negative 158 | template 159 | class _GenericRadix; 160 | template 161 | class _DecimalRadix; 162 | template 163 | class _SmallPower2Radix; 164 | template 165 | class _LargePower2Radix; 166 | template 167 | class _ExactDigitExtract; 168 | 169 | using _type::DigitProducerCRTP; 170 | using _type::isRLRef; 171 | using _type::isSigned; 172 | using _type::DigitProducer; 173 | 174 | // unsigned Digit 175 | template 176 | class _GenericRadix::value>::type> 178 | :public DigitProducerCRTP>{ 179 | private: 180 | using VSize = typename std::vector::size_type; 181 | using SizeT = typename BI::SizeT; 182 | public: 183 | _GenericRadix(const _GenericRadix &) = default; 184 | _GenericRadix(_GenericRadix &&) = delete; 185 | 186 | _GenericRadix &operator=(const _GenericRadix &) = delete; 187 | _GenericRadix &operator=(_GenericRadix &&) = delete; 188 | 189 | ~_GenericRadix() = default; 190 | 191 | // coroutine arguments 192 | template ::value>::type * = nullptr> 194 | explicit _GenericRadix(BIRef &&_lhs, Digit _radix) 195 | :fd(0), md(_radix), rd(0), ed(_radix), rf(0), rr(0), radix(_radix){ 196 | assert(_lhs.positive); 197 | 198 | if(_lhs.isZero()){ 199 | fd = 0; 200 | rf = 1; 201 | md = radix; 202 | rd = 0; 203 | rr = 0; 204 | ed = radix; 205 | return ; 206 | } 207 | if(_lhs.compareInt(Digit(radix), std::false_type()) == -1){ 208 | fd = _lhs.template convertSingleDigit(); 209 | rf = 1; 210 | md = radix; 211 | rd = 0; 212 | rr = 0; 213 | ed = radix; 214 | return ; 215 | } 216 | 217 | base.emplace_back(radix); 218 | do{ 219 | BI next = base.back(); 220 | next.selfMultiply(); 221 | std::int8_t comp = next.compare(_lhs); 222 | if(-1 == comp){ 223 | base.push_back(std::move(next)); 224 | continue; 225 | } 226 | if(0 == comp){ 227 | rf = 0; 228 | fd = 0; 229 | md = 1; 230 | rr = SizeT(1 << base.size()); 231 | rd = 0; 232 | ed = radix; 233 | return ; 234 | } 235 | if(1 == comp){ 236 | break; 237 | } 238 | }while(true); 239 | 240 | dStack.emplace(std::forward(_lhs), base.size(), 0); 241 | } 242 | 243 | virtual Digit _start(){ 244 | return _next(); 245 | } 246 | 247 | virtual Digit _next(){ 248 | assert(_hasNext()); 249 | 250 | { 251 | Digit res = trivalDigits(); 252 | if(res != radix){ 253 | return res; 254 | } 255 | } 256 | 257 | while(true){ 258 | assert(!dStack.empty()); 259 | // isZero() and (dStack.top()).isZero()){ 264 | // this means q * radix ^ {t} + 0, that is, print t zeroes when 265 | // facing this reminder, where t = 2 ^ {k} 266 | assert(std::get<2>(dStack.top()) == static_cast(1 << std::get<1>(dStack.top()))); 267 | ed = radix; 268 | rd = 0; 269 | rr = 0; 270 | md = radix; 271 | fd = 0; 272 | rf = std::get<2>(dStack.top()); 273 | dStack.pop(); 274 | return trivalDigits(); 275 | } 276 | if(std::get<0>(dStack.top()).compareInt(Digit(radix), std::false_type()) == -1){ 277 | Digit tmp = std::move(std::get<0>(dStack.top())).template convertSingleDigit(); 278 | rr = 0; 279 | rd = 0; 280 | ed = radix; 281 | if(std::get<2>(dStack.top()) == 0){ 282 | // highest digit 283 | md = radix; 284 | rf = 1; 285 | fd = tmp; 286 | } 287 | else{ 288 | md = tmp; 289 | rf = std::get<2>(dStack.top()) - 1; 290 | fd = 0; 291 | } 292 | dStack.pop(); 293 | return trivalDigits(); 294 | } 295 | 296 | // linear search fits well with the divide tree depth 297 | // binary search does not 298 | VSize k = std::get<1>(dStack.top()); 299 | std::int8_t comp; 300 | do{ 301 | --k; 302 | comp = base[k].compare(std::get<0>(dStack.top())); 303 | if(1 == comp){ 304 | continue; 305 | } 306 | else{ 307 | break; 308 | } 309 | assert(k != 0); 310 | }while(true); 311 | 312 | if(0 == comp){ 313 | ed = radix; 314 | md = 1; 315 | rd = 0; 316 | rr = static_cast(1 << k); 317 | fd = 0; 318 | rf = std::get<2>(dStack.top()); 319 | if(rf != 0){ 320 | rf -= 1 + rr; 321 | } 322 | dStack.pop(); 323 | return trivalDigits(); 324 | } 325 | 326 | assert(-1 == comp); 327 | std::pair qr = std::move(std::get<0>(dStack.top())).divideByMedium(base[k]); 328 | SizeT rLen = SizeT(1 << k); 329 | SizeT qLen = std::get<2>(dStack.top()); 330 | if(qLen != 0){ 331 | assert(qLen > rLen); 332 | qLen -= rLen; 333 | } 334 | dStack.pop(); 335 | 336 | // same as the procession at the beginning of the loop content. we add this just to 337 | // avoid some unnecessary move assignments 338 | if(qr.first.compareInt(Digit(radix), std::false_type{}) == -1){ 339 | Digit tmp = std::move(qr.first).template convertSingleDigit(); 340 | assert(tmp != 0); 341 | if(qLen == 0){ 342 | rf = 0; 343 | } 344 | else{ 345 | rf = qLen - 1; 346 | } 347 | 348 | if(qr.second.isZero()){ 349 | ed = radix; 350 | rd = 0; 351 | rr = rLen; 352 | md = tmp; 353 | fd = 0; 354 | return trivalDigits(); 355 | } 356 | 357 | if(qr.second.compareInt(Digit(radix), std::false_type()) == -1){ 358 | ed = std::move(qr.second).template convertSingleDigit(); 359 | rd = 0; 360 | rr = rLen - 1; 361 | md = tmp; 362 | fd = 0; 363 | return trivalDigits(); 364 | } 365 | else{ 366 | dStack.emplace(std::move(qr.second), k, rLen); 367 | ed = radix; 368 | rd = 0; 369 | rr = 0; 370 | md = tmp; 371 | fd = 0; 372 | return trivalDigits(); 373 | } 374 | } 375 | else{ 376 | dStack.emplace(std::move(qr.second), k, rLen); 377 | dStack.emplace(std::move(qr.first), k, qLen); 378 | continue; 379 | } 380 | }// while(true) 381 | // should never be reached 382 | assert(false); 383 | return 0; 384 | } 385 | 386 | virtual bool _hasNext() const{ 387 | if(rf > 0){ 388 | assert((fd >= 0) && (fd < radix)); 389 | return true; 390 | } 391 | if((md >= 0) && (md < radix)){ 392 | return true; 393 | } 394 | if(rr > 0){ 395 | assert((rd >= 0) && (rd < radix)); 396 | return true; 397 | } 398 | if((ed >= 0) && (ed < radix)){ 399 | return true; 400 | } 401 | return !dStack.empty(); 402 | } 403 | private: 404 | inline Digit trivalDigits(){ 405 | if(rf > 0){ 406 | --rf; 407 | return fd; 408 | } 409 | if((md >= 0) && (md < radix)){ 410 | Digit res = md; 411 | md = radix; 412 | return res; 413 | } 414 | if(rr > 0){ 415 | --rr; 416 | return rd; 417 | } 418 | if((ed >= 0) && (ed < radix)){ 419 | Digit res = ed; 420 | ed = radix; 421 | return res; 422 | } 423 | return radix; 424 | } 425 | 426 | // coroutine states 427 | std::vector base; 428 | // BI: current BigInt to producer 429 | // VSize: BI > base[VSize] > sqrt(BI) 430 | // SizeT: the output string shall be SizeT long, or 0 if no leading zero needed 431 | std::stack> dStack; 432 | // {fd}^(rf)+{md}+{rd}^(rf)+{ed} 433 | Digit fd, md, rd, ed; 434 | SizeT rf, rr; 435 | 436 | // coroutine arguments 437 | Digit radix; 438 | }; // class _GenericRadix 439 | // signed Digit 440 | template 441 | class _GenericRadix::value>::type> 443 | :public DigitProducerCRTP>{ 444 | private: 445 | using Unsigned = typename std::make_unsigned::type; 446 | using base = _GenericRadix; 447 | public: 448 | _GenericRadix(const _GenericRadix &) = default; 449 | _GenericRadix(_GenericRadix &&) = delete; 450 | 451 | _GenericRadix &operator=(const _GenericRadix &) = delete; 452 | _GenericRadix &operator=(_GenericRadix &&) = delete; 453 | 454 | ~_GenericRadix() = default; 455 | 456 | template ::value>::type * = nullptr> 458 | explicit _GenericRadix(BIRef &&_lhs, Digit radix) 459 | :producer(std::forward(_lhs), Unsigned(radix)){} 460 | 461 | virtual Digit _start(){ 462 | Unsigned tmp = producer._start(); 463 | return tmp; 464 | } 465 | 466 | virtual Digit _next(){ 467 | Unsigned tmp = producer._next(); 468 | return tmp; 469 | } 470 | 471 | virtual bool _hasNext() const{ 472 | return producer._hasNext(); 473 | } 474 | private: 475 | base producer; 476 | }; 477 | 478 | // unsigned digit 479 | template 480 | class _DecimalRadix::value>::type> 482 | :public DigitProducerCRTP>{ 483 | private: 484 | using VSize = typename std::vector::size_type; 485 | using SizeT = typename BI::SizeT; 486 | 487 | constexpr static Digit radix = 10; 488 | public: 489 | _DecimalRadix(const _DecimalRadix &) = default; 490 | _DecimalRadix(_DecimalRadix &&) = delete; 491 | 492 | _DecimalRadix &operator=(const _DecimalRadix &) = delete; 493 | _DecimalRadix &operator=(_DecimalRadix &&) = delete; 494 | 495 | ~_DecimalRadix() = default; 496 | 497 | template ::value>::type * = nullptr> 499 | explicit _DecimalRadix(BIRef &&_lhs) 500 | :decimalBase(BI::getDecimalBase()), fd(0), md(radix), rd(0), ed(radix), rf(0), rr(0){ 501 | assert(_lhs.positive); 502 | 503 | if(_lhs.isZero()){ 504 | fd = 0; 505 | rf = 1; 506 | md = radix; 507 | rd = 0; 508 | rr = 0; 509 | ed = radix; 510 | return ; 511 | } 512 | 513 | if(_lhs.buf.len == 1){ 514 | if(_lhs.buf.data[0] < radix){ 515 | fd = Digit(_lhs.buf.data[0]); 516 | rf = 1; 517 | md = radix; 518 | rd = 0; 519 | rr = 0; 520 | ed = radix; 521 | return ; 522 | } 523 | } 524 | 525 | for(VSize k(0);k < decimalBase.size();++k){ 526 | std::int8_t comp = decimalBase[k].compare(_lhs); 527 | if(0 == comp){ 528 | fd = 0; 529 | rf = 0; 530 | md = 1; 531 | rd = 0; 532 | rr = SizeT(1 << k); 533 | ed = radix; 534 | return ; 535 | } 536 | if(1 == comp){ 537 | dStack.emplace(std::forward(_lhs), k, 0); 538 | return ; 539 | } 540 | } 541 | 542 | if(dStack.empty()){ 543 | do{ 544 | BI next = decimalBase.back(); 545 | next.selfMultiply(); 546 | std::int8_t comp = next.compare(_lhs); 547 | if(-1 == comp){ 548 | decimalBase.push_back(std::move(next)); 549 | continue; 550 | } 551 | if(0 == comp){ 552 | fd = 0; 553 | rf = 0; 554 | md = 1; 555 | rf = 0; 556 | rr = SizeT(1 << decimalBase.size()); 557 | ed = radix; 558 | return ; 559 | } 560 | if(1 == comp){ 561 | dStack.emplace(std::forward(_lhs), decimalBase.size(), 0); 562 | break; 563 | } 564 | }while(true); 565 | } 566 | return ; 567 | } 568 | 569 | virtual Digit _start(){ 570 | return _next(); 571 | } 572 | 573 | virtual Digit _next(){ 574 | assert(_hasNext()); 575 | 576 | { 577 | Digit res = trivalDigits(); 578 | if(res != radix){ 579 | return res; 580 | } 581 | } 582 | 583 | while(true){ 584 | assert(!dStack.empty()); 585 | if(std::get<0>(dStack.top()).isZero()){ 586 | assert(std::get<2>(dStack.top()) == static_cast(1 << std::get<1>(dStack.top()))); 587 | ed = radix; 588 | rd = 0; 589 | rr = 0; 590 | md = radix; 591 | fd = 0; 592 | rf = std::get<2>(dStack.top()); 593 | dStack.pop(); 594 | return trivalDigits(); 595 | } 596 | //if((std::get<0>(dStack.top()).buf.len == 1) && (std::get<0>(dStack.top()).buf.data[0] < radix)){ 597 | if(std::get<0>(dStack.top()).compareInt(Digit(radix), std::false_type()) == -1){ 598 | Digit tmp = std::get<0>(dStack.top()).buf.data[0]; 599 | rr = 0; 600 | rd = 0; 601 | ed = radix; 602 | if(std::get<2>(dStack.top()) == 0){ 603 | md = radix; 604 | rf = 1; 605 | fd = tmp; 606 | } 607 | else{ 608 | md = tmp; 609 | rf = std::get<2>(dStack.top()) - 1; 610 | fd = 0; 611 | } 612 | dStack.pop(); 613 | return trivalDigits(); 614 | } 615 | 616 | VSize k = std::get<1>(dStack.top()); 617 | std::int8_t comp; 618 | do{ 619 | --k; 620 | comp = decimalBase[k].compare(std::get<0>(dStack.top())); 621 | if(1 == comp){ 622 | continue; 623 | } 624 | else{ 625 | break; 626 | } 627 | assert(k != 0); 628 | }while(true); 629 | 630 | if(0 == comp){ 631 | ed = radix; 632 | md = 1; 633 | rd = 0; 634 | rr = static_cast(1 << k); 635 | fd = 0; 636 | rf = std::get<2>(dStack.top()); 637 | if(rf != 0){ 638 | rf -= 1 + rr; 639 | } 640 | dStack.pop(); 641 | return trivalDigits(); 642 | } 643 | 644 | assert(-1 == comp); 645 | std::pair qr = std::move(std::get<0>(dStack.top())).divideByMedium(decimalBase[k]); 646 | SizeT rLen = SizeT(1 << k); 647 | SizeT qLen = std::get<2>(dStack.top()); 648 | if(qLen != 0){ 649 | assert(qLen > rLen); 650 | qLen -= rLen; 651 | } 652 | dStack.pop(); 653 | 654 | //if((qr.first.buf.len == 1) && (qr.first.buf.data[0] < radix)){ 655 | if(qr.first.compareInt(Digit(radix), std::false_type{}) == -1){ 656 | assert(!qr.first.isZero()); 657 | Digit tmp = qr.first.buf.data[0]; 658 | if(qLen == 0){ 659 | rf = 0; 660 | } 661 | else{ 662 | rf = qLen - 1; 663 | } 664 | 665 | if(qr.second.isZero()){ 666 | ed = radix; 667 | rd = 0; 668 | rr = rLen; 669 | md = tmp; 670 | fd = 0; 671 | return trivalDigits(); 672 | } 673 | //if((qr.second.buf.len == 1) && (qr.second.buf.data[0] < radix)){ 674 | if(qr.second.compareInt(Digit(radix), std::false_type()) == -1){ 675 | ed = qr.second.buf.data[0]; 676 | rd = 0; 677 | rr = rLen - 1; 678 | md = tmp; 679 | fd = 0; 680 | return trivalDigits(); 681 | } 682 | else{ 683 | dStack.emplace(std::move(qr.second), k, rLen); 684 | ed = radix; 685 | rd = 0; 686 | rr = 0; 687 | md = tmp; 688 | fd = 0; 689 | return trivalDigits(); 690 | } 691 | } 692 | else{ 693 | dStack.emplace(std::move(qr.second), k, rLen); 694 | dStack.emplace(std::move(qr.first), k, qLen); 695 | continue; 696 | } 697 | }// while(true) 698 | // should never be reached 699 | assert(false); 700 | return 0; 701 | } 702 | 703 | virtual bool _hasNext() const{ 704 | if(rf > 0){ 705 | assert((fd >= 0) && (fd < radix)); 706 | return true; 707 | } 708 | if((md >= 0) && (md < radix)){ 709 | return true; 710 | } 711 | if(rr > 0){ 712 | assert((rd >= 0) && (rd < radix)); 713 | return true; 714 | } 715 | if((ed >= 0) && (ed < radix)){ 716 | return true; 717 | } 718 | return !dStack.empty(); 719 | } 720 | private: 721 | inline Digit trivalDigits(){ 722 | if(rf > 0){ 723 | --rf; 724 | return fd; 725 | } 726 | if((md >= 0) && (md < radix)){ 727 | Digit res = md; 728 | md = radix; 729 | return res; 730 | } 731 | if(rr > 0){ 732 | --rr; 733 | return rd; 734 | } 735 | if((ed >= 0) && (ed < radix)){ 736 | Digit res = ed; 737 | ed = radix; 738 | return res; 739 | } 740 | return radix; 741 | } 742 | 743 | // coroutine state 744 | // TODO: make write operations on decimalBase thread-safe 745 | std::vector &decimalBase; 746 | std::stack> dStack; 747 | Digit fd, md, rd, ed; 748 | SizeT rf, rr; 749 | };// class _DecimalRadix 750 | // signed digit 751 | template 752 | class _DecimalRadix::value>::type> 754 | :public DigitProducerCRTP>{ 755 | private: 756 | using Unsigned = typename std::make_unsigned::type; 757 | using base = _DecimalRadix; 758 | public: 759 | _DecimalRadix(const _DecimalRadix &) = default; 760 | _DecimalRadix(_DecimalRadix &&) = delete; 761 | 762 | _DecimalRadix &operator=(const _DecimalRadix &) = delete; 763 | _DecimalRadix &operator=(_DecimalRadix &&) = delete; 764 | 765 | ~_DecimalRadix() = default; 766 | 767 | template ::value>::type * = nullptr> 769 | explicit _DecimalRadix(BIRef &&_lhs) 770 | :producer(std::forward(_lhs)){} 771 | 772 | virtual Digit _start(){ 773 | Unsigned tmp = producer._start(); 774 | return tmp; 775 | } 776 | 777 | virtual Digit _next(){ 778 | Unsigned tmp = producer._next(); 779 | return tmp; 780 | } 781 | 782 | virtual bool _hasNext() const{ 783 | return producer._hasNext(); 784 | } 785 | private: 786 | base producer; 787 | }; 788 | 789 | // unsigned digit 790 | template 791 | class _SmallPower2Radix::value>::type> 793 | :public DigitProducerCRTP>{ 794 | private: 795 | using SizeT = typename BI::SizeT; 796 | using Ele = typename BI::Ele; 797 | using LogSizeT = typename BI::LogSizeT; 798 | 799 | constexpr static Ele ENTRY_SIZE = BI::ENTRY_SIZE; 800 | public: 801 | _SmallPower2Radix(const _SmallPower2Radix &) = default; 802 | _SmallPower2Radix(_SmallPower2Radix &&) = delete; 803 | 804 | _SmallPower2Radix &operator=(const _SmallPower2Radix &) = delete; 805 | _SmallPower2Radix &operator=(_SmallPower2Radix &&) = delete; 806 | 807 | ~_SmallPower2Radix() = default; 808 | 809 | explicit _SmallPower2Radix(const BI &_lhs, SizeT _exp) 810 | :lhs(_lhs), exp(_exp), curI(_lhs.buf.len), curBit(0){ 811 | assert(exp < ENTRY_SIZE); 812 | } 813 | 814 | virtual Digit _start(){ 815 | if(lhs.isZero()){ 816 | curI = 0; 817 | curBit = 0; 818 | return static_cast(0); 819 | } 820 | 821 | LogSizeT highest = (lhs.buf.len * ENTRY_SIZE) % exp; 822 | Ele highestLeft = lhs.buf.data[lhs.buf.len - 1] >> (ENTRY_SIZE - highest); 823 | curI = lhs.buf.len - 1; 824 | curBit = ENTRY_SIZE - highest; 825 | if(highestLeft > 0){ 826 | return static_cast(highestLeft); 827 | } 828 | do{ 829 | Ele digit = 0; 830 | if(curBit >= exp){ 831 | digit = (lhs.buf.data[curI] >> (curBit - exp)) & ((1 << exp) - 1); 832 | curBit -= exp; 833 | } 834 | else{ 835 | assert(curI > 0); 836 | digit = ((lhs.buf.data[curI] & ((1 << curBit) - 1)) << (exp - curBit)) | (lhs.buf.data[curI - 1] >> (curBit + ENTRY_SIZE - exp)); 837 | curBit += ENTRY_SIZE - exp; 838 | --curI; 839 | assert(digit > 0); 840 | } 841 | if(digit > 0){ 842 | return static_cast(digit); 843 | } 844 | }while(true); 845 | } 846 | 847 | virtual Digit _next(){ 848 | assert(_hasNext()); 849 | 850 | Ele digit = 0; 851 | if(curBit >= exp){ 852 | digit = (lhs.buf.data[curI] >> (curBit - exp)) & ((1 << exp) - 1); 853 | curBit -= exp; 854 | } 855 | else{ 856 | assert(curI > 0); 857 | digit = ((lhs.buf.data[curI] & ((1 << curBit) - 1)) << (exp - curBit)) | (lhs.buf.data[curI - 1] >> (curBit + ENTRY_SIZE - exp)); 858 | curBit += ENTRY_SIZE - exp; 859 | --curI; 860 | } 861 | return static_cast(digit); 862 | } 863 | 864 | virtual bool _hasNext() const{ 865 | return (curBit > 0) || (curI > 0); 866 | } 867 | private: 868 | // coroutine arguments 869 | // lhs dangling after its parent RadixConvertEnumer objects invalidates 870 | // pretty much like what pointer behaves after its referencing memory 871 | // invalidates 872 | const BI &lhs; 873 | SizeT exp; 874 | 875 | // coroutine states 876 | LogSizeT curBit; 877 | SizeT curI; 878 | };// class _SmallPower2Radix 879 | // signed digit 880 | template 881 | class _SmallPower2Radix::value>::type> 883 | :public DigitProducerCRTP>{ 884 | private: 885 | using Unsigned = typename std::make_unsigned::type; 886 | using base = _SmallPower2Radix; 887 | 888 | using SizeT = typename BI::SizeT; 889 | public: 890 | _SmallPower2Radix(const _SmallPower2Radix &) = default; 891 | _SmallPower2Radix(_SmallPower2Radix &&) = delete; 892 | 893 | _SmallPower2Radix &operator=(const _SmallPower2Radix &) = delete; 894 | _SmallPower2Radix &operator=(_SmallPower2Radix &&) = delete; 895 | 896 | ~_SmallPower2Radix() = default; 897 | 898 | explicit _SmallPower2Radix(const BI &_lhs, SizeT _exp) 899 | :producer(_lhs, _exp){} 900 | 901 | virtual Digit _start(){ 902 | Unsigned tmp = producer._start(); 903 | return tmp; 904 | } 905 | 906 | virtual Digit _next(){ 907 | Unsigned tmp = producer._next(); 908 | return tmp; 909 | } 910 | 911 | virtual bool _hasNext() const{ 912 | return producer._hasNext(); 913 | } 914 | private: 915 | base producer; 916 | }; 917 | 918 | // unsigned digit 919 | template 920 | class _LargePower2Radix::value>::type> 922 | :public DigitProducerCRTP>{ 923 | private: 924 | using SizeT = typename BI::SizeT; 925 | using Ele = typename BI::Ele; 926 | using LogSizeT = typename BI::LogSizeT; 927 | 928 | constexpr static Ele ENTRY_SIZE = BI::ENTRY_SIZE; 929 | public: 930 | _LargePower2Radix(const _LargePower2Radix &) = default; 931 | _LargePower2Radix(_LargePower2Radix &&) = delete; 932 | 933 | _LargePower2Radix &operator=(const _LargePower2Radix &) = delete; 934 | _LargePower2Radix &operator=(_LargePower2Radix &&) = delete; 935 | 936 | ~_LargePower2Radix() = default; 937 | 938 | explicit _LargePower2Radix(const BI &_lhs, SizeT _exp) 939 | :lhs(_lhs), exp(_exp), curI(_lhs.buf.len), curBit(0){ 940 | assert(exp > ENTRY_SIZE); 941 | } 942 | 943 | virtual Digit _start(){ 944 | curI = lhs.buf.len - 1; 945 | curBit = ENTRY_SIZE; 946 | 947 | SizeT leftBit = (lhs.buf.len * ENTRY_SIZE) % exp; 948 | SizeT leftI = leftBit / ENTRY_SIZE; 949 | LogSizeT leftLeft = leftBit % ENTRY_SIZE; 950 | 951 | Digit highest = 0; 952 | for(SizeT i = 0;i < leftI;++i){ 953 | highest = (highest << ENTRY_SIZE) | static_cast(lhs.buf.data[curI - i]); 954 | } 955 | highest = (highest << leftLeft) | static_cast(lhs.buf.data[curI - leftI] >> (ENTRY_SIZE - leftLeft)); 956 | assert((leftI == 0) || (highest > 0)); 957 | 958 | assert((leftLeft == 0) || (curI >= leftI)); 959 | assert((leftLeft > 0) || (curI >= leftI - 1)); 960 | if(leftLeft > 0){ 961 | curI -= leftI; 962 | } 963 | else{ 964 | curI -= leftI - 1; 965 | } 966 | curBit -= leftLeft; 967 | 968 | if(highest > 0){ 969 | return highest; 970 | } 971 | else{ 972 | return _next(); 973 | } 974 | } 975 | 976 | virtual Digit _next(){ 977 | assert(_hasNext()); 978 | 979 | SizeT stepI = (exp - curBit) / ENTRY_SIZE; 980 | LogSizeT leftStep = (exp - curBit) % ENTRY_SIZE; 981 | Digit digit = lhs.buf.data[curI] & ((Digit(1) << curBit) - 1); 982 | for(SizeT i(1);i <= stepI;++i){ 983 | digit = (digit << ENTRY_SIZE) | static_cast(lhs.buf.data[curI - i]); 984 | } 985 | if(leftStep > 0){ 986 | assert(curI > stepI); 987 | digit = (digit << leftStep) | (static_cast(lhs.buf.data[curI - stepI - 1]) >> (ENTRY_SIZE - leftStep)); 988 | curI -= stepI + 1; 989 | curBit = ENTRY_SIZE - leftStep; 990 | } 991 | else{ 992 | assert(curI >= stepI); 993 | curI -= stepI; 994 | curBit = 0; 995 | } 996 | 997 | return digit; 998 | } 999 | 1000 | virtual bool _hasNext() const{ 1001 | return (curBit > 0) || (curI > 0); 1002 | } 1003 | private: 1004 | // coroutine arguments 1005 | const BI &lhs; 1006 | SizeT exp; 1007 | 1008 | // coroutine states 1009 | SizeT curI; 1010 | LogSizeT curBit; 1011 | };// class _LargePower2Radix 1012 | // signed digit 1013 | template 1014 | class _LargePower2Radix::value>::type> 1016 | :public DigitProducerCRTP>{ 1017 | private: 1018 | using Unsigned = typename std::make_unsigned::type; 1019 | using base = _LargePower2Radix; 1020 | 1021 | using SizeT = typename BI::SizeT; 1022 | public: 1023 | _LargePower2Radix(const _LargePower2Radix &) = default; 1024 | _LargePower2Radix(_LargePower2Radix &&) = delete; 1025 | 1026 | _LargePower2Radix &operator=(const _LargePower2Radix &) = delete; 1027 | _LargePower2Radix &operator=(_LargePower2Radix &&) = delete; 1028 | 1029 | ~_LargePower2Radix() = default; 1030 | 1031 | explicit _LargePower2Radix(const BI &_lhs, SizeT _exp) 1032 | :producer(_lhs, _exp){} 1033 | 1034 | virtual Digit _start(){ 1035 | Unsigned tmp = producer._start(); 1036 | return tmp; 1037 | } 1038 | 1039 | virtual Digit _next(){ 1040 | Unsigned tmp = producer._next(); 1041 | return tmp; 1042 | } 1043 | 1044 | virtual bool _hasNext() const{ 1045 | return producer._hasNext(); 1046 | } 1047 | private: 1048 | base producer; 1049 | }; 1050 | 1051 | // TODO: do some meta-programming trick to generate code directly operating on 1052 | // raw pointers 1053 | template 1054 | class _ExactDigitExtract:public DigitProducerCRTP>{ 1055 | private: 1056 | using Ptr = typename BI::Ptr; 1057 | using SizeT = typename BI::SizeT; 1058 | public: 1059 | _ExactDigitExtract(const _ExactDigitExtract &) = default; 1060 | _ExactDigitExtract(_ExactDigitExtract &&) = delete; 1061 | 1062 | _ExactDigitExtract &operator=(const _ExactDigitExtract &) = delete; 1063 | _ExactDigitExtract &operator=(_ExactDigitExtract &&) = delete; 1064 | 1065 | ~_ExactDigitExtract() = default; 1066 | 1067 | explicit _ExactDigitExtract(Ptr _begin, SizeT _len) 1068 | :begin(_begin), end(begin + _len), current(end){} 1069 | 1070 | virtual Digit _start(){ 1071 | return _next(); 1072 | } 1073 | 1074 | virtual Digit _next(){ 1075 | assert(_hasNext()); 1076 | --current; 1077 | return static_cast(*current); 1078 | } 1079 | 1080 | virtual bool _hasNext() const{ 1081 | return current != begin; 1082 | } 1083 | private: 1084 | Ptr begin, end, current; 1085 | };// class _ExactDigitExtract 1086 | 1087 | template 1088 | class RadixConvertEnumer{ 1089 | private: 1090 | using SizeT = typename BI::SizeT; 1091 | 1092 | using Ele = typename BI::Ele; 1093 | constexpr static Ele ENTRY_SIZE = BI::ENTRY_SIZE; 1094 | public: 1095 | using iterator = _type::DigitEnumIterator; 1096 | 1097 | RadixConvertEnumer(const RadixConvertEnumer &) = default; 1098 | RadixConvertEnumer(RadixConvertEnumer &&) = default; 1099 | 1100 | RadixConvertEnumer &operator=(const RadixConvertEnumer &) = default; 1101 | RadixConvertEnumer &operator=(RadixConvertEnumer &&) = default; 1102 | 1103 | ~RadixConvertEnumer() = default; 1104 | 1105 | // TODO: avoid unnecessary copy/moves 1106 | template ::value>::type * = nullptr> 1108 | explicit RadixConvertEnumer(BIRef &&_num, Digit _radix) 1109 | :num(std::forward(_num)), radix(_radix){ 1110 | if(!num.positive){ 1111 | num.positive = true; 1112 | assert(!num.isZero()); 1113 | } 1114 | } 1115 | 1116 | iterator begin() const{ 1117 | return beginImpl(std::integral_constant::value>{}); 1118 | } 1119 | 1120 | iterator end() const{ 1121 | return iterator(nullptr); 1122 | } 1123 | private: 1124 | // unsigned radix 1125 | iterator beginImpl(std::false_type) const{ 1126 | if(radix < 2){ 1127 | throw std::domain_error("a radix less than 2 is not accepted."); 1128 | // errno = EDOM; 1129 | } 1130 | 1131 | DigitProducer *producer = nullptr; 1132 | if(radix == 10){ 1133 | producer = new _DecimalRadix(std::move(num)); 1134 | } 1135 | if((radix & ((~radix) + 1)) == radix){ 1136 | SizeT exp = static_cast(std::ceil(std::log2(radix))); 1137 | if(exp < ENTRY_SIZE){ 1138 | producer = new _SmallPower2Radix(num, exp); 1139 | } 1140 | if(exp == ENTRY_SIZE){ 1141 | producer = new _ExactDigitExtract(num.buf.data, num.buf.len); 1142 | } 1143 | if(exp > ENTRY_SIZE){ 1144 | producer = new _LargePower2Radix(num, exp); 1145 | } 1146 | assert(nullptr != producer); 1147 | } 1148 | if(nullptr == producer){ 1149 | producer = new _GenericRadix(std::move(num), radix); 1150 | } 1151 | return iterator(producer); 1152 | } 1153 | // signed radix 1154 | iterator beginImpl(std::true_type) const{ 1155 | if(radix > 1){ 1156 | return beginImpl(std::false_type{}); 1157 | } 1158 | 1159 | if(radix < -1){ 1160 | // TODO: implement conversion to negative base 1161 | assert(false); 1162 | } 1163 | 1164 | throw std::domain_error("a radix less than 2 and greater than -2 is not accepted."); 1165 | // errno = EDOM; 1166 | } 1167 | 1168 | BI num; 1169 | Digit radix; 1170 | };// class RadixConvertEnumer 1171 | 1172 | template 1173 | inline decltype(auto) begin(const RadixConvertEnumer &c){ 1174 | return c.begin(); 1175 | } 1176 | 1177 | template 1178 | inline decltype(auto) end(const RadixConvertEnumer &c){ 1179 | return c.end(); 1180 | } 1181 | 1182 | };// namespace bignum 1183 | #endif // _BIG_INT_OUTPUT_HPP_ -------------------------------------------------------------------------------- /BigNum.hpp: -------------------------------------------------------------------------------- 1 | #ifndef _BIG_NUM_HPP_ 2 | #define _BIG_NUM_HPP_ 3 | 4 | #include "BigInt.hpp" 5 | #endif // _BIG_NUM_HPP_ -------------------------------------------------------------------------------- /LICENSE.BSD3c: -------------------------------------------------------------------------------- 1 | Here is the license template: 2 | 3 | Copyright (c) 2016-2017, gnaggnoyil(gnaggnoyil at gmail.com) 4 | All rights reserved. 5 | 6 | Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 7 | 8 | 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 9 | 10 | 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 11 | 12 | 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. 13 | 14 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 15 | -------------------------------------------------------------------------------- /LICENSE.GPLv2: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 2, June 1991 3 | 4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc. 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | 7 | Everyone is permitted to copy and distribute verbatim copies 8 | of this license document, but changing it is not allowed. 9 | 10 | Preamble 11 | 12 | The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Library General Public License instead.) You can apply it to your programs, too. 13 | 14 | When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. 15 | 16 | To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. 17 | 18 | For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. 19 | 20 | We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. 21 | 22 | Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. 23 | 24 | Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. 25 | 26 | The precise terms and conditions for copying, distribution and modification follow. 27 | 28 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 29 | 30 | 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". 31 | 32 | Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 33 | 34 | 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. 35 | 36 | You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 37 | 38 | 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: 39 | 40 | a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. 41 | 42 | b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. 43 | 44 | c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) 45 | 46 | These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. 47 | 48 | Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. 49 | 50 | In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 51 | 52 | 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: 53 | 54 | a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, 55 | 56 | b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, 57 | 58 | c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) 59 | 60 | The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. 61 | 62 | If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 63 | 64 | 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 65 | 66 | 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 67 | 68 | 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 69 | 70 | 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. 71 | 72 | If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. 73 | 74 | It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. 75 | 76 | This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 77 | 78 | 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 79 | 80 | 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. 81 | 82 | Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 83 | 84 | 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. 85 | 86 | NO WARRANTY 87 | 88 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 89 | 90 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 91 | 92 | END OF TERMS AND CONDITIONS 93 | 94 | How to Apply These Terms to Your New Programs 95 | 96 | If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. 97 | 98 | To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. 99 | 100 | One line to give the program's name and a brief idea of what it does. 101 | Copyright (C) 2016-2017 gnaggnoyil (gnaggnoyil at gmail.com) 102 | 103 | This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. 104 | 105 | This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. 106 | 107 | You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 108 | 109 | Also add information on how to contact you by electronic and paper mail. 110 | 111 | If the program is interactive, make it output a short notice like this when it starts in an interactive mode: 112 | 113 | Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. 114 | 115 | The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. 116 | 117 | You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: 118 | 119 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. 120 | 121 | signature of Ty Coon, 1 April 1989 122 | Ty Coon, President of Vice 123 | 124 | This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Library General Public License instead of this License. 125 | -------------------------------------------------------------------------------- /LICENSE.LGPLv3: -------------------------------------------------------------------------------- 1 | GNU LESSER GENERAL PUBLIC LICENSE 2 | 3 | Version 3, 29 June 2007 4 | 5 | Copyright © 2007 Free Software Foundation, Inc. 6 | 7 | Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. 8 | 9 | This version of the GNU Lesser General Public License incorporates the terms and conditions of version 3 of the GNU General Public License, supplemented by the additional permissions listed below. 10 | 11 | 0. Additional Definitions. 12 | 13 | As used herein, “this License” refers to version 3 of the GNU Lesser General Public License, and the “GNU GPL” refers to version 3 of the GNU General Public License. 14 | 15 | “The Library” refers to a covered work governed by this License, other than an Application or a Combined Work as defined below. 16 | 17 | An “Application” is any work that makes use of an interface provided by the Library, but which is not otherwise based on the Library. Defining a subclass of a class defined by the Library is deemed a mode of using an interface provided by the Library. 18 | 19 | A “Combined Work” is a work produced by combining or linking an Application with the Library. The particular version of the Library with which the Combined Work was made is also called the “Linked Version”. 20 | 21 | The “Minimal Corresponding Source” for a Combined Work means the Corresponding Source for the Combined Work, excluding any source code for portions of the Combined Work that, considered in isolation, are based on the Application, and not on the Linked Version. 22 | 23 | The “Corresponding Application Code” for a Combined Work means the object code and/or source code for the Application, including any data and utility programs needed for reproducing the Combined Work from the Application, but excluding the System Libraries of the Combined Work. 24 | 25 | 1. Exception to Section 3 of the GNU GPL. 26 | 27 | You may convey a covered work under sections 3 and 4 of this License without being bound by section 3 of the GNU GPL. 28 | 29 | 2. Conveying Modified Versions. 30 | 31 | If you modify a copy of the Library, and, in your modifications, a facility refers to a function or data to be supplied by an Application that uses the facility (other than as an argument passed when the facility is invoked), then you may convey a copy of the modified version: 32 | 33 | a) under this License, provided that you make a good faith effort to ensure that, in the event an Application does not supply the function or data, the facility still operates, and performs whatever part of its purpose remains meaningful, or 34 | 35 | b) under the GNU GPL, with none of the additional permissions of this License applicable to that copy. 36 | 37 | 3. Object Code Incorporating Material from Library Header Files. 38 | 39 | The object code form of an Application may incorporate material from a header file that is part of the Library. You may convey such object code under terms of your choice, provided that, if the incorporated material is not limited to numerical parameters, data structure layouts and accessors, or small macros, inline functions and templates (ten or fewer lines in length), you do both of the following: 40 | 41 | a) Give prominent notice with each copy of the object code that the Library is used in it and that the Library and its use are covered by this License. 42 | 43 | b) Accompany the object code with a copy of the GNU GPL and this license document. 44 | 45 | 4. Combined Works. 46 | 47 | You may convey a Combined Work under terms of your choice that, taken together, effectively do not restrict modification of the portions of the Library contained in the Combined Work and reverse engineering for debugging such modifications, if you also do each of the following: 48 | a) Give prominent notice with each copy of the Combined Work that the Library is used in it and that the Library and its use are covered by this License. 49 | 50 | b) Accompany the Combined Work with a copy of the GNU GPL and this license document. 51 | 52 | c) For a Combined Work that displays copyright notices during execution, include the copyright notice for the Library among these notices, as well as a reference directing the user to the copies of the GNU GPL and this license document. 53 | 54 | d) Do one of the following: ◦0) Convey the Minimal Corresponding Source under the terms of this License, and the Corresponding Application Code in a form suitable for, and under terms that permit, the user to recombine or relink the Application with a modified version of the Linked Version to produce a modified Combined Work, in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source. 55 | 56 | ◦1) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (a) uses at run time a copy of the Library already present on the user's computer system, and (b) will operate properly with a modified version of the Library that is interface-compatible with the Linked Version. 57 | 58 | e) Provide Installation Information, but only if you would otherwise be required to provide such information under section 6 of the GNU GPL, and only to the extent that such information is necessary to install and execute a modified version of the Combined Work produced by recombining or relinking the Application with a modified version of the Linked Version. (If you use option 4d0, the Installation Information must accompany the Minimal Corresponding Source and Corresponding Application Code. If you use option 4d1, you must provide the Installation Information in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source.) 59 | 60 | 5. Combined Libraries. 61 | 62 | You may place library facilities that are a work based on the Library side by side in a single library together with other library facilities that are not Applications and are not covered by this License, and convey such a combined library under terms of your choice, if you do both of the following: 63 | 64 | a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities, conveyed under the terms of this License. 65 | 66 | b) Give prominent notice with the combined library that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 67 | 68 | 6. Revised Versions of the GNU Lesser General Public License. 69 | 70 | The Free Software Foundation may publish revised and/or new versions of the GNU Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. 71 | 72 | Each version is given a distinguishing version number. If the Library as you received it specifies that a certain numbered version of the GNU Lesser General Public License “or any later version” applies to it, you have the option of following the terms and conditions either of that published version or of any later version published by the Free Software Foundation. If the Library as you received it does not specify a version number of the GNU Lesser General Public License, you may choose any version of the GNU Lesser General Public License ever published by the Free Software Foundation. 73 | 74 | If the Library as you received it specifies that a proxy can decide whether future versions of the GNU Lesser General Public License shall apply, that proxy's public statement of acceptance of any version is permanent authorization for you to choose that version for the Library. 75 | -------------------------------------------------------------------------------- /LICENSE.MIT: -------------------------------------------------------------------------------- 1 | Copyright (c) 2016-2017 gnaggnoyil(gnagnoyil at gmail.com) 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 4 | 5 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 6 | 7 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 8 | -------------------------------------------------------------------------------- /Libs/BigNumFFT.hpp: -------------------------------------------------------------------------------- 1 | #ifndef _BIG_NUM_HPP_ 2 | #error "This header must be included through BigNum.hpp" 3 | #endif // _BIG_NUM_HPP_ 4 | 5 | #ifndef _BIG_NUM_FFT_HPP_ 6 | #define _BIG_NUM_FFT_HPP_ 7 | 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | 14 | #include "BigNumTypeTrait.hpp" 15 | 16 | namespace bignum{ 17 | 18 | /*namespace _type{ 19 | 20 | template 21 | class RingTraits{ 22 | public: 23 | template ::value>::type * = nullptr, 25 | typename std::enable_if::value>::type * = nullptr> 26 | inline static Ring add(RingRef1 &&_lhs, RingRef2 &&_rhs){ 27 | return std::forward(_lhs) + std::forward(_rhs); 28 | } 29 | template ::value>::type * = nullptr> 31 | inline static void selfAdd(Ring &_lhs, RingRef &&_rhs){ 32 | _lhs += std::foward(_rhs); 33 | } 34 | 35 | template ::value>::type * = nullptr, 37 | typename std::enable_if::value>::type * = nullptr> 38 | inline static Ring sub(RingRef1 &&_lhs, RingRef2 &&_rhs){ 39 | return std::forward(_lhs) - std::forward(_rhs); 40 | } 41 | template ::value>::type * = nullptr> 43 | inline static void selfSub(Ring &_lhs, RingRef &&_rhs){ 44 | _lhs -= std::foward(_rhs); 45 | } 46 | 47 | template ::value>::type * = nullptr, 49 | typename std::enable_if::value>::type * = nullptr> 50 | inline static Ring mult(RingRef1 &&_lhs, RingRef2 &&_rhs){ 51 | return std::forward(_lhs) * std::forward(_rhs); 52 | } 53 | template ::value>::type * = nullptr> 55 | inline static void selfMult(Ring &_lhs, RingRef &&_rhs){ 56 | _lhs *= std::foward(_rhs); 57 | } 58 | 59 | template ::value>::type * = nullptr> 61 | inline static Ring pow(RingRef &&_lhs, std::size_t _rhs){ 62 | using std::pow; 63 | return pow(_lhs, _rhs); 64 | } 65 | }; 66 | 67 | }; // namespace _type*/ 68 | 69 | namespace _utility{ 70 | 71 | /*template 72 | inline static void fft1DPower2Impl(typename std::iterator_traits::size_type sizeN, 73 | InIter in, RndIter out, Trait, 74 | typename std::iterator_traits::value_type omega, 75 | std::input_iterator_tag, std::random_access_iterator_tag){ 76 | assert((sizeN & ((~sizeN) + 1)) == sizeN); 77 | 78 | using std::swap; 79 | 80 | using SizeT = typename std::iterator_traits::size_type; 81 | 82 | InIter inIter = in; 83 | RndIter outIter = out; 84 | for(SizeT i = 0;i < sizeN;++i){ 85 | *outIter = *inIter; 86 | ++outIter; 87 | ++inIter; 88 | } 89 | 90 | SizeT preRev = 0; rev; 91 | for(SizeT i = 1;i < sizeN;++i){ 92 | SizeT tmp = sizeN >> 1; 93 | for(rev = preRev;(rev & tmp) != 0;tmp >>= 1){ 94 | rev -= tmp; 95 | } 96 | rev += tmp; 97 | preRev = rev; 98 | 99 | if(rev < i){ 100 | swap(*(out + i), *(out + rev)); 101 | } 102 | } 103 | 104 | using Ring = typename std::iterator_traits::value_type; 105 | 106 | for(SizeT m = 2;m <= sizeN;m <<= 1){ 107 | Ring w0 = Trait::pow(omega, sizeN / m); 108 | Ring w = 1; 109 | for(SizeT i = 0, mh = m >> 1;i < mh;++i){ 110 | for(SizeT j = i;j < sizeN;j += m){ 111 | SizeT k = j + mh; 112 | Ring x = Trait::multi(w, *(out + k)); 113 | *(out + k) = Trait::sub(*(out + j), x); 114 | *(out + j) = Trait::add(*(out + j), x); 115 | } 116 | } 117 | Trait::selfMult(w, w0); 118 | } 119 | 120 | return ; 121 | } 122 | 123 | template 124 | inline static void fft1DPower2(typename std::iterator_traits::size_type sizeN, 125 | InIter in, RndIter out, 126 | typename std::iterator_traits::value_type omega){ 127 | using Ring = typename std::iterator_traits::value_type; 128 | fft1DPower2Impl(sizeN, in, out, omega, _type::RingTraits{}, 129 | typename std::iterator_traits::iterator_category{}, 130 | typename std::iterator_traits::iterator_category{}); 131 | } 132 | 133 | template 134 | inline static void fft1DPower2(typename std::iterator_traits::size_type sizeN, 135 | InIter in, RndIter out, 136 | typename std::iterator_traits::value_type omega, 137 | Trait){ 138 | fft1DPower2Impl(sizeN, in, out, omega, Trait{}, 139 | typename std::iterator_traits::iterator_category{}, 140 | typename std::iterator_traits::iterator_category{}); 141 | }*/ 142 | 143 | template 144 | inline static void fft1DPower2(std::size_t sizeN, Ring omega, InFunc &&getIn, OutFunc &&getOut){ 145 | assert((sizeN & ((~sizeN) + 1)) == sizeN); 146 | 147 | using std::pow; 148 | using std::swap; 149 | 150 | using Ele = typename std::remove_reference::type>::type; 151 | 152 | for(std::size_t i = 0;i < sizeN;++i){ 153 | getOut(i) = getIn(i); 154 | } 155 | 156 | std::size_t preRev = 0, rev; 157 | for(std::size_t i = 1;i < sizeN;++i){ 158 | std::size_t tmp = sizeN >> 1; 159 | for(rev = preRev;(rev & tmp) != 0;tmp >>= 1){ 160 | rev -= tmp; 161 | } 162 | rev += tmp; 163 | preRev = rev; 164 | 165 | if(rev < i){ 166 | swap(getOut(i), getOut(rev)); 167 | } 168 | } 169 | 170 | for(std::size_t m = 2;m <= sizeN;m <<= 1){ 171 | Ring w0 = pow(omega, sizeN / m); 172 | Ring w(1); 173 | for(std::size_t i = 0, mh = m >> 1;i < mh;++i){ 174 | for(std::size_t j = i;j < sizeN;j += m){ 175 | std::size_t k = j + mh; 176 | Ring x(w * getOut(k)); 177 | getOut(k) = Ele(Ring(getOut(j)) - x); 178 | getOut(j) = Ele(Ring(getOut(j)) + x); 179 | } 180 | w *= w0; 181 | } 182 | } 183 | 184 | return ; 185 | } 186 | 187 | }; // namespace _utility 188 | 189 | }; // namespace bignum 190 | #endif // _BIG_NUM_FFT_HPP_ -------------------------------------------------------------------------------- /Libs/BigNumGenerics.hpp: -------------------------------------------------------------------------------- 1 | #ifndef _BIG_NUM_HPP_ 2 | #error "This header must be included through BigNum.hpp" 3 | #endif // _BIG_NUM_HPP_ 4 | 5 | #ifndef _BIG_NUM_GENERICS_HPP_ 6 | #define _BIG_NUM_GENERICS_HPP_ 7 | 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | 15 | #include "BigNumTypeTrait.hpp" 16 | 17 | namespace bignum{ 18 | 19 | namespace _utility{ 20 | 21 | template 22 | class CharFindHelper{ 23 | public: 24 | static const Char *find(const Char *begin, const Char *end, Int ch) noexcept{ 25 | return std::find_if(begin, end, [&ch](const Char &ele) -> bool{ 26 | return Trait::eq_int_type(ch, Trait::to_int_type(ele)); 27 | }); 28 | } 29 | }; 30 | 31 | }; // namespace _utility 32 | 33 | namespace _type{ 34 | 35 | template 36 | struct CallableHolder; 37 | 38 | template 39 | struct CallableHolder::value>::type> 41 | :private Functor{ 42 | public: 43 | using Functor::operator(); 44 | 45 | template ::value>::type * = nullptr> 47 | explicit constexpr CallableHolder(FunctorRef &&_func) 48 | :Functor(std::forward(_func)){} 49 | }; 50 | 51 | template 52 | struct CallableHolder{ 53 | private: 54 | using FuncPtr = Ret (*)(Args...); 55 | public: 56 | explicit constexpr CallableHolder(FuncPtr _func) 57 | :func(_func){} 58 | 59 | Ret operator()(Args... args) const{ 60 | return (*func)(std::forward(args)...); 61 | } 62 | private: 63 | FuncPtr func; 64 | }; 65 | 66 | template 67 | struct CallableHolder::value>::type> 69 | :private CallableHolder()))>{ 70 | private: 71 | using MemPtr = Ret T::*; 72 | using base = CallableHolder()))>; 73 | public: 74 | explicit constexpr CallableHolder(MemPtr _func) 75 | :base(std::mem_fn(_func)){} 76 | 77 | using base::operator(); 78 | }; 79 | 80 | template 81 | struct CallableOverloader; 82 | 83 | template 84 | struct CallableOverloader:private CallableHolder{ 85 | private: 86 | using base = CallableHolder; 87 | public: 88 | template ::value>::type * = nullptr> 90 | constexpr CallableOverloader(CallableRef &&_func) 91 | :base(std::forward(_func)){} 92 | 93 | using base::operator(); 94 | }; 95 | 96 | template 97 | struct CallableOverloader 98 | :private CallableHolder, private CallableOverloader{ 99 | public: 100 | template , 102 | isRLRef, 103 | isRLRef...>::value>::type * = nullptr> 104 | constexpr CallableOverloader(CallableRef1 &&cr1, CallableRef2 &&cr2, CallableRefs && ...crs) 105 | :CallableHolder(std::forward(cr1)), 106 | CallableOverloader(std::forward(cr2), 107 | std::forward(crs)...){} 108 | 109 | using CallableHolder::operator(); 110 | using CallableOverloader::operator(); 111 | }; 112 | 113 | template 114 | inline CallableOverloader makeOverload(Callables... callables){ 115 | return CallableOverloader(std::forward(callables)...); 116 | } 117 | 118 | #define _BIG_NUM_GENERIC_LITERAL_(type, literal) \ 119 | ::bignum::_type::makeOverload([](char) -> decltype(auto){return literal;}, \ 120 | [](wchar_t) -> decltype(auto){return L ## literal;}, \ 121 | [](char16_t) -> decltype(auto){return u ## literal;}, \ 122 | [](char32_t) -> decltype(auto){return U ## literal;})(type()) 123 | 124 | }; // namespace _type 125 | 126 | }; // namespace bignum 127 | 128 | #endif // _BIG_NUM_GENERICS_HPP_ -------------------------------------------------------------------------------- /Libs/BigNumMemory.hpp: -------------------------------------------------------------------------------- 1 | #ifndef _BIG_NUM_HPP_ 2 | #error "This header must be included through BigNum.hpp" 3 | #endif // _BIG_NUM_HPP_ 4 | 5 | #ifndef _BIG_NUM_MEMORY_HPP_ 6 | #define _BIG_NUM_MEMORY_HPP_ 7 | 8 | #include 9 | #include 10 | 11 | #include "BigNumTypeTrait.hpp" 12 | 13 | namespace bignum{ 14 | 15 | namespace _utility{ 16 | 17 | using _type::isRLRef; 18 | 19 | template 20 | struct destroyHelper{}; 21 | // case for trivially destructible types 22 | template <> 23 | struct destroyHelper{ 24 | template 25 | static void destroy(ForIter, ForIter, Alloc &){ 26 | // do nothing 27 | } 28 | }; 29 | // case for non trivially destructible types 30 | template <> 31 | struct destroyHelper{ 32 | template 33 | static void destroy(ForIter _start, ForIter _last, Alloc &_alloc){ 34 | using valueT = typename std::iterator_traits::value_type; 35 | for(;_start != _last;++_start){ 36 | _alloc.template destroy(_alloc.address(*_start)); 37 | } 38 | } 39 | }; 40 | 41 | template 42 | void destroyAll(ForIter _start, ForIter _last, Alloc &_alloc){ 43 | using valueT = typename std::iterator_traits::value_type; 44 | destroyHelper::type>::destroy(_start, _last, _alloc); 45 | } 46 | 47 | template 48 | class FinalizerImpl; 49 | 50 | template 51 | class FinalizerImpl::value>::type, 53 | typename std::result_of::type> 54 | :private Functor{ 55 | private: 56 | using base = Functor; 57 | public: 58 | template ::value>::type * = nullptr> 60 | explicit FinalizerImpl(FunctorRef &&_func) 61 | :Functor(std::forward(_func)){} 62 | 63 | ~FinalizerImpl(){ 64 | base::operator()(); 65 | } 66 | }; 67 | 68 | template 69 | class FinalizerImpl{ 70 | private: 71 | using FuncPtr = Ret (*)(); 72 | public: 73 | explicit FinalizerImpl(FuncPtr _func) 74 | :func(_func){} 75 | 76 | ~FinalizerImpl(){ 77 | (*func)(); 78 | } 79 | private: 80 | FuncPtr func; 81 | }; 82 | 83 | template 84 | class Finalizer:public FinalizerImpl{ 85 | private: 86 | using base = FinalizerImpl; 87 | public: 88 | Finalizer(const Finalizer &) = delete; 89 | Finalizer(Finalizer &&) = default; 90 | 91 | template 92 | explicit Finalizer(CallableRef &&_func) 93 | :base(std::forward(_func)){} 94 | 95 | Finalizer &operator=(const Finalizer &) = delete; 96 | Finalizer &operator=(Finalizer &&) = default; 97 | }; 98 | 99 | template 100 | static inline Finalizer makeFinalizer(Callable &&_func){ 101 | return Finalizer(std::forward(_func)); 102 | } 103 | 104 | #define _BIG_NUM_CONTACT_(x, y) x ## y 105 | #define _BIG_NUM_CONTACT2_(x, y) _BIG_NUM_CONTACT_(x, y) 106 | #define _BIG_NUM_ADD_FINALIZER_(x) \ 107 | auto _BIG_NUM_CONTACT2_(_finalizer, __LINE__) = bignum::_utility::makeFinalizer(x); 108 | #define _BIG_NUM_ADD_FINALIZER_CODE_(x) _BIG_NUM_ADD_FINALIZER_([&](){x}); 109 | 110 | }; // namepsace _utility 111 | 112 | }; // namespace bignum 113 | #endif // _BIG_NUM_MEMORY_HPP_ -------------------------------------------------------------------------------- /Libs/BigNumModularRing.hpp: -------------------------------------------------------------------------------- 1 | #ifndef _BIG_NUM_HPP_ 2 | #error "This header must be included through BigNum.hpp" 3 | #endif // _BIG_NUM_HPP_ 4 | 5 | #ifndef _BIG_NUM_MODULAR_RING_HPP_ 6 | #define _BIG_NUM_MODULAR_RING_HPP_ 7 | 8 | #include "BigNumTypeTrait.hpp" 9 | 10 | namespace bignum{ 11 | 12 | namespace _utility{ 13 | 14 | /*template 15 | class ModularPTrait{ 16 | private: 17 | using SqrEle = typename _type::squareType::type; 18 | public: 19 | inline static Ele add(Ele _lhs, Ele _rhs){ 20 | return (_lhs + _rhs) % P; 21 | } 22 | inline static void selfAdd(Ele &_lhs, Ele _rhs){ 23 | _lhs = (_lhs + _rhs) % P; 24 | } 25 | };*/ 26 | 27 | template 28 | class ModularP{ 29 | private: 30 | using SqrEle = typename _type::squareType::type; 31 | public: 32 | constexpr ModularP(Ele _num) 33 | :num(_num % P){} 34 | 35 | explicit constexpr operator Ele() const{ 36 | return num; 37 | } 38 | 39 | constexpr ModularP &operator+=(const ModularP &_rhs){ 40 | num = (num + _rhs.num) % P; 41 | return *this; 42 | } 43 | friend constexpr ModularP operator+(const ModularP &_lhs, const ModularP &_rhs){ 44 | return ModularP((_lhs.num + _rhs.num) % P); 45 | } 46 | friend constexpr ModularP operator+(const ModularP &_lhs, Ele _rhs){ 47 | return ModularP((_lhs.num + _rhs % P) % P); 48 | } 49 | friend constexpr ModularP operator+(Ele _lhs, const ModularP &_rhs){ 50 | return ModularP((_lhs % P + _rhs.num) % P); 51 | } 52 | 53 | constexpr ModularP &operator-=(const ModularP &_rhs){ 54 | num = (P - _rhs.num + num) % P; 55 | return *this; 56 | } 57 | friend constexpr ModularP operator-(const ModularP &_lhs, const ModularP &_rhs){ 58 | return ModularP((P - _rhs.num + _lhs.num) % P); 59 | } 60 | friend constexpr ModularP operator-(const ModularP &_lhs, Ele _rhs){ 61 | return ModularP((P - _rhs % P + _lhs.num) % P); 62 | } 63 | friend constexpr ModularP operator-(Ele _lhs, const ModularP &_rhs){ 64 | return ModularP((P - _rhs.num + _lhs % P) % P); 65 | } 66 | 67 | constexpr ModularP &operator*=(const ModularP &_rhs){ 68 | num = static_cast((static_cast(num) * static_cast(_rhs.num)) % P); 69 | return *this; 70 | } 71 | friend constexpr ModularP operator*(const ModularP &_lhs, const ModularP &_rhs){ 72 | return ModularP(static_cast((static_cast(_lhs.num) * static_cast(_rhs.num)) % P)); 73 | } 74 | friend constexpr ModularP operator*(const ModularP &_lhs, Ele _rhs){ 75 | return ModularP(static_cast((static_cast(_lhs.num) * static_cast(_rhs % P)) % P)); 76 | } 77 | friend constexpr ModularP operator*(Ele _lhs, const ModularP &_rhs){ 78 | return ModularP(static_cast((static_cast(_lhs % P) * static_cast(_rhs.num)) % P)); 79 | } 80 | 81 | friend constexpr ModularP pow(const ModularP &base, std::size_t exp){ 82 | ModularP res(Ele(1)); 83 | ModularP exponent = base; 84 | 85 | for(;exp > 0;exp >>= 1){ 86 | if((exp & 1) == 1){ 87 | res *= exponent; 88 | } 89 | exponent *= exponent; 90 | } 91 | 92 | return res; 93 | } 94 | 95 | /*constexpr ModularP inverse() const{ 96 | //using std::swap; 97 | 98 | // exgcd 99 | std::intmax_t r(num), oldr(P); 100 | //std::intmax_t s(0), olds(1); 101 | std::intmax_t t(1), oldt(0); 102 | for(;r > 0;){ 103 | // a*s+b*t==r 104 | //{ 105 | // std::intmax_t prov = olds - (oldr / r) * s; 106 | // olds = s; 107 | // s = prov; 108 | //} 109 | { 110 | std::intmax_t prov = oldt - (oldr / r) * t; 111 | oldt = t; 112 | t = prov; 113 | } 114 | { 115 | std::intmax_t prov = oldr % r; 116 | oldr = r; 117 | r = prov; 118 | } 119 | } 120 | // assert(oldr == 1) 121 | 122 | return ModularP((oldt < 0)? static_cast(oldt + static_cast(P)): static_cast(oldt)); 123 | } 124 | 125 | constexpr ModularP &operator/=(const ModularP &_rhs){ 126 | num = static_cast(num * _rhs.inverse()); 127 | return *his; 128 | } 129 | friend constexpr ModularP operator/(const ModularP &_lhs, const ModularP &_rhs){ 130 | return _lhs * _rhs.inverse(); 131 | } 132 | friend constexpr ModularP operator/(const ModularP &_lhs, const Ele &_rhs){ 133 | return _lhs * ModularP(_rhs).inverse(); 134 | } 135 | friend constexpr ModularP operator/(const Ele &_lhs, const ModularP &_rhs){ 136 | return _lhs * _rhs.inverse(); 137 | }*/ 138 | 139 | Ele num; 140 | }; 141 | 142 | };// namespace _utility 143 | 144 | }; // namespace bignum 145 | #endif // _BIG_NUM_MODULAR_RING_HPP_ -------------------------------------------------------------------------------- /Libs/BigNumTypeTrait.hpp: -------------------------------------------------------------------------------- 1 | #ifndef _BIG_NUM_HPP_ 2 | #error "This header must be included through BigNum.hpp" 3 | #endif // _BIG_NUM_HPP_ 4 | 5 | #ifndef _BIG_NUM_TYPE_TRAIT_HPP_ 6 | #define _BIG_NUM_TYPE_TRAIT_HPP_ 7 | 8 | #include 9 | #include 10 | #include 11 | #include 12 | 13 | namespace bignum{ 14 | 15 | namespace _type{ 16 | 17 | template 18 | struct isSigned 19 | :public std::integral_constant::is_signed>{}; 20 | 21 | template 22 | struct isRLRef 23 | :public std::is_same::type>::type>{}; 24 | 25 | /*template 26 | struct isRLRef{ 27 | static constexpr bool value = false; 28 | }; 29 | template 30 | struct isRLRef{ 31 | static constexpr bool value = true; 32 | }; 33 | template 34 | struct isRLRef{ 35 | static constexpr bool value = true; 36 | }; 37 | template 38 | struct isRLRef{ 39 | static constexpr bool value - true; 40 | }; 41 | template 42 | struct isRLRef{ 43 | static constexpr bool value = true; 44 | };*/ 45 | 46 | template 47 | struct squareType{}; 48 | template <> 49 | struct squareType{ 50 | using type = int16_t; 51 | }; 52 | template <> 53 | struct squareType{ 54 | using type = int32_t; 55 | }; 56 | template <> 57 | struct squareType{ 58 | using type = int64_t; 59 | }; 60 | template <> 61 | struct squareType{ 62 | using type = uint16_t; 63 | }; 64 | template <> 65 | struct squareType{ 66 | using type = uint32_t; 67 | }; 68 | template <> 69 | struct squareType{ 70 | using type = uint64_t; 71 | }; 72 | 73 | template 74 | struct conj2; 75 | 76 | template 77 | struct conj2::value>::type, 79 | typename std::enable_if::value>::type> 80 | :public std::true_type{}; 81 | 82 | template 83 | struct conj2::value>::type, 85 | typename std::enable_if::value>::type> 86 | :public std::false_type{}; 87 | 88 | template 89 | struct conj2::value>::type, 91 | typename std::enable_if::value>::type> 92 | :public std::false_type{}; 93 | 94 | template 95 | struct conj2::value>::type, 97 | typename std::enable_if::value>::type> 98 | :public std::false_type{}; 99 | 100 | template 101 | struct conj; 102 | 103 | template 104 | struct conj:public std::is_base_of::type{}; 105 | 106 | template 107 | struct conj:public conj2>{}; 108 | 109 | template 110 | struct CompareCond{ 111 | using type = typename std::conditional<(M > N), G, 112 | typename std::conditional::type>::type; 113 | }; 114 | 115 | template 116 | struct StaticList{}; 117 | 118 | struct NothingType; 119 | 120 | template 121 | struct SFINAEWrapper{ 122 | using type = T; 123 | }; 124 | template<> 125 | struct SFINAEWrapper{}; 126 | 127 | template 128 | struct PushFront; 129 | template 130 | struct PushFront>{ 131 | using type = StaticList; 132 | }; 133 | template 134 | struct PushFront>{ 135 | using type = StaticList; 136 | }; 137 | template 138 | struct PushFront{ 139 | using type = NothingType; 140 | }; 141 | 142 | template