-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBiggerInts.cpp
1497 lines (1296 loc) · 51 KB
/
BiggerInts.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include <cctype>
#include <algorithm>
#include "BiggerInts.h"
using namespace BiggerInts;
void detail::demote(detail::fixed_int_wrapper a, const bigint &val) noexcept
{
if (a.blocks_n <= val.blocks.size())
{
for (std::size_t i = 0; i < a.blocks_n; ++i) a.blocks[i] = val.blocks[i];
}
else
{
for (std::size_t i = 0; i < val.blocks.size(); ++i) a.blocks[i] = val.blocks[i];
std::uint64_t fill = detail::is_neg(val) ? -1 : 0;
for (std::size_t i = val.blocks.size(); i < a.blocks_n; ++i) a.blocks[i] = fill;
}
}
// collapses the value in the given bigint to make it satisfy the requirements of the blocks array
void collapse(bigint &a)
{
if (detail::is_neg(a))
{
for (std::size_t i = a.blocks.size(); i-- > 0 && a.blocks[i] == 0xffffffffffffffffull; ) a.blocks.pop_back();
if (a.blocks.empty() || !(a.blocks.back() & 0x8000000000000000ull)) a.blocks.push_back(0xffffffffffffffffull);
}
else
{
for (std::size_t i = a.blocks.size(); i-- > 0 && a.blocks[i] == 0; ) a.blocks.pop_back();
if (!a.blocks.empty() && (a.blocks.back() & 0x8000000000000000ull)) a.blocks.push_back(0);
}
}
bool detail::is_neg(const bigint &val) noexcept { return !val.blocks.empty() && (val.blocks.back() & 0x8000000000000000); }
std::size_t detail::highest_set_bit(const bigint &val) noexcept
{
if (val.blocks.empty()) return 0;
if (val.blocks.back()) return (val.blocks.size() - 1) * 64 + highest_set_bit(val.blocks.back());
else return (val.blocks.size() - 2) * 64 + highest_set_bit(val.blocks[val.blocks.size() - 2]);
}
void detail::make_not(bigint &a)
{
if (a.blocks.empty()) a.blocks.push_back(0xffffffffffffffffull);
else
{
for (std::uint64_t &v : a.blocks) v = ~v;
collapse(a);
}
}
void detail::make_neg(bigint &a) { make_not(a); ++a; }
bool detail::bit_test(const bigint &val, std::uint64_t bit) noexcept
{
std::uint64_t block = bit / 64;
if (block >= val.blocks.size()) return detail::is_neg(val); // lookup in ghost blocks
return (val.blocks[block] >> (bit % 64)) & 1; // lookup in declared range
}
bool detail::bit_test_in_bounds_nonzero(const bigint &val, std::uint64_t bit) noexcept
{
return (val.blocks[bit / 64] >> (bit % 64)) & 1;
}
void detail::bit_set(bigint &val, std::uint64_t bit) noexcept
{
std::uint64_t block = bit / 64;
const bool neg = detail::is_neg(val);
if (block >= val.blocks.size())
{
if (neg) return; // if negative in ghost block region, already set
val.blocks.resize(block + 1, 0ul); // otherwise resize so that block is a valid index
}
bit %= 64;
val.blocks[block] |= 1ull << bit;
if (!neg && detail::is_neg(val)) val.blocks.push_back(0ull); // make sure positive things remain positive
collapse(val);
}
bool detail::cmp_less_non_negative(const bigint &a, const bigint &b) noexcept // same as cmp() but requires they both be non-negative
{
if (a.blocks.size() > b.blocks.size()) return false;
if (a.blocks.size() < b.blocks.size()) return true;
for (std::size_t i = a.blocks.size(); i-- > 0; ) if (a.blocks[i] != b.blocks[i]) return a.blocks[i] < b.blocks[i];
return false;
}
int detail::cmp_raw(const bigint &a, const bigint &b) noexcept
{
const bool a_neg = detail::is_neg(a);
const bool b_neg = detail::is_neg(b);
if (a_neg ^ b_neg) return a_neg ? -1 : 1; // if they have different signs we know right away
if (a.blocks.size() > b.blocks.size()) return a_neg ? -1 : 1; // if a has higher magnitude than b we can tell from the sign
if (a.blocks.size() < b.blocks.size()) return a_neg ? 1 : -1; // similarly
for (std::size_t i = a.blocks.size(); i-- > 0; ) if (a.blocks[i] != b.blocks[i]) return a.blocks[i] < b.blocks[i] ? -1 : 1; // otherwise base decision on first different block
return 0; // otherwise they're equal
}
int detail::cmp_bigint_builtin(const bigint &a, long long val) noexcept
{
const bool a_neg = detail::is_neg(a);
if (a_neg != (val < 0)) return a_neg ? -1 : 1; // if they have different signs we know right away
if (a.blocks.size() > 1) return a_neg ? -1 : 1; // if a has higher magnitude than b we can tell from the sign
else if (a.blocks.size() == 1)
{
if (a.blocks[0] == (unsigned long long)val) return 0;
else return a.blocks[0] < (unsigned long long)val ? -1 : 1;
}
else return val < 0 ? 1 : val > 0 ? -1 : 0; // otherwise a == 0
}
int detail::cmp_bigint_builtin(const bigint &a, unsigned long long val) noexcept
{
if (detail::is_neg(a)) return -1; // if a is negative we know it's < immediately
if (a.blocks.size() > 2) return 1; // if a has higher magnitude, it's greater
else if (a.blocks.size() == 2 && a.blocks[1]) return 1; // if second block is significant, a is greater
else if (a.blocks.size() == 0) return val ? -1 : 0; // if a == 0
else return a.blocks[0] < val ? -1 : a.blocks[0] > val ? 1 : 0; // otherwise same magnitude
}
void bigint::zero_extend(detail::const_fixed_int_wrapper val)
{
blocks.assign(val.blocks, val.blocks + val.blocks_n);
std::size_t s = blocks.size();
for (; s > 0; --s) if (blocks[s - 1]) break;
blocks.resize(s);
if (!blocks.empty() && (blocks.back() & 0x8000000000000000ull)) blocks.push_back(0ull);
}
void bigint::sign_extend(detail::const_fixed_int_wrapper val)
{
blocks.assign(val.blocks, val.blocks + val.blocks_n);
collapse(*this);
}
bigint &bigint::operator++()
{
for (std::size_t i = 1; i < blocks.size(); ++i) if (++blocks[i - 1]) { collapse(*this); return *this; }
if (blocks.empty()) blocks.push_back(1ull);
else
{
std::uint64_t high = ++blocks.back();
if (high == 0) blocks.clear();
else if (high == 0x8000000000000000ull) blocks.push_back(0ull);
else collapse(*this);
}
return *this;
}
bigint bigint::operator++(int) { bigint cpy = *this; ++*this; return cpy; }
bigint &bigint::operator--()
{
for (std::size_t i = 1; i < blocks.size(); ++i) if (blocks[i - 1]--) { collapse(*this); return *this; }
if (blocks.empty()) blocks.push_back(0xffffffffffffffffull);
else
{
std::uint64_t high = blocks.back()--;
/* high == 0 case cannot happen because 0 is represented by empty array and is therefore handled above */
if (high == 0x8000000000000000ull) blocks.push_back(0xffffffffffffffffull);
else collapse(*this);
}
return *this;
}
bigint bigint::operator--(int) { bigint cpy = *this; --*this; return cpy; }
template<bool subtract>
bigint &_add(bigint &a, const bigint &b)
{
std::size_t min = std::min(a.blocks.size(), b.blocks.size());
const bool a_neg = detail::is_neg(a);
const bool b_neg = subtract ^ detail::is_neg(b);
// compute addition on the mutually covered range
std::uint64_t carry = subtract ? 1 : 0;
for (std::size_t i = 0; i < min; ++i)
{
std::uint64_t v = (subtract ? ~b.blocks[i] : b.blocks[i]) + carry;
carry = (a.blocks[i] += v) < v || v < carry ? 1 : 0;
}
// perform addition on the extended range (ghost blocks)
if (a.blocks.size() < b.blocks.size())
{
a.blocks.resize(b.blocks.size(), a_neg ? -1 : 0);
for (std::size_t i = min; i < a.blocks.size(); ++i)
{
std::uint64_t v = (subtract ? ~b.blocks[i] : b.blocks[i]) + carry;
carry = (a.blocks[i] += v) < v || v < carry ? 1 : 0;
}
}
else if (a.blocks.size() > b.blocks.size())
{
std::size_t ghost = b_neg ? -1 : 0;
for (std::size_t i = min; i < a.blocks.size(); ++i)
{
std::uint64_t v = ghost + carry;
carry = (a.blocks[i] += v) < v || v < carry ? 1 : 0;
}
}
// perform addition on the infinite prefix blocks
if (!a_neg && !b_neg)
{
if (carry) a.blocks.push_back(1ull);
else if (detail::is_neg(a)) a.blocks.push_back(0ull); // value of a has changed and might be negative now
}
else if (a_neg && b_neg)
{
if (!carry) a.blocks.push_back(0xfffffffffffffffeull);
else if (!detail::is_neg(a)) a.blocks.push_back(0xffffffffffffffffull); // value of a has changed and might be negative now
}
else
{
if (carry)
{
if (detail::is_neg(a)) a.blocks.push_back(0ull);
}
else
{
if (!detail::is_neg(a)) a.blocks.push_back(0xffffffffffffffffull);
}
}
collapse(a);
return a;
}
bigint &bigint::operator+=(const bigint &b) { return _add<false>(*this, b); }
bigint &bigint::operator-=(const bigint &b) { return _add<true>(*this, b); }
bigint detail::operator+(const bigint &a, const bigint &b) { bigint cpy = a; cpy += b; return cpy; }
bigint detail::operator+(bigint &&a, const bigint &b) { bigint cpy = std::move(a); cpy += b; return cpy; }
bigint detail::operator+(const bigint &a, bigint &&b) { bigint cpy = std::move(b); cpy += a; return cpy; }
bigint detail::operator+(bigint &&a, bigint &&b)
{
if (a.blocks.size() >= b.blocks.size()) { bigint cpy = std::move(a); cpy += b; return cpy; }
else { bigint cpy = std::move(b); cpy += a; return cpy; }
}
bigint detail::operator-(const bigint &a, const bigint &b) { bigint cpy = a; cpy -= b; return cpy; }
bigint detail::operator-(bigint &&a, const bigint &b) { bigint cpy = std::move(a); cpy -= b; return cpy; }
bigint detail::operator-(const bigint &a, bigint &&b) { bigint cpy = std::move(b); cpy -= a; detail::make_neg(cpy); return cpy; } // not sure if this is faster than just making a dynamically-allocated copy
bigint detail::operator-(bigint &&a, bigint &&b) { bigint cpy = std::move(a); cpy -= b; return cpy; }
bigint &bigint::operator&=(const bigint &b)
{
const bool a_neg = detail::is_neg(*this);
const bool b_neg = detail::is_neg(b);
const std::size_t min = std::min(blocks.size(), b.blocks.size());
for (std::size_t i = 0; i < min; ++i) blocks[i] &= b.blocks[i]; // perform on range declared by both
if (blocks.size() < b.blocks.size())
{
// if a was positive then rest is all 0's and thus result is already computed
if (a_neg) // otherwise a was negative, so rest is all 1's - just copy remaining blocks from b
{
blocks.resize(b.blocks.size());
for (std::size_t i = min; i < b.blocks.size(); ++i) blocks[i] = b.blocks[i];
}
}
else if (b.blocks.size() < blocks.size())
{
// if b was negative then rest is all 1's - we keep everything in a that was already there
if (!b_neg) // otherwise b was positive - rest is all 0's and thus result is already computed - just truncate down to computed region and make sure result is positive
{
blocks.resize(min);
if (detail::is_neg(*this)) blocks.push_back(0ull);
}
}
collapse(*this);
return *this;
}
bigint detail::operator&(const bigint &a, const bigint &b) { bigint cpy = a; cpy &= b; return cpy; }
bigint detail::operator&(bigint &&a, const bigint &b) { bigint cpy = std::move(a); cpy &= b; return cpy; }
bigint detail::operator&(const bigint &a, bigint &&b) { bigint cpy = std::move(b); cpy &= a; return cpy; }
bigint detail::operator&(bigint &&a, bigint &&b) { bigint cpy = std::move(a); cpy &= b; return cpy; }
bigint &bigint::operator|=(const bigint &b)
{
const bool a_neg = detail::is_neg(*this);
const bool b_neg = detail::is_neg(b);
const std::size_t min = std::min(blocks.size(), b.blocks.size());
for (std::size_t i = 0; i < min; ++i) blocks[i] |= b.blocks[i]; // perform on range declared by both
if (blocks.size() < b.blocks.size())
{
// if a was negative then rest is all 1's, and thus result is already computed
if (!a_neg) // otherwise a positive, so rest is all 0's - just copy remaining blocks from b
{
blocks.resize(b.blocks.size());
for (std::size_t i = min; i < b.blocks.size(); ++i) blocks[i] = b.blocks[i];
}
}
else if (b.blocks.size() < blocks.size())
{
// if b was positive then rest is all 0's - we keep everything in a that was already there
if (b_neg) // otherwise b was negative, so rest is all 1's - just truncate down to computed region and make sure result is negative
{
blocks.resize(min);
if (!detail::is_neg(*this)) blocks.push_back(0xffffffffffffffffull);
}
}
collapse(*this);
return *this;
}
bigint detail::operator|(const bigint &a, const bigint &b) { bigint cpy = a; cpy |= b; return cpy; }
bigint detail::operator|(bigint &&a, const bigint &b) { bigint cpy = std::move(a); cpy |= b; return cpy; }
bigint detail::operator|(const bigint &a, bigint &&b) { bigint cpy = std::move(b); cpy |= a; return cpy; }
bigint detail::operator|(bigint &&a, bigint &&b) { bigint cpy = std::move(a); cpy |= b; return cpy; }
bigint &bigint::operator^=(const bigint &b)
{
const bool a_neg = detail::is_neg(*this);
const bool b_neg = detail::is_neg(b);
const std::size_t min = std::min(blocks.size(), b.blocks.size());
for (std::size_t i = 0; i < min; ++i) blocks[i] ^= b.blocks[i]; // perform on range declared by both
if (blocks.size() < b.blocks.size())
{
if (a_neg) // if a was negative then rest is all 1's - just copy the inverted bits of b
{
blocks.resize(b.blocks.size());
for (std::size_t i = min; i < b.blocks.size(); ++i) blocks[i] = ~b.blocks[i];
}
else // otherwise a was positive, so rest is all 0's - just copy the bits of b
{
blocks.resize(b.blocks.size());
for (std::size_t i = min; i < b.blocks.size(); ++i) blocks[i] = b.blocks[i];
}
}
else if (b.blocks.size() < blocks.size())
{
// if b was positive then rest is all 0's - so we already have the result
if (b_neg) // otherwise b negative, so rest is all 1's - just invert the bits of a
{
for (std::size_t i = min; i < blocks.size(); ++i) blocks[i] = ~blocks[i];
}
}
collapse(*this);
return *this;
}
bigint detail::operator^(const bigint &a, const bigint &b) { bigint cpy = a; cpy ^= b; return cpy; }
bigint detail::operator^(bigint &&a, const bigint &b) { bigint cpy = std::move(a); cpy ^= b; return cpy; }
bigint detail::operator^(const bigint &a, bigint &&b) { bigint cpy = std::move(b); cpy ^= a; return cpy; }
bigint detail::operator^(bigint &&a, bigint &&b) { bigint cpy = std::move(a); cpy ^= b; return cpy; }
bigint &bigint::operator<<=(std::uint64_t count)
{
if (!blocks.empty())
{
const std::uint64_t fill = detail::is_neg(*this) ? -1 : 0;
const std::size_t full = count / 64;
if (full)
{
blocks.resize(blocks.size() + full); // make room for the shifting blocks
for (std::size_t i = blocks.size(); i-- > full; ) blocks[i] = blocks[i - full];
for (std::size_t i = full; i-- > 0; ) blocks[i] = 0;
count &= 63;
}
if (count)
{
std::uint64_t overflow_block = (fill << count) | (blocks.back() >> (64 - count)); // compute overflow block from high block (include ghost bits based on sign)
for (std::size_t i = blocks.size() - 1; i > full; --i) blocks[i] = (blocks[i] << count) | (blocks[i - 1] >> (64 - count));
blocks[full] <<= count;
const std::uint64_t new_fill = detail::is_neg(*this) ? -1 : 0; // get new fill pattern
if (overflow_block != new_fill) blocks.push_back(overflow_block); // if the overflow block isn't generated by the new fill pattern, we need to append it
}
}
return *this;
}
bigint detail::operator<<(const bigint &val, std::uint64_t count) { bigint cpy = val; cpy <<= count; return cpy; }
bigint detail::operator<<(bigint &&val, std::uint64_t count) { bigint cpy = std::move(val); cpy <<= count; return cpy; }
bigint &bigint::operator>>=(std::uint64_t count)
{
if (!blocks.empty())
{
const std::uint64_t fill = detail::is_neg(*this) ? -1 : 0;
const std::size_t full = count / 64;
if (full)
{
for (std::size_t i = 0; i < blocks.size() - full; ++i) blocks[i] = blocks[i + full];
for (std::size_t i = blocks.size() - full; i < blocks.size(); ++i) blocks[i] = fill;
count &= 63;
}
if (count)
{
for (std::size_t i = full; i < blocks.size() - 1; ++i) blocks[i] = (blocks[i] >> count) | (blocks[i + 1] << (64 - count));
blocks[blocks.size() - 1] = (blocks[blocks.size() - 1] >> count) | (fill << (64 - count));
}
collapse(*this);
}
return *this;
}
bigint detail::operator>>(const bigint &val, std::uint64_t count) { bigint cpy = val; cpy >>= count; return cpy; }
bigint detail::operator>>(bigint &&val, std::uint64_t count) { bigint cpy = std::move(val); cpy >>= count; return cpy; }
bigint detail::operator+(const bigint &a) { return a; }
bigint detail::operator+(bigint &&a) { return std::move(a); }
bigint detail::operator-(const bigint &a) { bigint res = a; detail::make_neg(res); return res; }
bigint detail::operator-(bigint &&a) { bigint res = std::move(a); detail::make_neg(res); return res; }
bigint detail::operator~(const bigint &a) { bigint res = a; detail::make_not(res); return res; }
bigint detail::operator~(bigint &&a) { bigint res = std::move(a); detail::make_not(res); return res; }
bigint _multiply_positive(const bigint &a, const bigint &b)
{
const std::size_t a_size = a.blocks.size();
const std::size_t b_size = b.blocks.size();
bigint res; // the final result object - bastardized for efficiency right now
res.blocks.resize(a_size + b_size, 0ull); // allocate all the space we'll need, zero initialized for the add logic later
for (std::size_t i = 0; i < a_size; ++i) // loop through each block in a
{
// here we construct temp_1, which is the value of a->blocks[i] * b, scaled by i words (think long multiplication from grade school)
for (std::size_t j = 0; j < b_size; ++j)
{
auto p = detail::_mul_u64_fast(a.blocks[i], b.blocks[j]); // compute the product with this block from b
if ((res.blocks[j + i] += p.first) < p.first) // add the low half to the corresponding block in res - overflow propagates a carry up to higher blocks
{
for (std::size_t k = j + i + 1; !++res.blocks[k]; ++k);
}
if ((res.blocks[j + i + 1] += p.second) < p.second) // add the high half to the next block in res - overflow propagates a carry up to higher blocks
{
for (std::size_t k = j + i + 2; !++res.blocks[k]; ++k);
}
}
}
collapse(res); // we need to perform one collapse operation on the finished result to put it into a valid state
return res;
}
template<typename U, typename V, std::enable_if_t<std::is_same_v<std::decay_t<U>, bigint> && std::is_same_v<std::decay_t<V>, bigint>, int> = 0>
inline bigint _multiply_unknown(U &&a, V &&b)
{
const bool a_neg = detail::is_neg(a);
const bool b_neg = detail::is_neg(b);
if (a_neg && b_neg)
{
bigint a_cpy = std::forward<U>(a);
bigint b_cpy = std::forward<V>(b);
detail::make_neg(a_cpy);
detail::make_neg(b_cpy);
return _multiply_positive(a_cpy, b_cpy);
}
else if (a_neg)
{
bigint a_cpy = std::forward<U>(a);
detail::make_neg(a_cpy);
bigint res = _multiply_positive(a_cpy, b);
detail::make_neg(res);
return res;
}
else if (b_neg)
{
bigint b_cpy = std::forward<V>(b);
detail::make_neg(b_cpy);
bigint res = _multiply_positive(a, b_cpy);
detail::make_neg(res);
return res;
}
else return _multiply_positive(a, b);
}
bigint detail::operator*(const bigint &a, const bigint &b) { return _multiply_unknown(a, b); }
bigint detail::operator*(bigint &&a, const bigint &b) { return _multiply_unknown(std::move(a), b); }
bigint detail::operator*(const bigint &a, bigint &&b) { return _multiply_unknown(a, std::move(b)); }
bigint detail::operator*(bigint &&a, bigint &&b) { return _multiply_unknown(std::move(a), std::move(b)); }
bigint &bigint::operator*=(const bigint &b)
{
if (this != &b) *this = std::move(*this) * b;
else *this = *this * b;
return *this;
}
bigint &bigint::operator*=(bigint &&b) { *this = std::move(*this) * std::move(b); return *this; }
void detail::divmod_unchecked_positive_already_zero(bigint &quo, bigint &rem, const bigint &num, const bigint &den)
{
// both positive, so if num < den then we know result immediately (this also handles num == 0 case, as we already know den != 0)
if (num.blocks.size() < den.blocks.size()) { rem = num; return; }
// pre-allocate space for the results
quo.blocks.reserve(num.blocks.size() - den.blocks.size() + 1);
rem.blocks.reserve(den.blocks.size());
std::uint64_t bit = highest_set_bit(num);
const std::size_t den_highest_bit = highest_set_bit(den);
std::size_t res_second_highest_bit = 0;
std::size_t shift_count = 0;
while (true)
{
++shift_count;
if (res_second_highest_bit + shift_count >= den_highest_bit)
{
rem <<= shift_count;
res_second_highest_bit += shift_count;
shift_count = 0;
if (bit_test_in_bounds_nonzero(num, bit)) ++rem;
if (!cmp_less_non_negative(rem, den))
{
rem -= den;
res_second_highest_bit = highest_set_bit(rem);
bit_set(quo, bit); // no unchecked equivalent because arbitrary precision
}
}
else if (bit_test_in_bounds_nonzero(num, bit))
{
rem <<= shift_count;
res_second_highest_bit += shift_count;
shift_count = 0;
++rem;
}
if (bit-- == 0) break;
}
rem <<= shift_count;
}
std::pair<bigint, bigint> detail::divmod_unchecked_positive(const bigint &num, const bigint &den)
{
std::pair<bigint, bigint> res;
detail::divmod_unchecked_positive_already_zero(res.first, res.second, num, den);
return res;
}
template<typename U, typename V, std::enable_if_t<std::is_same_v<std::decay_t<U>, bigint> && std::is_same_v<std::decay_t<V>, bigint>, int> = 0>
std::pair<bigint, bigint> _divmod_unchecked(U &&a, V &&b)
{
const bool a_neg = detail::is_neg(a);
const bool b_neg = detail::is_neg(b);
if (a_neg && b_neg)
{
bigint a_cpy = std::forward<U>(a);
bigint b_cpy = std::forward<V>(b);
detail::make_neg(a_cpy);
detail::make_neg(b_cpy);
auto res = detail::divmod_unchecked_positive(a_cpy, b_cpy);
detail::make_neg(res.second);
return res;
}
else if (a_neg)
{
bigint a_cpy = std::forward<U>(a);
detail::make_neg(a_cpy);
auto res = detail::divmod_unchecked_positive(a_cpy, b);
detail::make_neg(res.first);
detail::make_neg(res.second);
return res;
}
else if (b_neg)
{
bigint b_cpy = std::forward<V>(b);
detail::make_neg(b_cpy);
auto res = detail::divmod_unchecked_positive(a, b_cpy);
detail::make_neg(res.first);
return res;
}
else return detail::divmod_unchecked_positive(a, b);
}
template<typename U, typename V, std::enable_if_t<std::is_same_v<std::decay_t<U>, bigint> && std::is_same_v<std::decay_t<V>, bigint>, int> = 0>
std::pair<bigint, bigint> _divmod(U &&a, V &&b)
{
if (!b) throw std::domain_error("divide by zero");
return _divmod_unchecked(std::forward<U>(a), std::forward<V>(b));
}
std::pair<bigint, bigint> BiggerInts::divmod(const bigint &a, const bigint &b) { return _divmod(a, b); }
std::pair<bigint, bigint> BiggerInts::divmod(bigint &&a, const bigint &b) { return _divmod(std::move(a), b); }
std::pair<bigint, bigint> BiggerInts::divmod(const bigint &a, bigint &&b) { return _divmod(a, std::move(b)); }
std::pair<bigint, bigint> BiggerInts::divmod(bigint &&a, bigint &&b) { return _divmod(std::move(a), std::move(b)); }
bigint detail::operator/(const bigint &num, const bigint &den) { return BiggerInts::divmod(num, den).first; }
bigint detail::operator/(bigint &&num, const bigint &den) { return BiggerInts::divmod(std::move(num), den).first; }
bigint detail::operator/(const bigint &num, bigint &&den) { return BiggerInts::divmod(num, std::move(den)).first; }
bigint detail::operator/(bigint &&num, bigint &&den) { return BiggerInts::divmod(std::move(num), std::move(den)).first; }
bigint detail::operator%(const bigint &num, const bigint &den) { return BiggerInts::divmod(num, den).second; }
bigint detail::operator%(bigint &&num, const bigint &den) { return BiggerInts::divmod(std::move(num), den).second; }
bigint detail::operator%(const bigint &num, bigint &&den) { return BiggerInts::divmod(num, std::move(den)).second; }
bigint detail::operator%(bigint &&num, bigint &&den) { return BiggerInts::divmod(std::move(num), std::move(den)).second; }
bigint &bigint::operator/=(const bigint &den)
{
if (this != &den) *this = std::move(*this) / den;
else *this = *this / den;
return *this;
}
bigint &bigint::operator/=(bigint &&den) { *this = std::move(*this) / std::move(den); return *this; }
bigint &bigint::operator%=(const bigint &den)
{
if (this != &den) *this = std::move(*this) % den;
else *this = *this % den;
return *this;
}
bigint &bigint::operator%=(bigint &&den) { *this = std::move(*this) % std::move(den); return *this; }
bigint bigint::pow(bigint a, const bigint &b) // pass by value is intentional
{
if (detail::is_neg(b)) return {}; // if exponent is negative just return 0
bigint res = 1;
std::uint64_t high_bit = highest_set_bit(b);
for (std::uint64_t bit = 0; bit <= high_bit + 1; ++bit)
{
if (detail::bit_test(b, bit)) res *= a;
a *= a;
}
return res;
}
static constexpr std::uint64_t _factorial_lookups[] = {
1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800, 39916800, 479001600, 6227020800, 87178291200,
1307674368000, 20922789888000, 355687428096000, 6402373705728000, 121645100408832000, 2432902008176640000
};
static constexpr std::uint64_t _factorial_lookups_count = sizeof(_factorial_lookups) / sizeof(*_factorial_lookups);
bigint bigint::factorial(std::uint64_t v)
{
if (v < _factorial_lookups_count) return _factorial_lookups[v];
bigint res = _factorial_lookups[_factorial_lookups_count - 1];
for (std::uint64_t i = _factorial_lookups_count; i <= v; ++i) res *= i;
return res;
}
// given a hex character, converts it to an integer [0, 15] - returns true if it was a valid hex digit. ch is only meaningful on success.
bool ext_hex(int &ch) noexcept
{
if (ch >= '0' && ch <= '9') { ch -= '0'; return true; }
ch |= 32;
if (ch >= 'a' && ch <= 'f') { ch = ch - 'a' + 10; return true; }
return false;
}
int parse_base(const std::ios_base &stream)
{
switch ((int)(stream.flags() & std::ios::basefield))
{
case 0: return 0; // if no base flags are set, use prefix mode
case (int)std::ios::dec: return 10;
case (int)std::ios::hex: return 16;
case (int)std::ios::oct: return 8;
default: throw std::invalid_argument("multiple base flags were set for stream object");
}
}
parse_fmt::parse_fmt(const std::ios_base &stream) : base(parse_base(stream)) {}
tostr_fmt::tostr_fmt(const std::ios_base &stream)
{
switch ((int)(stream.flags() & std::ios::basefield))
{
case 0: // if no base flags are set, use decimal as a default
case (int)std::ios::dec: base = 10; break;
case (int)std::ios::hex: base = 16; break;
case (int)std::ios::oct: base = 8; break;
default: throw std::invalid_argument("multiple base flags were set for stream object");
}
showpos = stream.flags() & std::ios::showpos;
showbase = stream.flags() & std::ios::showbase;
uppercase = stream.flags() & std::ios::uppercase;
}
template<typename T, std::enable_if_t<std::is_same_v<T, detail::fixed_int_wrapper> || std::is_same_v<T, bigint&>, int> = 0>
std::string tostr_positive_hex(T val, const tostr_fmt &fmt, char sign_ch)
{
constexpr bool is_bigint = std::is_same_v<T, bigint&>;
std::string str;
int digit, dcount;
std::uint64_t block;
const bool sign = detail::is_neg(val);
const char hex_alpha = fmt.uppercase ? 'A' : 'a';
if constexpr (is_bigint)
{
if (sign) val.blocks.push_back(0ull); // fix the issue of using arithmetic right shifts for bigint (negative would be infinite loop)
str.reserve(val.blocks.size() * 16 + 4);
}
else
{
(void)sign; // suppress unused warnings
str.reserve(val.blocks_n * 16 + 4);
}
while (true)
{
// get a block
if constexpr (is_bigint)
{
block = val.blocks.empty() ? 0ull : val.blocks[0];
val >>= 64;
}
else
{
block = val.blocks[0];
shr(val, 64);
}
dcount = 0;
do // write the block - do-while to ensure 0 gets printed
{
digit = block & 15;
str.push_back(digit < 10 ? '0' + digit : hex_alpha + digit - 10);
block >>= 4;
++dcount;
} while (block);
if (detail::nonzero(val)) { for (; dcount < 16; ++dcount) str.push_back('0'); } // if there's still stuff, pad with zeroes and continue
else break; // otherwise we're done
}
if constexpr (is_bigint)
{
if (sign)
{
const char f = fmt.uppercase ? 'F' : 'f';
std::size_t s; // now we truncate all leading f's
for (s = str.size(); s > 0; --s) if (str[s - 1] != f) break;
str.resize(s); // chop off everything we don't want
if (str.empty() || str.back() <= '7') str.push_back(f); // if the string is now empty or no longer sign extends to negative, add a (single) f back on
}
else if (str.back() >= '8') str.push_back('0'); // if val was positive but ends in an 8 or higher, add a 0 to prevent sign extending to negative on parsing
}
if (fmt.showbase)
{
str.push_back('x');
str.push_back('0');
}
if (sign_ch) str.push_back(sign_ch); // append the sign character if specified
std::reverse(str.begin(), str.end()); // reverse the string for printing
return str;
}
template<typename T, std::enable_if_t<std::is_same_v<T, detail::fixed_int_wrapper> || std::is_same_v<T, bigint&>, int> = 0>
std::string tostr_positive_bin(T val, const tostr_fmt &fmt, char sign_ch)
{
constexpr bool is_bigint = std::is_same_v<T, bigint&>;
std::string str;
int digit, dcount;
std::uint64_t block;
const bool sign = detail::is_neg(val);
if constexpr (is_bigint)
{
if (sign) val.blocks.push_back(0ull); // fix the issue of using arithmetic right shifts for bigint (negative would be infinite loop)
str.reserve(val.blocks.size() * 64 + 4);
}
else
{
(void)sign; // suppress unused warnings
str.reserve(val.blocks_n * 64 + 4);
}
while (true)
{
// get a block
if constexpr (is_bigint)
{
block = val.blocks.empty() ? 0ull : val.blocks[0];
val >>= 64;
}
else
{
block = val.blocks[0];
shr(val, 64);
}
dcount = 0;
do // write the block - do-while to ensure 0 gets printed
{
digit = block & 1;
str.push_back('0' + digit);
block >>= 1;
++dcount;
} while (block);
if (detail::nonzero(val)) { for (; dcount < 64; ++dcount) str.push_back('0'); } // if there's still stuff, pad with zeroes and continue
else break; // otherwise we're done
}
if constexpr (is_bigint)
{
if (sign)
{
std::size_t s; // now we truncate all leading 1's
for (s = str.size(); s > 0; --s) if (str[s - 1] != '1') break;
str.resize(s); // chop off everything we don't want
if (str.empty() || str.back() == '0') str.push_back('1'); // if the string is now empty or no longer sign extends to negative, add a (single) 1 back on
}
else if (str.back() == '1') str.push_back('0'); // if val was positive but ends in a 1, add a 0 to prevent sign extending to negative on parsing
}
if (fmt.showbase)
{
str.push_back('b');
str.push_back('0');
}
if (sign_ch) str.push_back(sign_ch); // append the sign character if specified
std::reverse(str.begin(), str.end()); // reverse the string for printing
return str;
}
template<typename T, std::enable_if_t<std::is_same_v<T, detail::fixed_int_wrapper> || std::is_same_v<T, bigint&>, int> = 0>
std::string tostr_positive_oct(T val, const tostr_fmt &fmt, char sign_ch)
{
constexpr bool is_bigint = std::is_same_v<T, bigint&>;
std::string str;
int dcount;
std::uint64_t block;
const bool sign = detail::is_neg(val);
if constexpr (is_bigint)
{
if (sign) val.blocks.push_back(0ull); // fix the issue of using arithmetic right shifts for bigint (negative would be infinite loop)
str.reserve(val.blocks.size() * 22 + 4);
}
else
{
(void)sign; // suppress unused warnings
str.reserve(val.blocks_n * 22 + 4);
}
while (true)
{
// get a block
if constexpr (is_bigint)
{
block = val.blocks.empty() ? 0ull : val.blocks[0];
val >>= 63;
}
else
{
block = val.blocks[0];
shr(val, 63);
}
block &= 0777777777777777777777ull;
dcount = 0;
// write the block - do-while to ensure 0 gets printed
do
{
str.push_back('0' + (block & 7));
block >>= 3;
++dcount;
} while (block);
if (detail::nonzero(val)) { for (; dcount < 21; ++dcount) str.push_back('0'); } // if there's still stuff, pad with zeroes and continue
else break; // otherwise we're done
}
if constexpr (is_bigint)
{
if (sign)
{
// if it was negative we need to ensure that the high char will sign extend to negative
if (str.back() == '1') str.back() = '7'; // 001 -> 111
else if (str.back() <= '3') str.back() += 4; // 010, 011 -> 110, 111
// otherwise is at least 4 and therefore already good to go
std::size_t s; // now we truncate all leading 7's
for (s = str.size(); s > 0; --s) if (str[s - 1] != '7') break;
str.resize(s); // chop off everything we don't want
if (str.empty() || str.back() <= '3') str.push_back('7'); // if the string is now empty or no longer sign extends to negative, add a (single) 7 back on
}
else if (str.back() >= '4') str.push_back('0'); // if val was positive but ends in a 4 or higher, add a 0 to prevent sign extending to negative on parsing
}
if (fmt.showbase)
{
str.push_back('o');
str.push_back('0');
}
if (sign_ch) str.push_back(sign_ch); // append the sign character if specified
std::reverse(str.begin(), str.end()); // reverse the string for printing
return str;
}
template<typename T, std::enable_if_t<std::is_same_v<T, detail::fixed_int_wrapper> || std::is_same_v<T, bigint&>, int> = 0>
std::string tostr_positive_dec(T val, const tostr_fmt &/*fmt*/, char sign_ch)
{
constexpr bool is_bigint = std::is_same_v<T, bigint&>;
std::string str;
int dcount;
std::uint64_t block;
typedef std::remove_reference_t<T> T_v;
std::conditional_t<!is_bigint, std::vector<std::uint64_t>, int> buffer; // buffer area for use with fixed_int
std::pair<T_v, T_v> temp;
T_v base;
if constexpr (!is_bigint)
{
buffer.resize(val.blocks_n * 3, 0); // allocate space for temp.first, temp.second, and base
temp.first = { &buffer[0], val.blocks_n };
temp.second = { &buffer[val.blocks_n], val.blocks_n };
base = { &buffer[2 * val.blocks_n], val.blocks_n };
base.blocks[0] = 10000000000000000000ull; // initialize base
str.reserve(val.blocks_n * 20 + 4);
}
else
{
(void)buffer; // suppress unused warnings (will just be optimized away)
base = 10000000000000000000ull; // initialize base
str.reserve(val.blocks.size() * 20 + 4);
}
while (true)
{
// get a block
if constexpr (!is_bigint)
{
for (std::size_t i = 0; i < val.blocks_n * 2; ++i) buffer[i] = 0; // zero temp for the next step
detail::divmod_unchecked_positive_already_zero(temp.first, temp.second, val, base);
block = temp.second.blocks[0];
for (std::size_t i = 0; i < val.blocks_n; ++i) val.blocks[i] = buffer[i]; // copy quotient back to val
}
else
{
using std::swap; // import std::swap for adl
temp.first.blocks.clear(); // zero temp for the next step
temp.second.blocks.clear();
detail::divmod_unchecked_positive_already_zero(temp.first, temp.second, val, base);
block = temp.second.blocks.empty() ? 0ull : temp.second.blocks[0];
swap(val, temp.first); // copy quotient back to val (swap is so we don't reallocate a vector each time we loop)
}
dcount = 0;
// write the block - do-while to ensure 0 gets printed
do
{
str.push_back('0' + block % 10);
block /= 10;
++dcount;
} while (block);
if (detail::nonzero(val)) { for (; dcount < 19; ++dcount) str.push_back('0'); } // if there's still stuff, pad with zeroes and continue
else break; // otherwise we're done
}
if (sign_ch) str.push_back(sign_ch); // append the sign character if specified
std::reverse(str.begin(), str.end()); // reverse the string for printing
return str;
}
template<typename T, std::enable_if_t<std::is_same_v<T, detail::fixed_int_wrapper> || std::is_same_v<T, bigint&>, int> = 0>
std::string tostr_positive(T val, const tostr_fmt &fmt, char sign_ch)
{
switch (fmt.base)
{
case 10: return tostr_positive_dec<T>(val, fmt, sign_ch);
case 16: return tostr_positive_hex<T>(val, fmt, sign_ch);