-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy pathBigInteger.cs
1898 lines (1631 loc) · 64 KB
/
BigInteger.cs
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
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
/*=============================================================================
**
** Struct: BigInteger
**
** Purpose: Represents an arbitrary precision integer.
**
=============================================================================*/
using System;
using System.Diagnostics.Contracts;
using System.Collections.Generic;
using System.Globalization;
using System.Numerics;
using System.Text;
using Conditional = System.Diagnostics.ConditionalAttribute;
namespace System.Numerics
{
#if !SILVERLIGHT
[Serializable]
#endif // !SILVERLIGHT
public struct BigInteger : IFormattable, IComparable, IComparable<BigInteger>, IEquatable<BigInteger>
{
// ---- SECTION: members supporting exposed properties -------------*
#region members supporting exposed properties
private const int knMaskHighBit = int.MinValue;
private const uint kuMaskHighBit = unchecked((uint)int.MinValue);
private const int kcbitUint = 32;
private const int kcbitUlong = 64;
private const int DecimalScaleFactorMask = 0x00FF0000;
private const int DecimalSignMask = unchecked((int)0x80000000);
// For values int.MinValue < n <= int.MaxValue, the value is stored in sign
// and _bits is null. For all other values, sign is +1 or -1 and the bits are in _bits
internal int _sign;
internal uint[] _bits;
// We have to make a choice of how to represent int.MinValue. This is the one
// value that fits in an int, but whose negation does not fit in an int.
// We choose to use a large representation, so we're symmetric with respect to negation.
private static readonly BigInteger s_bnMinInt = new BigInteger(-1, new uint[] { kuMaskHighBit });
private static readonly BigInteger s_bnOneInt = new BigInteger(1);
private static readonly BigInteger s_bnZeroInt = new BigInteger(0);
private static readonly BigInteger s_bnMinusOneInt = new BigInteger(-1);
#if CONTRACTS_FULL
[ContractInvariantMethod]
private void ObjectInvariant()
{
Contract.Invariant((_bits == null) ? _sign > Int32.MinValue :
((_sign == 1 || _sign == -1) && Length(_bits) > 0));
Contract.Invariant(_bits == null || Length(_bits) > 1 || _bits[0] >= kuMaskHighBit
, "One element array stores integers whose absolute value is between 0x80000000 and 0xFFFFFFFF");
}
#endif
[Conditional("DEBUG")]
private void AssertValid()
{
if (_bits != null)
{
Contract.Assert(_sign == 1 || _sign == -1 /*, "_sign must be +1 or -1 when _bits is non-null"*/);
Contract.Assert(Length(_bits) > 0 /*, "_bits must contain at least 1 element or be null"*/);
if (Length(_bits) == 1)
Contract.Assert(_bits[0] >= kuMaskHighBit /*, "Wasted space _bits[0] could have been packed into _sign"*/);
}
else
Contract.Assert(_sign > int.MinValue /*, "Int32.MinValue should not be stored in the _sign field"*/);
}
#endregion members supporting exposed properties
// ---- SECTION: public properties --------------*
#region public properties
public static BigInteger Zero
{
get { return s_bnZeroInt; }
}
public static BigInteger One
{
get { return s_bnOneInt; }
}
public static BigInteger MinusOne
{
get { return s_bnMinusOneInt; }
}
public bool IsPowerOfTwo
{
get
{
AssertValid();
if (_bits == null)
return (_sign & (_sign - 1)) == 0 && _sign != 0;
if (_sign != 1)
return false;
int iu = Length(_bits) - 1;
if ((_bits[iu] & (_bits[iu] - 1)) != 0)
return false;
while (--iu >= 0)
{
if (_bits[iu] != 0)
return false;
}
return true;
}
}
public bool IsZero { get { AssertValid(); return _sign == 0; } }
public bool IsOne { get { AssertValid(); return _sign == 1 && _bits == null; } }
public bool IsEven { get { AssertValid(); return _bits == null ? (_sign & 1) == 0 : (_bits[0] & 1) == 0; } }
public int Sign
{
get { AssertValid(); return (_sign >> (kcbitUint - 1)) - (-_sign >> (kcbitUint - 1)); }
}
#endregion public properties
// ---- SECTION: public instance methods --------------*
#region public instance methods
public override bool Equals(object obj)
{
AssertValid();
if (!(obj is BigInteger))
return false;
return Equals((BigInteger)obj);
}
public override int GetHashCode()
{
AssertValid();
if (_bits == null)
return _sign;
int hash = _sign;
for (int iv = Length(_bits); --iv >= 0; )
hash = NumericsHelpers.CombineHash(hash, (int)_bits[iv]);
return hash;
}
public bool Equals(Int64 other)
{
AssertValid();
if (_bits == null)
return _sign == other;
int cu;
if ((_sign ^ other) < 0 || (cu = Length(_bits)) > 2)
return false;
ulong uu = other < 0 ? (ulong)-other : (ulong)other;
if (cu == 1)
return _bits[0] == uu;
return NumericsHelpers.MakeUlong(_bits[1], _bits[0]) == uu;
}
[CLSCompliant(false)]
public bool Equals(UInt64 other)
{
AssertValid();
if (_sign < 0)
return false;
if (_bits == null)
return (ulong)_sign == other;
int cu = Length(_bits);
if (cu > 2)
return false;
if (cu == 1)
return _bits[0] == other;
return NumericsHelpers.MakeUlong(_bits[1], _bits[0]) == other;
}
public bool Equals(BigInteger other)
{
AssertValid();
other.AssertValid();
if (_sign != other._sign)
return false;
if (_bits == other._bits)
// _sign == other._sign && _bits == null && other._bits == null
return true;
if (_bits == null || other._bits == null)
return false;
int cu = Length(_bits);
if (cu != Length(other._bits))
return false;
int cuDiff = GetDiffLength(_bits, other._bits, cu);
return cuDiff == 0;
}
public int CompareTo(Int64 other)
{
AssertValid();
if (_bits == null)
return ((long)_sign).CompareTo(other);
int cu;
if ((_sign ^ other) < 0 || (cu = Length(_bits)) > 2)
return _sign;
ulong uu = other < 0 ? (ulong)-other : (ulong)other;
ulong uuTmp = cu == 2 ? NumericsHelpers.MakeUlong(_bits[1], _bits[0]) : _bits[0];
return _sign * uuTmp.CompareTo(uu);
}
[CLSCompliant(false)]
public int CompareTo(UInt64 other)
{
AssertValid();
if (_sign < 0)
return -1;
if (_bits == null)
return ((ulong)_sign).CompareTo(other);
int cu = Length(_bits);
if (cu > 2)
return +1;
ulong uuTmp = cu == 2 ? NumericsHelpers.MakeUlong(_bits[1], _bits[0]) : _bits[0];
return uuTmp.CompareTo(other);
}
public int CompareTo(BigInteger other)
{
AssertValid();
other.AssertValid();
if ((_sign ^ other._sign) < 0)
{
// Different signs, so the comparison is easy.
return _sign < 0 ? -1 : +1;
}
// Same signs
if (_bits == null)
{
if (other._bits == null)
return _sign < other._sign ? -1 : _sign > other._sign ? +1 : 0;
return -other._sign;
}
int cuThis, cuOther;
if (other._bits == null || (cuThis = Length(_bits)) > (cuOther = Length(other._bits)))
return _sign;
if (cuThis < cuOther)
return -_sign;
int cuDiff = GetDiffLength(_bits, other._bits, cuThis);
if (cuDiff == 0)
return 0;
return _bits[cuDiff - 1] < other._bits[cuDiff - 1] ? -_sign : _sign;
}
public int CompareTo(Object obj)
{
if (obj == null)
return 1;
if (!(obj is BigInteger))
throw new ArgumentException(SR.GetString(SR.Argument_MustBeBigInt));
return this.CompareTo((BigInteger)obj);
}
// Return the value of this BigInteger as a little-endian twos-complement
// byte array, using the fewest number of bytes possible. If the value is zero,
// return an array of one byte whose element is 0x00.
public byte[] ToByteArray() {
if (_bits == null && _sign == 0)
return new byte[] { 0 };
// We could probably make this more efficient by eliminating one of the passes.
// The current code does one pass for uint array -> byte array conversion,
// and then another pass to remove unneeded bytes at the top of the array.
uint[] dwords;
byte highByte;
if (_bits == null) {
dwords = new uint[] { (uint)_sign };
highByte = (byte)((_sign < 0) ? 0xff : 0x00);
}
else if(_sign == -1) {
dwords = (uint[])_bits.Clone();
NumericsHelpers.DangerousMakeTwosComplement(dwords); // mutates dwords
highByte = 0xff;
} else {
dwords = _bits;
highByte = 0x00;
}
byte[] bytes = new byte[checked(4 * dwords.Length)];
int curByte = 0;
uint dword;
for (int i = 0; i < dwords.Length; i++) {
dword = dwords[i];
for (int j = 0; j < 4; j++) {
bytes[curByte++] = (byte)(dword & 0xff);
dword >>= 8;
}
}
// find highest significant byte
int msb;
for (msb = bytes.Length - 1; msb > 0; msb--) {
if (bytes[msb] != highByte) break;
}
// ensure high bit is 0 if positive, 1 if negative
bool needExtraByte = (bytes[msb] & 0x80) != (highByte & 0x80);
byte[] trimmedBytes = new byte[msb + 1 + (needExtraByte ? 1 : 0)];
Array.Copy(bytes, trimmedBytes, msb + 1);
if (needExtraByte) trimmedBytes[trimmedBytes.Length - 1] = highByte;
return trimmedBytes;
}
// Return the value of this BigInteger as a little-endian twos-complement
// uint array, using the fewest number of uints possible. If the value is zero,
// return an array of one uint whose element is 0.
private UInt32[] ToUInt32Array() {
if (_bits == null && _sign == 0)
return new uint[] { 0 };
uint[] dwords;
uint highDWord;
if (_bits == null) {
dwords = new uint[] { (uint)_sign };
highDWord = (_sign < 0) ? UInt32.MaxValue : 0;
}
else if(_sign == -1) {
dwords = (uint[])_bits.Clone();
NumericsHelpers.DangerousMakeTwosComplement(dwords); // mutates dwords
highDWord = UInt32.MaxValue;
} else {
dwords = _bits;
highDWord = 0;
}
// find highest significant byte
int msb;
for (msb = dwords.Length - 1; msb > 0; msb--) {
if (dwords[msb] != highDWord) break;
}
// ensure high bit is 0 if positive, 1 if negative
bool needExtraByte = (dwords[msb] & 0x80000000) != (highDWord & 0x80000000);
uint[] trimmed = new uint[msb + 1 + (needExtraByte ? 1 : 0)];
Array.Copy(dwords, trimmed, msb + 1);
if (needExtraByte) trimmed[trimmed.Length - 1] = highDWord;
return trimmed;
}
public override String ToString() {
return BigNumber.FormatBigInteger(this, null, NumberFormatInfo.CurrentInfo);
}
public String ToString(IFormatProvider provider) {
return BigNumber.FormatBigInteger(this, null, NumberFormatInfo.GetInstance(provider));
}
public String ToString(String format) {
return BigNumber.FormatBigInteger(this, format, NumberFormatInfo.CurrentInfo);
}
public String ToString(String format, IFormatProvider provider) {
return BigNumber.FormatBigInteger(this, format, NumberFormatInfo.GetInstance(provider));
}
#endregion public instance methods
// -------- SECTION: constructors -----------------*
#region constructors
public BigInteger(int value)
{
if (value == Int32.MinValue)
this = s_bnMinInt;
else {
_sign = value;
_bits = null;
}
AssertValid();
}
[CLSCompliant(false)]
public BigInteger(uint value)
{
if (value <= Int32.MaxValue)
{
_sign = (int)value;
_bits = null;
}
else
{
_sign = +1;
_bits = new uint[1];
_bits[0] = value;
}
AssertValid();
}
public BigInteger(Int64 value)
{
if (Int32.MinValue <= value && value <= Int32.MaxValue)
{
if (value == Int32.MinValue)
this = s_bnMinInt;
else
{
_sign = (int)value;
_bits = null;
}
AssertValid();
return;
}
ulong x = 0;
if (value < 0)
{
x = (ulong)-value;
_sign = -1;
}
else
{
Contract.Assert(value != 0);
x = (ulong)value;
_sign = +1;
}
_bits = new uint[2];
_bits[0] = (uint)x;
_bits[1] = (uint)(x >> kcbitUint);
AssertValid();
}
[CLSCompliant(false)]
public BigInteger(UInt64 value)
{
if (value <= Int32.MaxValue)
{
_sign = (int)value;
_bits = null;
}
else
{
_sign = +1;
_bits = new uint[2];
_bits[0] = (uint)value;
_bits[1] = (uint)(value >> kcbitUint);
}
AssertValid();
}
public BigInteger(Single value)
{
if (Single.IsInfinity(value))
throw new OverflowException(SR.GetString(SR.Overflow_BigIntInfinity));
if (Single.IsNaN(value))
throw new OverflowException(SR.GetString(SR.Overflow_NotANumber));
Contract.EndContractBlock();
_sign = 0;
_bits = null;
SetBitsFromDouble(value);
AssertValid();
}
public BigInteger(Double value)
{
if (Double.IsInfinity(value))
throw new OverflowException(SR.GetString(SR.Overflow_BigIntInfinity));
if (Double.IsNaN(value))
throw new OverflowException(SR.GetString(SR.Overflow_NotANumber));
Contract.EndContractBlock();
_sign = 0;
_bits = null;
SetBitsFromDouble(value);
AssertValid();
}
public BigInteger(Decimal value)
{
// First truncate to get scale to 0 and extract bits
int[] bits = Decimal.GetBits(Decimal.Truncate(value));
Contract.Assert(bits.Length == 4 && (bits[3] & DecimalScaleFactorMask) == 0);
int size = 3;
while (size > 0 && bits[size - 1] == 0)
size--;
if (size == 0) {
this = s_bnZeroInt;
}
else if (size == 1 && bits[0] > 0) {
// bits[0] is the absolute value of this decimal
// if bits[0] < 0 then it is too large to be packed into _sign
_sign = bits[0];
_sign *= ((bits[3] & DecimalSignMask) != 0) ? -1 : +1;
_bits = null;
}
else {
_bits = new UInt32[size];
_bits[0] = (UInt32)bits[0];
if (size > 1)
_bits[1] = (UInt32)bits[1];
if (size > 2)
_bits[2] = (UInt32)bits[2];
_sign = ((bits[3] & DecimalSignMask) != 0) ? -1 : +1;
}
AssertValid();
}
[CLSCompliant(false)]
//
// Create a BigInteger from a little-endian twos-complement byte array
//
public BigInteger(Byte[] value)
{
if (value == null)
throw new ArgumentNullException("value");
Contract.EndContractBlock();
int byteCount = value.Length;
bool isNegative = byteCount > 0 && ((value[byteCount - 1] & 0x80) == 0x80);
// Try to conserve space as much as possible by checking for wasted leading byte[] entries
while (byteCount > 0 && value[byteCount-1] == 0) byteCount--;
if (byteCount == 0)
{
// BigInteger.Zero
_sign = 0;
_bits = null;
AssertValid();
return;
}
if (byteCount <= 4)
{
if (isNegative)
_sign = unchecked((int)0xffffffff);
else
_sign = 0;
for (int i = byteCount - 1; i >= 0; i--)
{
_sign <<= 8;
_sign |= value[i];
}
_bits = null;
if (_sign < 0 && !isNegative)
{
// int32 overflow
// example: Int64 value 2362232011 (0xCB, 0xCC, 0xCC, 0x8C, 0x0)
// can be naively packed into 4 bytes (due to the leading 0x0)
// it overflows into the int32 sign bit
_bits = new uint[1];
_bits[0] = (uint)_sign;
_sign = +1;
}
if (_sign == Int32.MinValue)
this = s_bnMinInt;
}
else
{
int unalignedBytes = byteCount % 4;
int dwordCount = byteCount / 4 + (unalignedBytes == 0 ? 0 : 1);
bool isZero = true;
uint[] val = new uint[dwordCount];
// Copy all dwords, except but don't do the last one if it's not a full four bytes
int curDword, curByte, byteInDword;
curByte = 3;
for (curDword = 0; curDword < dwordCount - (unalignedBytes == 0 ? 0 : 1); curDword++) {
byteInDword = 0;
while (byteInDword < 4) {
if (value[curByte] != 0x00) isZero = false;
val[curDword] <<= 8;
val[curDword] |= value[curByte];
curByte--;
byteInDword++;
}
curByte += 8;
}
// Copy the last dword specially if it's not aligned
if (unalignedBytes != 0) {
if (isNegative) val[dwordCount - 1] = 0xffffffff;
for (curByte = byteCount - 1; curByte >= byteCount - unalignedBytes; curByte--) {
if (value[curByte] != 0x00) isZero = false;
val[curDword] <<= 8;
val[curDword] |= value[curByte];
}
}
if (isZero) {
this = s_bnZeroInt;
}
else if (isNegative) {
NumericsHelpers.DangerousMakeTwosComplement(val); // mutates val
// pack _bits to remove any wasted space after the twos complement
int len = val.Length;
while (len > 0 && val[len - 1] == 0)
len--;
if (len == 1 && ((int)(val[0])) > 0) {
if (val[0] == 1 /* abs(-1) */) {
this = s_bnMinusOneInt;
}
else if (val[0] == kuMaskHighBit /* abs(Int32.MinValue) */) {
this = s_bnMinInt;
}
else {
_sign = (-1) * ((int)val[0]);
_bits = null;
}
}
else if (len != val.Length) {
_sign = -1;
_bits = new uint[len];
Array.Copy(val, _bits, len);
}
else {
_sign = -1;
_bits = val;
}
}
else
{
_sign = +1;
_bits = val;
}
}
AssertValid();
}
internal BigInteger(int n, uint[] rgu)
{
_sign = n;
_bits = rgu;
AssertValid();
}
//
// BigInteger(uint[] value, bool negative)
//
// Constructor used during bit manipulation and arithmetic
//
// The uint[] value is expected to be the absolute value of the number
// with the bool negative indicating the Sign of the value.
//
// When possible the uint[] will be packed into _sign to conserve space
//
internal BigInteger(uint[] value, bool negative)
{
if (value == null)
throw new ArgumentNullException("value");
Contract.EndContractBlock();
int len;
// Try to conserve space as much as possible by checking for wasted leading uint[] entries
// sometimes the uint[] has leading zeros from bit manipulation operations & and ^
for(len = value.Length; len > 0 && value[len-1] == 0; len--);
if (len == 0)
this = s_bnZeroInt;
// values like (Int32.MaxValue+1) are stored as "0x80000000" and as such cannot be packed into _sign
else if (len == 1 && value[0] < kuMaskHighBit)
{
_sign = (negative ? -(int)value[0] : (int)value[0]);
_bits = null;
// Although Int32.MinValue fits in _sign, we represent this case differently for negate
if (_sign == Int32.MinValue)
this = s_bnMinInt;
}
else
{
_sign = negative ? -1 : +1;
_bits = new uint[len];
Array.Copy(value, _bits, len);
}
AssertValid();
}
//
// Create a BigInteger from a little-endian twos-complement UInt32 array
// When possible, value is assigned directly to this._bits without an array copy
// so use this ctor with care
//
private BigInteger(uint[] value)
{
if (value == null)
throw new ArgumentNullException("value");
int dwordCount = value.Length;
bool isNegative = dwordCount > 0 && ((value[dwordCount - 1] & 0x80000000) == 0x80000000);
// Try to conserve space as much as possible by checking for wasted leading uint[] entries
while (dwordCount > 0 && value[dwordCount-1] == 0) dwordCount--;
if (dwordCount == 0)
{
// BigInteger.Zero
this = s_bnZeroInt;
AssertValid();
return;
}
if (dwordCount == 1)
{
if ((int)value[0] < 0 && !isNegative) {
_bits = new uint[1];
_bits[0] = value[0];
_sign = +1;
}
// handle the special cases where the BigInteger likely fits into _sign
else if (Int32.MinValue == (int)value[0]) {
this = s_bnMinInt;
}
else {
_sign = (int)value[0];
_bits = null;
}
AssertValid();
return;
}
if (!isNegative) {
// handle the simple postive value cases where the input is already in sign magnitude
if (dwordCount != value.Length) {
_sign = +1;
_bits = new uint[dwordCount];
Array.Copy(value, _bits, dwordCount);
}
// no trimming is possible. Assign value directly to _bits.
else {
_sign = +1;
_bits = value;
}
AssertValid();
return;
}
// finally handle the more complex cases where we must transform the input into sign magnitude
NumericsHelpers.DangerousMakeTwosComplement(value); // mutates val
// pack _bits to remove any wasted space after the twos complement
int len = value.Length;
while (len > 0 && value[len - 1] == 0) len--;
// the number is represented by a single dword
if (len == 1 && ((int)(value[0])) > 0) {
if (value[0] == 1 /* abs(-1) */) {
this = s_bnMinusOneInt;
}
else if (value[0] == kuMaskHighBit /* abs(Int32.MinValue) */) {
this = s_bnMinInt;
}
else {
_sign = (-1) * ((int)value[0]);
_bits = null;
}
}
// the number is represented by multiple dwords
// trim off any wasted uint values when possible
else if (len != value.Length) {
_sign = -1;
_bits = new uint[len];
Array.Copy(value, _bits, len);
}
// no trimming is possible. Assign value directly to _bits.
else {
_sign = -1;
_bits = value;
}
AssertValid();
return;
}
#endregion constructors
// -------- SECTION: public static methods -----------------*
#region public static methods
#if !SILVERLIGHT || FEATURE_NETCORE
public static BigInteger Parse(String value) {
return BigNumber.ParseBigInteger(value, NumberStyles.Integer, NumberFormatInfo.CurrentInfo);
}
public static BigInteger Parse(String value, NumberStyles style) {
return BigNumber.ParseBigInteger(value, style, NumberFormatInfo.CurrentInfo);
}
public static BigInteger Parse(String value, IFormatProvider provider) {
return BigNumber.ParseBigInteger(value, NumberStyles.Integer, NumberFormatInfo.GetInstance(provider));
}
public static BigInteger Parse(String value, NumberStyles style, IFormatProvider provider) {
return BigNumber.ParseBigInteger(value, style, NumberFormatInfo.GetInstance(provider));
}
public static Boolean TryParse(String value, out BigInteger result) {
return BigNumber.TryParseBigInteger(value, NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out result);
}
public static Boolean TryParse(String value, NumberStyles style, IFormatProvider provider, out BigInteger result) {
return BigNumber.TryParseBigInteger(value, style, NumberFormatInfo.GetInstance(provider), out result);
}
#endif //!SILVERLIGHT || FEATURE_NETCORE
public static Int32 Compare(BigInteger left, BigInteger right)
{
return left.CompareTo(right);
}
public static BigInteger Abs(BigInteger value)
{
return (value >= BigInteger.Zero) ? value : -value;
}
public static BigInteger Add(BigInteger left, BigInteger right)
{
return left + right;
}
public static BigInteger Subtract(BigInteger left, BigInteger right)
{
return left - right;
}
public static BigInteger Multiply(BigInteger left, BigInteger right)
{
return left * right;
}
public static BigInteger Divide(BigInteger dividend, BigInteger divisor)
{
return dividend / divisor;
}
public static BigInteger Remainder(BigInteger dividend, BigInteger divisor)
{
return dividend % divisor;
}
public static BigInteger DivRem(BigInteger dividend, BigInteger divisor, out BigInteger remainder)
{
dividend.AssertValid();
divisor.AssertValid();
int signNum = +1;
int signDen = +1;
BigIntegerBuilder regNum = new BigIntegerBuilder(dividend, ref signNum);
BigIntegerBuilder regDen = new BigIntegerBuilder(divisor, ref signDen);
BigIntegerBuilder regQuo = new BigIntegerBuilder();
// regNum and regQuo are overwritten with the remainder and quotient, respectively
regNum.ModDiv(ref regDen, ref regQuo);
remainder = regNum.GetInteger(signNum);
return regQuo.GetInteger(signNum * signDen);
}
public static BigInteger Negate(BigInteger value)
{
return -value;
}
// Returns the natural (base e) logarithm of a specified number.
public static Double Log(BigInteger value)
{
return BigInteger.Log(value, Math.E);
}
public static Double Log(BigInteger value, Double baseValue)
{
if (value._sign < 0 || baseValue == 1.0D)
return Double.NaN;
if (baseValue == Double.PositiveInfinity)
return value.IsOne ? 0.0D : Double.NaN;
if (baseValue == 0.0D && !value.IsOne)
return Double.NaN;
if (value._bits == null)
return Math.Log((double)value._sign, baseValue);
Double c = 0, d = 0.5D;
const Double log2 = 0.69314718055994529D;
int uintLength = Length(value._bits);
int topbits = BitLengthOfUInt(value._bits[uintLength - 1]);
int bitlen = (uintLength - 1) * kcbitUint + topbits;
uint indbit = (uint)(1 << (topbits - 1));
for(int index = uintLength -1; index >= 0; --index)
{
while (indbit != 0)
{
if ((value._bits[index] & indbit) != 0)
c += d;
d *= 0.5;
indbit >>= 1;
}
indbit = 0x80000000;
}
return (Math.Log(c) + log2 * bitlen) / Math.Log(baseValue);
}
public static Double Log10(BigInteger value)
{
return BigInteger.Log(value, 10);
}
public static BigInteger GreatestCommonDivisor(BigInteger left, BigInteger right)
{
left.AssertValid();
right.AssertValid();
// gcd(0, 0) = 0
// gcd(a, 0) = |a|, for a != 0, since any number is a divisor of 0, and the greatest divisor of a is |a|
if (left._sign == 0) return BigInteger.Abs(right);
if (right._sign == 0) return BigInteger.Abs(left);
BigIntegerBuilder reg1 = new BigIntegerBuilder(left);
BigIntegerBuilder reg2 = new BigIntegerBuilder(right);
BigIntegerBuilder.GCD(ref reg1, ref reg2);
return reg1.GetInteger(+1);
}
public static BigInteger Max(BigInteger left, BigInteger right)
{
if (left.CompareTo(right) < 0)
return right;
return left;
}
public static BigInteger Min(BigInteger left, BigInteger right)
{
if (left.CompareTo(right) <= 0)
return left;
return right;
}
private static void ModPowUpdateResult(ref BigIntegerBuilder regRes, ref BigIntegerBuilder regVal, ref BigIntegerBuilder regMod, ref BigIntegerBuilder regTmp)
{
NumericsHelpers.Swap(ref regRes, ref regTmp);
regRes.Mul(ref regTmp, ref regVal); // result = result * value;
regRes.Mod(ref regMod); // result = result % modulus;
}
private static void ModPowSquareModValue(ref BigIntegerBuilder regVal, ref BigIntegerBuilder regMod, ref BigIntegerBuilder regTmp)
{
NumericsHelpers.Swap(ref regVal, ref regTmp);
regVal.Mul(ref regTmp, ref regTmp); // value = value * value;
regVal.Mod(ref regMod); // value = value % modulus;
}
private static void ModPowInner(uint exp, ref BigIntegerBuilder regRes, ref BigIntegerBuilder regVal, ref BigIntegerBuilder regMod, ref BigIntegerBuilder regTmp)
{
while (exp != 0) // !(Exponent.IsZero)
{
if ((exp & 1) == 1) // !(Exponent.IsEven)
ModPowUpdateResult(ref regRes, ref regVal, ref regMod, ref regTmp);
if (exp == 1) // Exponent.IsOne - we can exit early
break;
ModPowSquareModValue(ref regVal, ref regMod, ref regTmp);
exp >>= 1;
}
}
private static void ModPowInner32(uint exp, ref BigIntegerBuilder regRes, ref BigIntegerBuilder regVal, ref BigIntegerBuilder regMod, ref BigIntegerBuilder regTmp)
{
for (int i = 0; i < 32; i++)
{