-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBigInteger.cpp
More file actions
4931 lines (3764 loc) · 107 KB
/
BigInteger.cpp
File metadata and controls
4931 lines (3764 loc) · 107 KB
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
#ifndef BIGINTEGER_H
#define BIGINTEGER_H
#include <chrono>
#include <string>
#include<stdexcept>
#include<cstring>
#include <memory>
#include <vector>
#include <cstdlib>
#include <sstream>
#include <iostream>
#include <fstream>
#include <algorithm>
#include <cmath>
#include <vector>
#include <memory>
using namespace std;
class IIRandom;
typedef shared_ptr<IIRandom> IRandom;
class IIRandom
{
public:
virtual void NextBytes(vector<uint8_t> &buf) = 0;
virtual double NextDouble() = 0;
virtual int32_t Next() = 0;
virtual int32_t Next(const int32_t maxValue) = 0;
virtual int32_t Next(const int32_t minValue, const int32_t maxValue) = 0;
};
#include <vector>
using namespace std;
class IIRandomGenerator;
typedef shared_ptr<IIRandomGenerator> IRandomGenerator;
class IIRandomGenerator
{
public:
/// <summary>Add more seed material to the generator.</summary>
/// <param name="seed">A byte array to be mixed into the generator's state.</param>
virtual void AddSeedMaterial(vector<uint8_t> &seed) = 0;
/// <summary>Add more seed material to the generator.</summary>
/// <param name="seed">A long value to be mixed into the generator's state.</param>
virtual void AddSeedMaterial(const int64_t seed) = 0;
/// <summary>Fill byte array with random values.</summary>
/// <param name="bytes">Array to be filled.</param>
virtual void NextBytes(vector<uint8_t> &bytes) = 0;
/// <summary>Fill byte array with random values.</summary>
/// <param name="bytes">Array to receive bytes.</param>
/// <param name="start">Index to start filling at.</param>
/// <param name="len">Length of segment to fill.</param>
virtual void NextBytes(vector<uint8_t> &bytes, const int32_t start, const int32_t len) = 0;
};
#include <vector>
#include <memory>
using namespace std;
class IIRandomNumberGenerator;
typedef shared_ptr<IIRandomNumberGenerator> IRandomNumberGenerator;
class IIRandomNumberGenerator
{
public:
virtual void GetBytes(vector<uint8_t> &data) = 0;
virtual void GetNonZeroBytes(vector<uint8_t> &data) = 0;
};
class IICryptoApiRandomGenerator;
typedef shared_ptr<IICryptoApiRandomGenerator> ICryptoApiRandomGenerator;
class IICryptoApiRandomGenerator : public virtual IIRandomGenerator
{};
class IISecureRandom;
typedef shared_ptr<IISecureRandom> ISecureRandom;
class IISecureRandom : public virtual IIRandom
{
public:
virtual vector<uint8_t> GenerateSeed(const int32_t length) = 0;
virtual void SetSeed(vector<uint8_t> &seed) = 0;
virtual void SetSeed(const int64_t seed) = 0;
virtual void NextBytes(vector<uint8_t> &buf) = 0;
virtual void NextBytes(vector<uint8_t> &buf, const int32_t off, const int32_t len) = 0;
virtual int32_t NextInt32() = 0;
virtual int64_t NextInt64() = 0;
};
class NumberStyles
{
public:
static const auto None = 0;
static const auto AllowLeadingWhite = 1;
static const auto AllowTrailingWhite = 2;
static const auto AllowLeadingSign = 4;
static const auto AllowTrailingSign = 8;
static const auto AllowParentheses = 16;
static const auto AllowDecimalPoint = 32;
static const auto AllowThousands = 64;
static const auto AllowExponent = 128;
static const auto AllowCurrencySymbol = 256;
static const auto AllowHexSpecifier = 512;
static const auto Integer = 4 | 2 | 1;
};
class Bits
{
public:
static void ReverseByteArray(const void *Source, void * Dest, int64_t size)
{
uint8_t *ptr_src = (uint8_t *)Source;
uint8_t *ptr_dest = (uint8_t *)Dest;
ptr_dest = ptr_dest + (size - 1);
while (size > 0)
{
*ptr_dest = *ptr_src;
ptr_src += 1;
ptr_dest -= 1;
size -= 1;
} // end while
} // end function ReverseByteArray
inline static int32_t ReverseBytesInt32(const int32_t value)
{
int32_t i1 = value & 0xFF;
int32_t i2 = Bits::Asr32(value, 8) & 0xFF;
int32_t i3 = Bits::Asr32(value, 16) & 0xFF;
int32_t i4 = Bits::Asr32(value, 24) & 0xFF;
return (i1 << 24) | (i2 << 16) | (i3 << 8) | (i4 << 0);
} // end function ReverseBytesInt32
inline static uint8_t ReverseBitsUInt8(const uint8_t value)
{
uint8_t result = ((value >> 1) & 0x55) | ((value << 1) & 0xAA);
result = ((result >> 2) & 0x33) | ((result << 2) & 0xCC);
return ((result >> 4) & 0x0F) | ((result << 4) & 0xF0);
} // end function ReverseBitsUInt8
inline static uint16_t ReverseBytesUInt16(const uint16_t value)
{
return ((value & uint32_t(0xFF)) << 8 | (value & uint32_t(0xFF00)) >> 8);
} // end function ReverseBytesUInt16
inline static uint32_t ReverseBytesUInt32(const uint32_t value)
{
return (value & uint32_t(0x000000FF)) << 24 |
(value & uint32_t(0x0000FF00)) << 8 |
(value & uint32_t(0x00FF0000)) >> 8 |
(value & uint32_t(0xFF000000)) >> 24;
} // end function ReverseBytesUInt32
inline static uint64_t ReverseBytesUInt64(const uint64_t value)
{
return (value & uint64_t(0x00000000000000FF)) << 56 |
(value & uint64_t(0x000000000000FF00)) << 40 |
(value & uint64_t(0x0000000000FF0000)) << 24 |
(value & uint64_t(0x00000000FF000000)) << 8 |
(value & uint64_t(0x000000FF00000000)) >> 8 |
(value & uint64_t(0x0000FF0000000000)) >> 24 |
(value & uint64_t(0x00FF000000000000)) >> 40 |
(value & uint64_t(0xFF00000000000000)) >> 56;
} // end function ReverseBytesUInt64
inline static int32_t Asr32(const int32_t value, const int32_t ShiftBits)
{
int32_t result = value >> ShiftBits;
if ((value & 0x80000000) > 0)
{
// if you don't want to cast (0xFFFFFFFF) to an Int32,
// simply replace it with (-1) to avoid range check error.
result = result | (int32_t(0xFFFFFFFF) << (32 - ShiftBits));
} // end if
return result;
} // end function Asr32
inline static int64_t Asr64(const int64_t value, const int32_t ShiftBits)
{
int64_t result = value >> ShiftBits;
if ((value & 0x8000000000000000) > 0)
{
result = result | (0xFFFFFFFFFFFFFFFF << (64 - ShiftBits));
} // end if
return result;
} // end function Asr64
inline static uint32_t RotateLeft32(const uint32_t a_value, int32_t a_n)
{
a_n = a_n & 31;
return (a_value << a_n) | (a_value >> (32 - a_n));
} // end function RotateLeft32
inline static uint64_t RotateLeft64(const uint64_t a_value, int32_t a_n)
{
a_n = a_n & 63;
return (a_value << a_n) | (a_value >> (64 - a_n));
} // end function RotateLeft64
inline static uint32_t RotateRight32(const uint32_t a_value, int32_t a_n)
{
a_n = a_n & 31;
return (a_value >> a_n) | (a_value << (32 - a_n));
} // end function RotateRight32
inline static uint64_t RotateRight64(const uint64_t a_value, int32_t a_n)
{
a_n = a_n & 63;
return (a_value >> a_n) | (a_value << (64 - a_n));
} // end function RotateRight64
};
#include <memory>
#include <chrono>
using namespace std::chrono;
class Pcg
{
private:
/// <summary>
/// The RNG state. All values are possible.
/// </summary>
static uint64_t m_state;
/// <summary>
/// Controls which RNG sequence (stream) is selected.
/// Must <strong>always</strong> be odd.
/// </summary>
static uint64_t m_inc;
/// <summary>
/// Internal variable used for Casting.
/// </summary>
static int64_t I64;
/// <summary>
/// Seed Pcg in two parts, a state initializer
/// and a sequence selection constant (a.k.a.
/// stream id).
/// </summary>
/// <param name="initState">Initial state.</param>
/// <param name="initSeq">Initial sequence</param>
static inline void Seed(const uint64_t initState, const uint64_t initSeq);
/// <summary>
/// Generates a uniformly distributed number, r,
/// where 0 <= r < exclusiveBound.
/// </summary>
/// <param name="exclusiveBound">Exclusive bound.</param>
static uint32_t Range32(const uint32_t exclusiveBound);
/// <summary>
/// Generates an Init State from System Time.
/// </summary>
/// <param name="initSeq">Calculated initSeq.</param>
/// <returns> UInt64 </returns>
static inline uint64_t GetInitState(uint64_t &initSeq);
/// <summary>
/// Generates an Init Sequence from GetInitState value * 181783497276652981.
/// <param name="tempVal">Previous value from GetInitState.</param>
/// </summary>
/// <returns> UInt64 </returns>
static inline uint64_t GetInitSeq(const uint64_t tempVal);
public:
/// <summary>
/// Initializes a new instance of the <see cref="TPcg"/> class
/// <strong>FOR TESTING</strong> with a <strong>KNOWN</strong> seed.
/// </summary>
Pcg();
/// <summary>
/// Initializes a new instance of the <see cref="TPcg"/> class.
/// </summary>
/// <param name="initState">Initial state.</param>
/// <param name="initSeq">Initial sequence</param>
Pcg(const uint64_t initState, const uint64_t initSeq);
/// <summary>
/// Generates a uniformly-distributed 32-bit random number.
/// </summary>
static uint32_t NextUInt32();
/// <summary>
/// Generates a uniformly distributed number, r,
/// where minimum <= r < exclusiveBound.
/// </summary>
/// <param name="minimum">The minimum inclusive value.</param>
/// <param name="exclusiveBound">The maximum exclusive bound.</param>
static uint32_t NextUInt32(const uint32_t minimum, const uint32_t exclusiveBound);
/// <summary>
/// Generates a uniformly distributed number, r,
/// where minimum <= r < exclusiveBound.
/// </summary>
/// <param name="minimum">The minimum inclusive value.</param>
/// <param name="exclusiveBound">The maximum exclusive bound.</param>
static int NextInt(const int minimum, const int exclusiveBound);
};
uint64_t Pcg::m_state = 0;
uint64_t Pcg::m_inc = 0;
int64_t Pcg::I64 = 0;
Pcg::Pcg()
{
uint64_t LinitState, LinitSeq;
LinitState = GetInitState(LinitSeq);
// ==> initializes using system time as initState and calculated value as
// initSeq
Seed(LinitState, LinitSeq);
}
Pcg::Pcg(const uint64_t initState, const uint64_t initSeq)
{
Seed(initState, initSeq);
}
uint32_t Pcg::NextUInt32()
{
uint64_t oldState;
uint32_t xorShifted;
int rot;
oldState = m_state;
m_state = oldState * uint64_t(6364136223846793005) + m_inc;
xorShifted = uint32_t(((oldState >> 18) ^ oldState) >> 27);
rot = int(oldState >> 59);
return (xorShifted >> rot) | (xorShifted << ((-rot) & 31));
}
uint32_t Pcg::NextUInt32(const uint32_t minimum, const uint32_t exclusiveBound)
{
uint32_t boundRange, rangeResult;
boundRange = exclusiveBound - minimum;
rangeResult = Range32(boundRange);
return rangeResult + minimum;
}
int Pcg::NextInt(const int minimum, const int exclusiveBound)
{
uint32_t boundRange, rangeResult;
boundRange = uint32_t(exclusiveBound - minimum);
rangeResult = Range32(boundRange);
return int(rangeResult) + int(minimum);
}
void Pcg::Seed(const uint64_t initState, const uint64_t initSeq)
{
m_state = uint32_t(0);
m_inc = (initSeq << 1) | uint64_t(1);
NextUInt32();
m_state = m_state + initState;
NextUInt32();
}
uint32_t Pcg::Range32(const uint32_t exclusiveBound)
{
uint32_t r, threshold;
// To avoid bias, we need to make the range of the RNG
// a multiple of bound, which we do by dropping output
// less than a threshold. A naive scheme to calculate the
// threshold would be to do
//
// threshold = UInt64($100000000) mod exclusiveBound;
//
// but 64-bit div/mod is slower than 32-bit div/mod
// (especially on 32-bit platforms). In essence, we do
//
// threshold := UInt32((UInt64($100000000) - exclusiveBound) mod exclusiveBound);
//
// because this version will calculate the same modulus,
// but the LHS value is less than 2^32.
threshold = uint32_t((uint64_t(0x100000000) - exclusiveBound) % exclusiveBound);
// Uniformity guarantees that this loop will terminate.
// In practice, it should terminate quickly; on average
// (assuming all bounds are equally likely), 82.25% of
// the time, we can expect it to require just one
// iteration. In the worst case, someone passes a bound
// of 2^31 + 1 (i.e., 2147483649), which invalidates
// almost 50% of the range. In practice bounds are
// typically small and only a tiny amount of the range
// is eliminated.
while (true)
{
r = NextUInt32();
if (r >= threshold)
{
return r % exclusiveBound;
}
}
return 0; // to make FixInsight Happy :)
}
uint64_t Pcg::GetInitState(uint64_t &initSeq)
{
milliseconds ms = duration_cast<milliseconds>(system_clock::now().time_since_epoch());
uint64_t result = ms.count();
initSeq = GetInitSeq(result) * uint64_t(int64_t(1000000));
return result;
}
uint64_t Pcg::GetInitSeq(const uint64_t tempVal)
{
return tempVal * uint64_t(181783497276652981);
}
#include <string>
class RandomNumberGenerator : public IRandomNumberGenerator
{
private:
// Resource string
static const char * UnknownAlgorithm;
public:
static IRandomNumberGenerator CreateRNG();
static IRandomNumberGenerator CreateRNG(const string rngName);
virtual void GetBytes(vector<uint8_t> &data) = 0;
virtual void GetNonZeroBytes(vector<uint8_t> &data) = 0;
};
class PCGRandomNumberGenerator : public virtual IIRandomNumberGenerator, public RandomNumberGenerator
{
public:
PCGRandomNumberGenerator();
virtual void GetBytes(vector<uint8_t> &data);
virtual void GetNonZeroBytes(vector<uint8_t> &data);
};
PCGRandomNumberGenerator::PCGRandomNumberGenerator()
{
Pcg();
}
void PCGRandomNumberGenerator::GetBytes(vector<uint8_t> &data)
{
int64_t i;
for (i = data.size() - 1; i >= 0; i--)
{
data[i] = uint8_t(Pcg::NextInt(INT32_MIN, INT32_MAX));
}
}
void PCGRandomNumberGenerator::GetNonZeroBytes(vector<uint8_t> &data)
{
int64_t i;
uint8_t val;
i = data.size();
while (i > 0)
{
do
{
val = uint8_t(Pcg::NextUInt32(INT32_MIN, INT32_MAX));
} while (!(val == 0));
data[i - 1] = val;
i--;
}
}
#include<stdexcept>
#include<cstring>
const char * RandomNumberGenerator::UnknownAlgorithm = "Unknown Random Generation Algorithm Requested";
IRandomNumberGenerator RandomNumberGenerator::CreateRNG()
{
return make_shared<PCGRandomNumberGenerator>();
}
IRandomNumberGenerator RandomNumberGenerator::CreateRNG(const string rngName)
{
if (rngName == "PCGRandomNumberGenerator") return make_shared<PCGRandomNumberGenerator>();
throw invalid_argument(UnknownAlgorithm);
}
class CryptoApiRandomGenerator : public virtual IICryptoApiRandomGenerator, public virtual IIRandomGenerator
{
private:
// Resource string
const char * NegativeOffset = "Start Offset Cannot be Negative, \"Start\"";
const char * ArrayTooSmall = "Byte Array Too Small For Requested Offset and Length";
IRandomNumberGenerator FrndProv = nullptr;
public:
/// <summary>
/// Uses TRandomNumberGenerator.CreateRNG() to Get randomness generator
/// </summary>
CryptoApiRandomGenerator()
{
FrndProv = RandomNumberGenerator::CreateRNG();
}
CryptoApiRandomGenerator(IRandomNumberGenerator rng)
{
FrndProv = rng;
}
/// <summary>Add more seed material to the generator.</summary>
/// <param name="seed">A byte array to be mixed into the generator's state.</param>
virtual void AddSeedMaterial(vector<uint8_t> &seed) {};
/// <summary>Add more seed material to the generator.</summary>
/// <param name="seed">A long value to be mixed into the generator's state.</param>
virtual void AddSeedMaterial(const int64_t seed) {};
/// <summary>Fill byte array with random values.</summary>
/// <param name="bytes">Array to be filled.</param>
virtual void NextBytes(vector<uint8_t> &bytes)
{
FrndProv.get()->GetBytes(bytes);
}
/// <summary>Fill byte array with random values.</summary>
/// <param name="bytes">Array to receive bytes.</param>
/// <param name="start">Index to start filling at.</param>
/// <param name="len">Length of segment to fill.</param>
virtual void NextBytes(vector<uint8_t> &bytes, const int32_t start, const int32_t len)
{
vector<uint8_t> tmpBuf;
if (start < 0)
throw invalid_argument(NegativeOffset);
if (bytes.size() < (start + len))
throw invalid_argument(ArrayTooSmall);
if ((bytes.size() == len) && (start == 0))
NextBytes(bytes);
else
{
tmpBuf = vector<uint8_t>(len);
NextBytes(tmpBuf);
std::memmove(&tmpBuf[0], &bytes[start], len * sizeof(uint8_t));
}
}
};
#include <memory>
#include <vector>
#include <cstdlib>
#include <cmath>
using namespace std;
class Random : public virtual IIRandom
{
private:
// Resourcestring
const char * BufferNil = "Buffer Cannot be Nil";
const char * MaxValueNegative = "maxValue Must be Positive";
const char * InvalidMinValue = "minValue Cannot be Greater Than maxValue";
private:
const int32_t MBIG = int32_t(2147483647);
const int32_t MSEED = int32_t(161803398);
const int32_t MZ = int32_t(0);
static vector<int32_t> SeedArray;
private:
int32_t inext, inextp;
inline int32_t InternalSample();
double GetSampleForLargeRange();
protected:
/// <summary>Returns a random floating-point number between 0.0 and 1.0.</summary>
/// <returns>A double-precision floating point number that is greater than or equal to 0.0, and less than 1.0.</returns>
virtual double Sample();
public:
Random()
{
SeedArray = vector<int32_t>(56);
}
Random(const int32_t Seed);
~Random();
virtual void NextBytes(vector<uint8_t> &buf);
virtual double NextDouble();
virtual int32_t Next();
virtual int32_t Next(const int32_t maxValue);
virtual int32_t Next(const int32_t minValue, const int32_t maxValue);
};
vector<int32_t> Random::SeedArray = vector<int32_t>();
Random::Random(const int32_t Seed)
{
Random();
int32_t num1, num2, index1, index2;
num1 = MSEED - abs(Seed);
SeedArray[55] = num1;
num2 = 1;
for (index1 = 1; index1 < 55; index1++)
{
index2 = 21 * index1 % 55;
SeedArray[index2] = num2;
num2 = num1 - num2;
if (num2 < 0)
num2 = num2 + INT32_MAX;
num1 = SeedArray[index2];
}
index1 = 1;
while (index1 < 5)
{
for (index2 = 1; index2 < 56; index2++)
{
SeedArray[index2] = SeedArray[index2] - SeedArray[1 + (index2 + 30) % 55];
if (SeedArray[index2] < 0)
SeedArray[index2] = SeedArray[index2] + INT32_MAX;
}
index1++;
}
inext = 0;
inextp = 21;
}
Random::~Random()
{
}
double Random::Sample()
{
return InternalSample() * 4.6566128752458E-10;
}
void Random::NextBytes(vector<uint8_t> &buf)
{
int32_t i;
if (buf.empty())
throw invalid_argument(BufferNil);
for (i = 0; i < buf.size(); i++)
buf[i] = uint8_t(InternalSample() % (255 + 1));
}
double Random::NextDouble()
{
return Sample();
}
int32_t Random::InternalSample()
{
int32_t _inext, _inextp, index1, index2, num;
_inext = inext;
_inextp = inextp;
index1 = _inext + 1;
if ((index1) >= 56)
index1 = 1;
index2 = _inextp + 1;
if ((index2) >= 56)
index2 = 1;
num = SeedArray[index1] - SeedArray[index2];
if (num < 0)
num = num + INT32_MAX;
SeedArray[index1] = num;
inext = index1;
inextp = index2;
return num;
}
double Random::GetSampleForLargeRange()
{
int32_t num;
num = InternalSample();
if (InternalSample() % 2 == 0)
num = -num;
return (num + 2147483646.0) / 4294967293.0;
}
int32_t Random::Next()
{
return InternalSample();
}
int32_t Random::Next(const int32_t maxValue)
{
if (maxValue < 0)
throw out_of_range(MaxValueNegative);
return int32_t(trunc(Sample() * maxValue));
}
int32_t Random::Next(const int32_t minValue, const int32_t maxValue)
{
int64_t num;
if (minValue > maxValue)
throw out_of_range(InvalidMinValue);
num = int64_t(maxValue) - int64_t(minValue);
if (num <= int64_t(INT32_MAX))
return int32_t(trunc(Sample()) * num) + minValue;
return int32_t(int64_t(trunc(GetSampleForLargeRange()) * num) + int64_t(minValue));
}
class SecureRandom : public Random, public virtual IISecureRandom
{
private:
// Resource string
const char * UnrecognisedPRNGAlgorithm = "Unrecognised PRNG Algorithm: %s \"algorithm\"";
const char * CannotBeNegative = "Cannot be Negative \"maxValue\"";
const char * InvalidMaxValue = "maxValue Cannot be Less Than minValue";
private:
static int64_t Counter;
static ISecureRandom master;
static double DoubleScale;
static int64_t NextCounterValue();
protected:
static IRandomGenerator generator;
public:
SecureRandom()
{
Boot();
}
SecureRandom(IRandomGenerator _generator)
: Random(0)
{
generator = _generator;
}
static ISecureRandom GetMaster()
{
return master;
}
virtual vector<uint8_t> GenerateSeed(const int32_t length);
virtual void SetSeed(vector<uint8_t> &seed);
virtual void SetSeed(const int64_t seed);
virtual void NextBytes(vector<uint8_t> &buf);
virtual void NextBytes(vector<uint8_t> &buf, const int32_t off, const int32_t len);
virtual int32_t NextInt32();
virtual int64_t NextInt64();
virtual double NextDouble();
virtual int32_t Next();
virtual int32_t Next(const int32_t maxValue);
virtual int32_t Next(const int32_t minValue, const int32_t maxValue);
static vector<uint8_t> GetNextBytes(ISecureRandom secureRandom, const int32_t length);
static void Boot();
};
#include <chrono>
using namespace std::chrono;
int64_t SecureRandom::Counter = 0;
double SecureRandom::DoubleScale = 0;
IRandomGenerator SecureRandom::generator = nullptr;
ISecureRandom SecureRandom::master = nullptr;
vector<uint8_t> SecureRandom::GenerateSeed(const int32_t length)
{
return GetNextBytes(master, length);
}
void SecureRandom::SetSeed(vector<uint8_t> &seed)
{
generator.get()->AddSeedMaterial(seed);
}
void SecureRandom::SetSeed(const int64_t seed)
{
generator.get()->AddSeedMaterial(seed);
}
void SecureRandom::NextBytes(vector<uint8_t> &buf)
{
generator.get()->NextBytes(buf);
}
void SecureRandom::NextBytes(vector<uint8_t> &buf, const int32_t off, const int32_t len)
{
generator.get()->NextBytes(buf, off, len);
}
int32_t SecureRandom::NextInt32()
{
uint32_t tempRes;
vector<uint8_t> bytes(4);
NextBytes(bytes);
tempRes = bytes[0];
tempRes = tempRes << 8;
tempRes = tempRes | bytes[1];
tempRes = tempRes << 8;
tempRes = tempRes | bytes[2];
tempRes = tempRes << 8;
tempRes = tempRes | bytes[3];
return int32_t(tempRes);
}
int64_t SecureRandom::NextInt64()
{
return (int64_t(uint32_t(NextInt32())) << 32) | (int64_t(uint32_t(NextInt32())));
}
double SecureRandom::NextDouble()
{
return uint64_t(NextInt64()) / DoubleScale;
}
int64_t SecureRandom::NextCounterValue()
{
uint32_t LCounter;
LCounter = uint32_t(Counter);
int64_t result = LCounter; // InterLockedIncrement(LCounter);
Counter = int64_t(LCounter);
return result;
}
int32_t SecureRandom::Next()
{
return NextInt32() & INT32_MAX;
}
int32_t SecureRandom::Next(const int32_t maxValue)
{
int32_t bits;
if (maxValue < 2)
{
if (maxValue < 0)
throw out_of_range(CannotBeNegative);
return 0;
}
// Test whether maxValue is a power of 2
if ((maxValue & (maxValue - 1)) == 0)
{
bits = NextInt32() & INT32_MAX;
return int32_t(Bits::Asr64((int64_t(bits) * maxValue), 31));
}
int32_t result;
do
{
bits = NextInt32() & INT32_MAX;
result = bits % maxValue;
// Ignore results near overflow
} while (((bits - (result + (maxValue - 1))) < 0));
return result;
}
int32_t SecureRandom::Next(const int32_t minValue, const int32_t maxValue)
{
int32_t diff, i;
if (maxValue <= minValue)
{
if (maxValue == minValue) return minValue;
throw invalid_argument(InvalidMaxValue);
}
diff = maxValue - minValue;
if (diff > 0) return minValue + Next(diff);
while (true)
{
i = NextInt32();
if ((i >= minValue) && (i < maxValue)) return i;
}
return 0; // to make FixInsight Happy :)
}
vector<uint8_t> SecureRandom::GetNextBytes(ISecureRandom secureRandom, const int32_t length)
{
vector<uint8_t> result(length);
secureRandom.get()->NextBytes(result);
return result;
}
void SecureRandom::Boot()
{
auto now = high_resolution_clock::now();
nanoseconds nn = duration_cast<nanoseconds>(now.time_since_epoch());
Counter = nn.count();
if (master == nullptr)
{
master = make_shared<SecureRandom>(make_shared<CryptoApiRandomGenerator>());
}
DoubleScale = pow(2.0, 64.0);
}
#include <memory>
#include <vector>
#include <string>
#include <sstream>
#include <iostream>
#include <fstream>
//#include "../Interfaces/ISecureRandom.h"
using namespace std;
class BigInteger
{
private: