-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathF.cpp
1584 lines (1452 loc) · 60.1 KB
/
F.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 <iostream>
#include <cstring>
#include <cmath>
#include <string>
#include <random>
#include <sstream>
namespace UPmath
{
#define FFT_MULTIPLICATION
#define SIZE_OF_PIECE 4
#define BITS_OF_DWORD 32
typedef unsigned int uint32;
static_assert(sizeof(uint32) == SIZE_OF_PIECE, "sizeof(uint32) must be 4 bytes!");
extern std::random_device gRandomDevice;
class BigInteger
{
public:
uint32 capacity = 0, size = 0;//in DWORD (NOT byte)
bool negativity = false;//*this <= 0 when `negativity` is true and >= 0 when it is false
BigInteger();
BigInteger(bool isHexadecimal, const std::string&);//decimal or hexdecimal
BigInteger(const std::string&);//init as hexadecimal only if the string starts with `0x` or `0X`
BigInteger(int);
BigInteger(long long);
BigInteger(unsigned long long);
BigInteger(const void* dataPtr, size_t dataSize);//for cryptography
BigInteger(const BigInteger& source);
const BigInteger& operator=(const BigInteger& source);
BigInteger(BigInteger&& source);
const BigInteger& operator=(BigInteger&& source);
~BigInteger() { delete[] _valPtr; }
int intValue() const;//abs modular 0x80000000
double doubleValue() const;
void saveBytesToBuffer(char* dst, size_t writingSize) const;
const std::string toString() const;
char* toHexadecimalCharArray() const;
bool* convertAbsToBinaryArray(size_t* out_digitsSize) const;//from lower digit to higher. eg: 4 -> 001
size_t getBitLength() const;
void setLowerBitsToRandom(uint32 bitLength);
bool testBit(uint32 bitPos) const;
int compareAbsoluteValueTo(const BigInteger&) const;
int compareTo(const BigInteger&) const;
bool operator==(const BigInteger& rhs) const { return compareTo(rhs) == 0; }
bool operator!=(const BigInteger& rhs) const { return compareTo(rhs) != 0; }
bool operator<(const BigInteger& rhs) const { return compareTo(rhs) < 0; }
bool operator>(const BigInteger& rhs) const { return compareTo(rhs) > 0; }
bool operator<=(const BigInteger& rhs) const { return compareTo(rhs) <= 0; }
bool operator>=(const BigInteger& rhs) const { return compareTo(rhs) >= 0; }
BigInteger operator-() const { BigInteger t(*this); t.negativity = !t.negativity; return t; }
const BigInteger& operator+=(const BigInteger& rhs);
const BigInteger& operator-=(const BigInteger& rhs);
const BigInteger& operator>>=(const uint32 shift);
const BigInteger& operator<<=(const uint32 shift);
friend BigInteger operator*(const BigInteger& lhs, const BigInteger& rhs);
BigInteger absDivideAndSetThisToRemainder(const BigInteger& rhs);
const BigInteger& operator%=(const BigInteger& rhs);
const BigInteger& operator/=(const BigInteger& rhs);
BigInteger sqrt(bool ceilling = false) const;
BigInteger pow(uint32 positive_exponent) const;
BigInteger modInverse(const BigInteger& m) const;//return BigInteger(0) when the inverse doesnot exist
BigInteger modPow(const BigInteger& exponent, const BigInteger& m) const;
struct _EEAstruct;
static BigInteger gcd(const BigInteger& a, const BigInteger& b);
static int JacobiSymbol(const BigInteger& upperArgument, const BigInteger& lowerArgument);
bool isPrime(int confidenceFactor = -1) const;
bool weakerBailliePSWPrimeTest() const;
BigInteger nextProbablePrime() const;
static const BigInteger kBigInteger_0;
static const BigInteger kBigInteger_1;
private:
uint32* _valPtr = nullptr;
class _SharedMemBigInteger;
template <uint32 FractionalBitLen> friend class FixedPointNum;
void _setSize(uint32 maxPossibleSize);
void _absSubtract(const BigInteger& rhs);//only if abs(rhs) <= abs(*this)
static BigInteger _absMultiply(const BigInteger& lhs, const BigInteger& rhs);
void _seperateToHigherAndLowerHalfs(BigInteger* dst) const;
#ifdef FFT_MULTIPLICATION
#define FFT_MAX_N 1024u
#define FFT_WORD_BITLEN 16
#define _IS_LITTLE_ENDIAN() (true)
public:
inline void _FFTgetBeginAndEndOfVal(unsigned short* &begin, unsigned short* &end) const
{
begin = reinterpret_cast<unsigned short*>(_valPtr);
end = reinterpret_cast<unsigned short*>(_valPtr + size);
}
private:
static bool _isRootsOfUnityInitialized;
static void _FFTMultiply(BigInteger& dst, const BigInteger& lhs, const BigInteger& rhs, void* buffer = nullptr);
#endif
BigInteger _trivialModPow(bool* binaryArrayOfExponent, size_t bitsOfExponent, const BigInteger& m) const;
BigInteger _montgomeryModPow(bool* binaryArrayOfExponent, size_t bitsOfExponent, const BigInteger& m) const;
static _EEAstruct _extendedEuclid(BigInteger* a, BigInteger* b);
static BigInteger* _euclidGcd(BigInteger* a, BigInteger* b);
bool _MillerRabinPrimalityTest(const BigInteger& a, const BigInteger& thisMinus1) const;//logically wrong when *this <= 2
static int _JacobiSymbolImpl(BigInteger* numerator, BigInteger* denominator);
std::pair<BigInteger, BigInteger> _getModLucasSequence(const BigInteger& k, const BigInteger& D, const BigInteger& P, const BigInteger& Q) const;
bool _LucasPseudoprimeTest() const;//logically wrong when *this <= 2
static unsigned char _requiredCapacityList[129];
static uint32 _calcMinimumCapacity(uint32 size_);
inline static uint32 _getMinimumCapacity(uint32 size_)
{
if (size_ < sizeof(_requiredCapacityList)) return _requiredCapacityList[size_];
return _calcMinimumCapacity(size_);
}
};
struct BigInteger::_EEAstruct { BigInteger *d, *x, *y; };
class BigInteger::_SharedMemBigInteger : public BigInteger {
public:
_SharedMemBigInteger(const BigInteger& src) { _valPtr = src._valPtr; negativity = src.negativity; capacity = src.capacity; size = src.size; }
_SharedMemBigInteger(uint32 size_, uint32* val);
~_SharedMemBigInteger() { _valPtr = nullptr; }
};
template <class T> T operator+(const T& lhs, const T& rhs) { return T(lhs) += rhs; }
template <class T> T operator-(const T& lhs, const T& rhs) { return T(lhs) -= rhs; }
template <class T> T operator%(const T& lhs, const T& rhs) { return T(lhs) %= rhs; }
template <class T> T operator/(const T& lhs, const T& rhs) { return T(lhs) /= rhs; }
template <class T> T operator>>(const T& lhs, const uint32 shift) { return T(lhs) >>= shift; }
template <class T> T operator<<(const T& lhs, const uint32 shift) { return T(lhs) <<= shift; }
inline std::ostream& operator<<(std::ostream& os, const BigInteger& src)
{
os << src.toString();
return os;
}
inline std::istream& operator>>(std::istream& is, BigInteger& dst)
{
std::string str;
is >> str;
dst = BigInteger(str);
return is;
}
}//namespace UPMath
namespace UPmath
{
std::random_device gRandomDevice;
const BigInteger BigInteger::kBigInteger_0 = BigInteger(0);
const BigInteger BigInteger::kBigInteger_1 = BigInteger(1);
BigInteger::BigInteger() { }
BigInteger::BigInteger(int num)
{
if (num) {
if (num < 0) { negativity = true; num = -num; }
(_valPtr = new uint32[capacity = size = 1])[0] = num;
}
}
BigInteger::BigInteger(long long num) : BigInteger((unsigned long long)(num < 0 ? -num : num)) { negativity = (num < 0); }
BigInteger::BigInteger(unsigned long long num)
{
static_assert(sizeof(long long) / sizeof(uint32) == 2, "Compile error in BigInteger(long long)");
_valPtr = new uint32[capacity = 2];
if (num) _valPtr[0] = static_cast<uint32>(num), ++size;
num >>= BITS_OF_DWORD;
if (num) _valPtr[1] = static_cast<uint32>(num), ++size;
}
BigInteger::BigInteger(bool isHexadecimal, const std::string& str)
{
int i = 0, strLen = (int)str.length(), t;
bool neg_ = false;
if (str[i] == '-') { neg_ = true; ++i; }
else if (str[i] == '+') ++i;
if (!isHexadecimal)
{
while (i < strLen && (t = (int)str[i] - '0') >= 0 && t < 10) {
BigInteger tupi = *this <<= 1;
*this <<= 2; *this += tupi; *this += BigInteger(t);
++i;
}
}
else
{
(_valPtr = new uint32[capacity = 1])[0] = 0;
if (strLen >= 2 && ( ('\x5F' & str[i + 1]) == 'X')) i += 2;
while (i < strLen && (t = (int)str[i] - '0') >= 0) {
if (t > 9) {
t = (int)(str[i] & '\x5F') - 'A' + 10;
if ((t < 10) | (t >= 16)) break;
}
*this <<= 4;
this->_valPtr[0] |= t;
if (size == 0 && t) ++size;
++i;
}
}
negativity = neg_;
}
BigInteger::BigInteger(const BigInteger& source)
{
negativity = source.negativity;
size = source.size;
capacity = _getMinimumCapacity(size);
_valPtr = new uint32[capacity];
uint32 *_temptr = _valPtr, *_srcptr = source._valPtr;
for (uint32* _comptr = _temptr + size; _temptr < _comptr; ++_temptr, ++_srcptr) *_temptr = *_srcptr;
}
const BigInteger& BigInteger::operator=(const BigInteger& source)
{
if (this == &source) return *this;
if (source.size > this->capacity) {
delete[] this->_valPtr;
this->_valPtr = new uint32[this->capacity = _getMinimumCapacity(source.size)];
}
negativity = source.negativity;
size = source.size;
uint32 *_temptr = _valPtr, *_srcptr = source._valPtr;
for (uint32* _comptr = _temptr + size; _temptr < _comptr; ++_temptr, ++_srcptr) *_temptr = *_srcptr;
return *this;
}
const BigInteger& BigInteger::operator=(BigInteger&& source)
{
delete[] _valPtr;
_valPtr = source._valPtr;
negativity = source.negativity;
capacity = source.capacity;
size = source.size;
source._valPtr = nullptr;
source.capacity = source.size = 0;
return *this;
}
BigInteger::BigInteger(BigInteger&& source)
{
_valPtr = source._valPtr;
negativity = source.negativity;
capacity = source.capacity;
size = source.size;
source._valPtr = nullptr;
source.capacity = source.size = 0;
}
BigInteger::BigInteger(const std::string& str) :
BigInteger((str.length() >= 2 && str[0] == '0' && (('\x5F' & str[1]) == 'X')), str) { }
void BigInteger::_setSize(uint32 maxPossibleSize)
{
if ((size = maxPossibleSize))
for (uint32* ptr = _valPtr + size; --ptr >= _valPtr; --size)
if (*ptr) break;
}
unsigned char BigInteger::_requiredCapacityList[129] = {
0, 1, 2, 4, 4, 8, 8, 8, 8, 16, 16, 16, 16, 16, 16, 16, 16, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32,
64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64,
128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128,
128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128 };
uint32 BigInteger::_calcMinimumCapacity(uint32 size_)
{
uint32 minCap = (size_ < sizeof(_requiredCapacityList)) ? 1 : 256;
while (size_ > minCap) minCap <<= 1;
return minCap;
}
int BigInteger::compareAbsoluteValueTo(const BigInteger& rhs) const
{
if (size != rhs.size)
return (size > rhs.size) ? 1 : -1;
for (uint32 i = size; i > 0; ) {
--i;
if (_valPtr[i] != rhs._valPtr[i])
return (_valPtr[i] > rhs._valPtr[i]) ? 1 : -1;
}
return 0;
}
int BigInteger::compareTo(const BigInteger& rhs) const
{
if (negativity != rhs.negativity) {
if (0 == (size | rhs.size)) return 0;
return negativity ? -1 : 1;
}
int result = compareAbsoluteValueTo(rhs);
return negativity ? -result : result;
}
//only if abs(rhs) <= abs(*this)
void BigInteger::_absSubtract(const BigInteger& rhs)
{
bool borrowFlag = false;
uint32* ptr = _valPtr;
for (uint32 ti = 0; ti < rhs.size; ++ti, ++ptr) {
uint32 temp = *ptr;
*ptr -= rhs._valPtr[ti];
*ptr -= borrowFlag;
borrowFlag = (*ptr > temp) | ((*ptr == temp) & borrowFlag);
}
if (borrowFlag) while (true) if ((*(ptr++))--) break;
_setSize(size);
}
const BigInteger& BigInteger::operator+=(const BigInteger& rhs)
{
if (this == &rhs) *this <<= 1;
else if (negativity == rhs.negativity)
{
uint32 commonPiecesCount = (size > rhs.size) ? rhs.size : size;
uint32 *l_ptr, *r_ptr, *c_ptr;
if (commonPiecesCount != rhs.size)
{//rhs is longer
if (capacity < rhs.size) {
uint32* newptr = new uint32[capacity = _getMinimumCapacity(rhs.size)];
for (c_ptr = (l_ptr = _valPtr) + size; l_ptr < c_ptr; ++newptr, ++l_ptr) *newptr = *l_ptr;
delete[] _valPtr;
_valPtr = newptr - size;
}
l_ptr = _valPtr + size;
r_ptr = rhs._valPtr + size;
c_ptr = rhs._valPtr + (size = rhs.size);
while (r_ptr < c_ptr) *(l_ptr++) = *(r_ptr++);
}
l_ptr = _valPtr;
r_ptr = rhs._valPtr;
bool carryFlag = false;
for (c_ptr = rhs._valPtr + commonPiecesCount; r_ptr < c_ptr; ++l_ptr, ++r_ptr)
{
*l_ptr += *r_ptr;
*l_ptr += carryFlag;
carryFlag = (*l_ptr < *r_ptr) | ((*l_ptr == *r_ptr) & carryFlag);
}
if (carryFlag) {
for (c_ptr = _valPtr + size; l_ptr < c_ptr; ++l_ptr) if (++*l_ptr) break;
if (l_ptr == c_ptr) {
if (capacity > size)
_valPtr[size++] = 1;
else {
l_ptr = new uint32[capacity <<= 1];
c_ptr = l_ptr + size;
while (l_ptr < c_ptr) *(l_ptr++) = *(_valPtr++);
*l_ptr = 1;
delete[] (_valPtr -= size);
_valPtr = l_ptr - size++;
}
}
}
}
else if (compareAbsoluteValueTo(rhs) >= 0)
this->_absSubtract(rhs);
else
{
BigInteger absGreaterOne(rhs);
absGreaterOne._absSubtract(*this);
*this = std::move(absGreaterOne);
}
return *this;
}
const BigInteger& BigInteger::operator-=(const BigInteger& rhs)
{
if (this == &rhs) { this->size = 0; return *this; }
_SharedMemBigInteger signModified_rhs(rhs);
signModified_rhs.negativity = !rhs.negativity;
*this += signModified_rhs;
return *this;
}
const BigInteger& BigInteger::operator>>=(const uint32 shift)
{
uint32 a = shift / BITS_OF_DWORD;
if (a >= size) { this->size = 0; return *this; }
else if (a) {
uint32 i = 0;
size -= a;
do {
_valPtr[i] = _valPtr[i + a];
++i;
} while (i < size);
for (a += size; i < a; ++i) _valPtr[i] = 0;
}
a = shift & (BITS_OF_DWORD - 1);
if (a && size)
{
uint32 pm1 = size - 1;
for (uint32 i = 0; i < pm1; ++i)
_valPtr[i] = (_valPtr[i] >> a) | ((_valPtr[i + 1] & ((1 << a) - 1)) << (32 - a));
if (0 == (_valPtr[pm1] >>= a)) --size;
}
return *this;
}
const BigInteger& BigInteger::operator<<=(const uint32 shift)
{
if (size)
{
uint32 a = shift / BITS_OF_DWORD, b = shift & (BITS_OF_DWORD - 1);
bool newMemAlloced = false;
if (b) ++a;
if (a) {
uint32 *souptr, *tarptr, *comptr;
if (capacity < (size += a)) {
newMemAlloced = true;
capacity = _getMinimumCapacity(size);
tarptr = new uint32[capacity];
comptr = tarptr + size;
tarptr += capacity;
while (tarptr > comptr) *(--tarptr) = 0;
}
else
tarptr = _valPtr + size;
souptr = _valPtr + (size - a);
while (souptr > _valPtr) *(--tarptr) = *(--souptr);
for (comptr = tarptr - a; tarptr > comptr; ) *(--tarptr) = 0;
if (newMemAlloced) {
delete[] _valPtr;
_valPtr = tarptr;
}
}
if (b) *this >>= (BITS_OF_DWORD - b);
}
return *this;
}
BigInteger operator*(const BigInteger& lhs, const BigInteger& rhs)
{//multipication
BigInteger ret = BigInteger::_absMultiply(lhs, rhs);
ret.negativity = (lhs.negativity != rhs.negativity);
return ret;
}
void BigInteger::_seperateToHigherAndLowerHalfs(BigInteger* dst) const
{
uint32 halfCapacity = capacity >> 1;
dst[0]._valPtr = _valPtr + halfCapacity;
dst[0].size = (size < halfCapacity) ? 0 : size - halfCapacity;
dst[0].capacity = _getMinimumCapacity(dst[0].size);
dst[1]._valPtr = _valPtr;
dst[1]._setSize((size < halfCapacity) ? size : halfCapacity);
dst[1].capacity = _getMinimumCapacity(dst[1].size);
}
BigInteger BigInteger::_absMultiply(const BigInteger& lhs, const BigInteger& rhs)
{
if ((!lhs.size) | (!rhs.size)) return BigInteger();
#ifdef FFT_MULTIPLICATION
uint32 sizeSum = lhs.size + rhs.size;
if (sizeSum == 2) return BigInteger((unsigned long long)lhs._valPtr[0] * rhs._valPtr[0]);
if (sizeSum <= FFT_MAX_N / (BITS_OF_DWORD / FFT_WORD_BITLEN)) {
BigInteger ret;
_FFTMultiply(ret, lhs, rhs);
return ret;
}
#endif
if (lhs.capacity != rhs.capacity)
{
const BigInteger& longer = (lhs.capacity >= rhs.capacity) ? lhs : rhs;
const BigInteger& shorter = (lhs.capacity >= rhs.capacity) ? rhs : lhs;
unsigned char _sharedMemBigIntegers[2 * sizeof(BigInteger)];
BigInteger* sharedMemeoryBigIntegers = reinterpret_cast<BigInteger*>(_sharedMemBigIntegers);
longer._seperateToHigherAndLowerHalfs(sharedMemeoryBigIntegers);//initialize read only variables
BigInteger ret = _absMultiply(sharedMemeoryBigIntegers[0], shorter);
ret <<= (longer.capacity << 4);
ret += _absMultiply(sharedMemeoryBigIntegers[1], shorter);
return ret;
}
if (lhs.capacity > 1)
{
unsigned char _sharedMemBigIntegers[4 * sizeof(BigInteger)];
BigInteger *lhsParts = reinterpret_cast<BigInteger*>(_sharedMemBigIntegers), *rhsParts = 2 + lhsParts;//read only variables
lhs._seperateToHigherAndLowerHalfs(lhsParts);
rhs._seperateToHigherAndLowerHalfs(rhsParts);//initialize read only variables
BigInteger higher_part = _absMultiply(lhsParts[0], rhsParts[0]);
BigInteger lower_part = _absMultiply(lhsParts[1], rhsParts[1]);
BigInteger mid_part = higher_part + lower_part;
mid_part += ((lhsParts[1] - lhsParts[0]) * (rhsParts[0] - rhsParts[1]));
higher_part <<= (lhs.capacity * BITS_OF_DWORD);
mid_part <<= (lhs.capacity * (BITS_OF_DWORD / 2));
higher_part += (mid_part += lower_part);
return higher_part;
}
return BigInteger((unsigned long long)*lhs._valPtr * *rhs._valPtr);
}
//Set *this to remainder and return the quotient.
//It is ok to execute this->absDivideAndSetThisToRemainder(*this)
BigInteger BigInteger::absDivideAndSetThisToRemainder(const BigInteger& rhs)
{
int pDiff = this->size - rhs.size;
if (0 == rhs.size) throw std::logic_error("Divide by zero");
if (pDiff < 0) return BigInteger();
int pow = pDiff * BITS_OF_DWORD;
int lhsLeftmostBitLen = 0, rhsLeftmostBitLen = 0;
for (uint32 lhsLeftmost = _valPtr[size - 1], rhsLeftmost = rhs._valPtr[rhs.size - 1]; lhsLeftmost | rhsLeftmost; ) {
if (lhsLeftmost) ++lhsLeftmostBitLen;
if (rhsLeftmost) ++rhsLeftmostBitLen;
lhsLeftmost >>= 1; rhsLeftmost >>= 1;
}
pow += 1 + lhsLeftmostBitLen - rhsLeftmostBitLen;
if (pow <= 0) return BigInteger();
BigInteger newrhs(rhs);
newrhs <<= --pow;
int leftMostBit = pow;
bool fillOne = !(newrhs.compareAbsoluteValueTo(*this) > 0);
if (fillOne)
this->_absSubtract(newrhs);
else if (--leftMostBit < 0)
return BigInteger();
bool* binaryList = new bool[pow + 1];
binaryList[pow] = fillOne;
while (--pow >= 0) {
newrhs >>= 1;
fillOne = binaryList[pow] = !(newrhs.compareAbsoluteValueTo(*this) > 0);
if (fillOne) this->_absSubtract(newrhs);
}
BigInteger ret;
ret.size = 1 + ((uint32)leftMostBit / BITS_OF_DWORD);
ret._valPtr = new uint32[ret.capacity = _getMinimumCapacity(ret.size)];
for (uint32 piece = 0; pow < leftMostBit; ++piece) {
ret._valPtr[piece] = 0;
int biMax = leftMostBit - pow;
if (biMax > BITS_OF_DWORD) biMax = BITS_OF_DWORD;
for (int bi = 0; bi < biMax; ++bi)
ret._valPtr[piece] |= ((uint32)binaryList[++pow] << bi);
}
delete[] binaryList;
return ret;
}
const BigInteger& BigInteger::operator/=(const BigInteger& rhs)
{
bool neg_ = (this->negativity != rhs.negativity);
*this = this->absDivideAndSetThisToRemainder(rhs);
this->negativity = neg_;
return *this;
}
const BigInteger& BigInteger::operator%=(const BigInteger& rhs)
{
this->absDivideAndSetThisToRemainder(rhs);
return *this;
}
int BigInteger::intValue() const
{
if (size == 0) return 0;
int ret = _valPtr[0] & 0x7FFFFFFF;
return negativity ? -ret : ret;
}
double BigInteger::doubleValue() const
{
double ret = 0.0;
for (uint32 i = 0; i < size; ++i) {
ret *= (double)0x100000000;
ret += _valPtr[i];
}
return negativity ? -ret : ret;
}
const std::string BigInteger::toString() const
{
if (size == 0) return std::string("0");
uint32 t = (size * 10) + 2;
char* buffer = new char[t];
char* c = buffer + t;
*(--c) = '\0';
const BigInteger ten(10);
BigInteger* newthis = new BigInteger(*this);
do {
BigInteger* temptr = new BigInteger(newthis->absDivideAndSetThisToRemainder(ten));
*(--c) = *(newthis->_valPtr) + '0';
delete newthis;
newthis = temptr;
} while (newthis->size);
delete newthis;
if (negativity) *(--c) = '-';
std::string ret(c);
delete[] buffer;
return ret;
}
char* BigInteger::toHexadecimalCharArray() const
{
char* c_str = new char[(size << 3) + 2];
char* c = c_str;
if (size)
{
if (negativity) *(c++) = '-';
uint32 *v_ptr;
for (v_ptr = _valPtr + size; v_ptr > _valPtr; ) {
uint32 piece = *(--v_ptr), shifting = BITS_OF_DWORD;
do {
shifting -= 4;
uint32 letter = (piece >> shifting) & 0xF;
*(c++) = (letter > 9) ? ('A' - 10 + letter) : ('0' + letter);
} while (shifting);
}
}
else *(c++) = '0';
*c = '\0';
return c_str;
}
bool* BigInteger::convertAbsToBinaryArray(size_t* out_digitsSize) const
{
if (!this->size) {
*out_digitsSize = 0;
return nullptr;
}
size_t digitsSize = this->size * BITS_OF_DWORD;
bool* ret = new bool[digitsSize];
for (uint32 i = 0, pieceIndex = 0; pieceIndex < this->size; ++pieceIndex, i += BITS_OF_DWORD)
{
uint32 piece = this->_valPtr[pieceIndex];
ret[i + 0] = (piece & (1 << 0)) != 0; ret[i + 1] = (piece & (1 << 1)) != 0; ret[i + 2] = (piece & (1 << 2)) != 0; ret[i + 3] = (piece & (1 << 3)) != 0;
ret[i + 4] = (piece & (1 << 4)) != 0; ret[i + 5] = (piece & (1 << 5)) != 0; ret[i + 6] = (piece & (1 << 6)) != 0; ret[i + 7] = (piece & (1 << 7)) != 0;
ret[i + 8] = (piece & (1 << 8)) != 0; ret[i + 9] = (piece & (1 << 9)) != 0; ret[i + 10] = (piece & (1 << 10)) != 0; ret[i + 11] = (piece & (1 << 11)) != 0;
ret[i + 12] = (piece & (1 << 12)) != 0; ret[i + 13] = (piece & (1 << 13)) != 0; ret[i + 14] = (piece & (1 << 14)) != 0; ret[i + 15] = (piece & (1 << 15)) != 0;
static_assert(BITS_OF_DWORD == 32, "convertAbsToBinaryArray");
ret[i + 16] = (piece & (1 << 16)) != 0; ret[i + 17] = (piece & (1 << 17)) != 0; ret[i + 18] = (piece & (1 << 18)) != 0; ret[i + 19] = (piece & (1 << 19)) != 0;
ret[i + 20] = (piece & (1 << 20)) != 0; ret[i + 21] = (piece & (1 << 21)) != 0; ret[i + 22] = (piece & (1 << 22)) != 0; ret[i + 23] = (piece & (1 << 23)) != 0;
ret[i + 24] = (piece & (1 << 24)) != 0; ret[i + 25] = (piece & (1 << 25)) != 0; ret[i + 26] = (piece & (1 << 26)) != 0; ret[i + 27] = (piece & (1 << 27)) != 0;
ret[i + 28] = (piece & (1 << 28)) != 0; ret[i + 29] = (piece & (1 << 29)) != 0; ret[i + 30] = (piece & (1 << 30)) != 0; ret[i + 31] = (piece & (1 << 31)) != 0;
}
if (out_digitsSize) {
do { --digitsSize; } while (!ret[digitsSize]);
*out_digitsSize = ++digitsSize;
}
return ret;
}
size_t BigInteger::getBitLength() const
{
if (size == 0) return 0;
size_t lowerBound = size * BITS_OF_DWORD - BITS_OF_DWORD;
uint32 x = _valPtr[size - 1];
while (x) { ++lowerBound; x >>= 1; }
return lowerBound;
}
BigInteger BigInteger::sqrt(bool ceilling) const
{//x = (prev_x + *this/prev_x) / 2
if (this->negativity && this->size != 0) throw std::logic_error("Cannot evaluate square root of a negative Biginteger.");
BigInteger x(1), prev_x;
do {
prev_x = x;
x += *this / prev_x;
x >>= 1;
} while (x != prev_x);
if (ceilling) {
BigInteger xSquared = x * x;
if (xSquared < *this) x += kBigInteger_1;
}
return x;
}
BigInteger BigInteger::pow(uint32 positive_exponent) const
{
if (0 == positive_exponent) return BigInteger(1);
BigInteger t = this->pow(positive_exponent >> 1);
BigInteger tSquared = _absMultiply(t, t);
if (positive_exponent & 1) {
BigInteger ret = _absMultiply(*this, tSquared);
ret.negativity = this->negativity;
return ret;
}
return tSquared;
}
//`m` must be a odd number and larger than BigInteger(2) to apply montgomeryModPow method
BigInteger BigInteger::modPow(const BigInteger& exponent, const BigInteger& m) const
{
if (0 == exponent.size) return BigInteger(1);
if ((0 == m.size) | m.negativity) throw std::logic_error("modular for `modPow` function must be positive.");
if (1 == (m._valPtr[0] | m.size)) return BigInteger(0);
bool montgomeryModPow = m._valPtr[0] & 1;
size_t digitsSizeOfExponent;
bool* binaryArrayOfExponent = exponent.convertAbsToBinaryArray(&digitsSizeOfExponent);
BigInteger base = exponent.negativity ? this->modInverse(m) : *this;
if (base.compareAbsoluteValueTo(m) > 0) base.absDivideAndSetThisToRemainder(m);
if (base.negativity) base += m;
BigInteger result = !montgomeryModPow ?
base._trivialModPow(binaryArrayOfExponent, digitsSizeOfExponent, m) :
base._montgomeryModPow(binaryArrayOfExponent, digitsSizeOfExponent, m);
delete[] binaryArrayOfExponent;
return result;
}
BigInteger BigInteger::_trivialModPow(bool* binaryArrayOfExponent, size_t bitsOfExponent, const BigInteger& m) const
{
BigInteger result(1), newResult;
BigInteger tSquared(*this), thisPow_i;
for (size_t i = 0; i < bitsOfExponent; ++i) {
thisPow_i = std::move(tSquared);
if (binaryArrayOfExponent[i]) {
newResult = _absMultiply(result, thisPow_i);
newResult.absDivideAndSetThisToRemainder(m);
result = std::move(newResult);
}
tSquared = _absMultiply(thisPow_i, thisPow_i);
tSquared.absDivideAndSetThisToRemainder(m);
}
return result;
}
//http://www.hackersdelight.org/MontgomeryMultiplication.pdf
BigInteger BigInteger::_montgomeryModPow(bool* binaryArrayOfExponent, size_t bitsOfExponent, const BigInteger& m) const
{
BigInteger r(1);
r <<= m.size * BITS_OF_DWORD;
BigInteger r_tmp(r), m_tmp(m);
_EEAstruct eeaStruct = _extendedEuclid(&r_tmp, &m_tmp);
BigInteger r_slash = std::move(*eeaStruct.x);
BigInteger m_slash = std::move(*eeaStruct.y); m_slash.negativity = !m_slash.negativity;
delete eeaStruct.d; delete eeaStruct.x; delete eeaStruct.y;
BigInteger result_mf(r), newResult;
BigInteger thisPow_2i(*this * r), thisPow_i;
result_mf.absDivideAndSetThisToRemainder(m);
thisPow_2i.absDivideAndSetThisToRemainder(m);
for (size_t i = 0; i < bitsOfExponent; ++i) {
thisPow_i = std::move(thisPow_2i);
if (binaryArrayOfExponent[i]) {
newResult = result_mf * thisPow_i;//t = a_ * b_
BigInteger tm_slash = newResult * m_slash;//tm'
if (tm_slash.size > m.size) tm_slash.size = m.size;//tm' mod r
newResult += tm_slash * m;// (t + (tm' mod r)m)
newResult >>= BITS_OF_DWORD * m.size;//u = (t + (tm' mod r)m) / r
if (newResult.compareAbsoluteValueTo(m) >= 0) newResult._absSubtract(m);//if (u >= m) return u - m;
result_mf = std::move(newResult);
}
thisPow_2i = thisPow_i * thisPow_i;
BigInteger tm_slash = thisPow_2i * m_slash;
if (tm_slash.size > m.size) tm_slash.size = m.size;
thisPow_2i += tm_slash * m;
thisPow_2i >>= BITS_OF_DWORD * m.size;
if (thisPow_2i.compareAbsoluteValueTo(m) >= 0) thisPow_2i._absSubtract(m);
}
BigInteger result = result_mf * r.modInverse(m);
result.absDivideAndSetThisToRemainder(m);
if (result < 0) result += m;
return result;
}
//return BigInteger(0) when the inverse doesnot exist
BigInteger BigInteger::modInverse(const BigInteger& m) const
{
if ((0 == m.size) | m.negativity) throw std::logic_error("modular for `modInverse` function must be positive.");
if (gcd(*this, m) != kBigInteger_1) return BigInteger(0);
BigInteger a_(*this), m_(m);
_EEAstruct eeaStruct = _extendedEuclid(&a_, &m_);
BigInteger ddd = *this * *eeaStruct.x + m * *eeaStruct.y;
BigInteger ret = std::move(*eeaStruct.x);
delete eeaStruct.d; delete eeaStruct.x; delete eeaStruct.y;
if (ret.negativity) ret += m;
return ret;
}
BigInteger::_EEAstruct BigInteger::_extendedEuclid(BigInteger* a, BigInteger* b)
{
if (b->size == 0) return BigInteger::_EEAstruct{ new BigInteger(*a), new BigInteger(1), new BigInteger(0) };
bool neg_ = (a->negativity != b->negativity);
BigInteger quotient = a->absDivideAndSetThisToRemainder(*b);
quotient.negativity = neg_;
BigInteger::_EEAstruct ts = _extendedEuclid(b, a);
*ts.x -= quotient * *ts.y;
return BigInteger::_EEAstruct{ ts.d, ts.y, ts.x };
}
BigInteger BigInteger::gcd(const BigInteger& a, const BigInteger& b)
{
BigInteger a_(a), b_(b);
BigInteger* result = _euclidGcd(&a_, &b_);
BigInteger ret = std::move(*result);
ret.negativity = false;
return ret;
}
BigInteger* BigInteger::_euclidGcd(BigInteger* a, BigInteger* b)
{
if (b->size == 0) return a;
a->absDivideAndSetThisToRemainder(*b);
return _euclidGcd(b, a);
}
//Set `confidenceFactor` <= 0 to run Deterministic Robin-Miller Primality Test.
//When testing integers contain more than 1000 bits, it makes it a LITTLE BIT faster to
//set `confidenceFactor` to a positive number at the expense of
//the probability of getting a wrong result is no more than 4^(-confidenceFactor)
bool BigInteger::isPrime(int confidenceFactor) const
{
if (0 == size || negativity) return false;
if (1 == size && _valPtr[0] <= 3) return (_valPtr[0] > 1);
if ((_valPtr[0] & 1) == 0) return false;
BigInteger thisMinus1(*this); thisMinus1 += BigInteger(-1);
double ln_n = log(size * BITS_OF_DWORD);
int maxTesterForDeterministicResult = (int)(2.0 * ln_n * ln_n);
BigInteger a(1);
if (size <= 2) goto qwordTest;
if (maxTesterForDeterministicResult <= confidenceFactor) goto drmpt;
if (confidenceFactor > 0)
{
qwordTest: const char kTestNumbers[] = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37 };
int index = 0;
do {
a._valPtr[0] = kTestNumbers[index];
if (a.compareAbsoluteValueTo(thisMinus1) >= 0) return true;
if (!_MillerRabinPrimalityTest(a, thisMinus1)) return false;
} while (++index < sizeof(kTestNumbers) / sizeof(char));
if (size > 2) {
confidenceFactor -= (sizeof(kTestNumbers) / sizeof(char));
std::mt19937 mt(gRandomDevice());
do {
a._valPtr[0] = mt();
if (a._valPtr[0] < 41) a._valPtr[0] += 41;
if (!_MillerRabinPrimalityTest(a, thisMinus1)) return false;
} while (--confidenceFactor > 0);
}
}
else
{
drmpt: uint32 base = 2;
do {
a._valPtr[0] = base;
if (!_MillerRabinPrimalityTest(a, thisMinus1)) return false;
} while (++base <= (uint32)maxTesterForDeterministicResult);
}
return true;
}
// http://www.sti15.com/nt/pseudoprimes.html
bool BigInteger::weakerBailliePSWPrimeTest() const
{
if (0 == size || negativity) return false;
if (1 == size && _valPtr[0] <= 3) return (_valPtr[0] > 1);
if ((_valPtr[0] & 1) == 0) return false;
BigInteger thisMinus1(*this); thisMinus1 += BigInteger(-1);
BigInteger a(2);
if (!_MillerRabinPrimalityTest(a, thisMinus1)) return false;
if (_LucasPseudoprimeTest()) {
a._valPtr[0] = 3;
if (_MillerRabinPrimalityTest(a, thisMinus1)) return true;
throw std::logic_error("Severe logic flaw detected during `weakerBailliePSWPrimeTest`, please report this issue.");
}
return false;
}
bool BigInteger::_MillerRabinPrimalityTest(const BigInteger& a, const BigInteger& thisMinus1) const
{//logically wrong when *this <= 2
if (a.modPow(thisMinus1, *this) != kBigInteger_1) return false;
BigInteger u(thisMinus1);
do { u >>= 1; } while ((u._valPtr[0] & 1) == 0);
BigInteger x = a.modPow(u, *this);
do {
BigInteger y = _absMultiply(x, x);
y.absDivideAndSetThisToRemainder(*this);
if (y == kBigInteger_1 && x != kBigInteger_1 && x != thisMinus1) return false;
x = std::move(y);
u <<= 1;
} while (u < *this);
if (x != kBigInteger_1) return false;
return true;
}
//Calculating the Jacobi symbol according to the properties at https://en.wikipedia.org/wiki/Jacobi_symbol
int BigInteger::JacobiSymbol(const BigInteger& upperArgument, const BigInteger& lowerArgument)
{
if ((!lowerArgument.testBit(0)) | lowerArgument.negativity)
throw std::logic_error("lowerArgument of function `JacobiSymbol` must be a positive odd number.");
BigInteger denominator(lowerArgument);
BigInteger numerator(upperArgument);
if (numerator.negativity) {
numerator.absDivideAndSetThisToRemainder(denominator);
numerator += denominator;
}
return _JacobiSymbolImpl(&numerator, &denominator);
}
// http://math.fau.edu/richman/jacobi.htm
int BigInteger::_JacobiSymbolImpl(BigInteger* numerator, BigInteger* denominator)
{
if (denominator->size == 1 && denominator->_valPtr[0] == 1) return 1;//"Following the normal convention for the empty product, (Z / 1) = 1 for all `Z` "
if (numerator->size == 0) return 0;
numerator->absDivideAndSetThisToRemainder(*denominator);
unsigned countFactorsOf2 = 0;
for (; false == numerator->testBit(0) && numerator->size != 0; *numerator >>= 1) ++countFactorsOf2;
if (gcd(*numerator, *denominator) != 1) return 0;
int ret = 1;
if (countFactorsOf2 & 1) {
uint32 m = denominator->_valPtr[0] % 8;
ret = ((m == 1) | (m == 7)) ? 1 : -1;
}
if (denominator->_valPtr[0] % 4 == 3 && numerator->_valPtr[0] % 4 == 3) ret = -ret;
return ret * _JacobiSymbolImpl(denominator, numerator);
}
// http://stackoverflow.com/questions/38343738/lucas-probable-prime-test
std::pair<BigInteger, BigInteger> BigInteger::_getModLucasSequence(const BigInteger& k, const BigInteger& D, const BigInteger& P, const BigInteger& Q) const
{
BigInteger U_n(1), V_n(P), Q_n(Q);
if (V_n < 0) { V_n.absDivideAndSetThisToRemainder(*this); V_n += *this; }
if (Q_n < 0) { Q_n.absDivideAndSetThisToRemainder(*this); Q_n += *this; }
BigInteger U(!k.testBit(0) ? 0 : 1);
BigInteger V(!k.testBit(0) ? 2 : V_n);
BigInteger n(k);
n >>= 1;
while (n.size)
{
BigInteger U2 = _absMultiply(U_n, V_n);
U2.absDivideAndSetThisToRemainder(*this);
BigInteger V2 = _absMultiply(V_n, V_n);
V2 -= (Q_n << 1);
V2.absDivideAndSetThisToRemainder(*this);
if (V2 < 0) V2 += *this;
BigInteger Q2 = _absMultiply(Q_n, Q_n);
Q2.absDivideAndSetThisToRemainder(*this);
if ((n._valPtr[0] & 1)) {
BigInteger newU = _absMultiply(U, V2) + _absMultiply(V, U2);
if (newU.testBit(0)) newU += *this;
newU >>= 1;
newU.absDivideAndSetThisToRemainder(*this);
BigInteger newV = _absMultiply(V, V2) + _absMultiply(U, U2) * D;
if (newV.testBit(0)) newV += *this;
newV >>= 1;
newV.absDivideAndSetThisToRemainder(*this);
if (newV < 0) newV += *this;
U = std::move(newU);
V = std::move(newV);
}
U_n = std::move(U2);
V_n = std::move(V2);
Q_n = std::move(Q2);
n >>= 1;
}
return std::pair<BigInteger, BigInteger>(U, V);
}
bool BigInteger::_LucasPseudoprimeTest() const
{//logically wrong when *this is small
int D = 5;
do {
if (gcd(D, *this) != 1) return 0;
if (JacobiSymbol(D, *this) == -1) break;
D = -D + ((D < 0) ? 2 : -2);
} while (true);
const BigInteger Q((1 - D) / 4);
BigInteger deltaThis(*this); deltaThis += 1;
std::pair<BigInteger, BigInteger> UV = this->_getModLucasSequence(deltaThis, D, 1, Q);
return (UV.first.size == 0);
}
//Warnning: not suitable when *this has more than 10k bits
BigInteger BigInteger::nextProbablePrime() const
{
if (this->negativity || this->size == 0) return BigInteger(2);
BigInteger ret(*this);
if (ret.size == 1)
while (true) if ((ret += kBigInteger_1).isPrime()) return ret;
if ((ret._valPtr[0] & 1) == 0) ++ret._valPtr[0];
else ret += 2;
const char kTestNumbers[] = { 3, 5, 7, 11, 13, 17, 19, 23 };
BigInteger m(2);
static_assert(sizeof(char) == 1, "");
uint32 modList[sizeof(kTestNumbers)];
for (int i = 0; i < sizeof(kTestNumbers); ++i) {
m._valPtr[0] = kTestNumbers[i];
BigInteger x(ret);
x.absDivideAndSetThisToRemainder(m);
modList[i] = x.size ? x._valPtr[0] : 0;
}
while (true)
{
bool multipleOfTestNumbers = false;
for (int i = 0; i < sizeof(kTestNumbers); ++i) {
if (0 == modList[i] % kTestNumbers[i]) multipleOfTestNumbers = true;
modList[i] += 2;//it may overflow until we find a next prime if *this is very large
}
if (!multipleOfTestNumbers && ret.weakerBailliePSWPrimeTest()) return ret;
ret += 2;
}
}
//for cryptography
BigInteger::BigInteger(const void* dataPtr, size_t dataSize)
{