/
BigInteger.cs
5337 lines (4521 loc) · 187 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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Buffers;
using System.Buffers.Binary;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace System.Numerics
{
[Serializable]
[TypeForwardedFrom("System.Numerics, Version=4.0.0.0, PublicKeyToken=b77a5c561934e089")]
[DebuggerDisplay("{DebuggerDisplay,nq}")]
public readonly struct BigInteger
: ISpanFormattable,
IComparable,
IComparable<BigInteger>,
IEquatable<BigInteger>,
IBinaryInteger<BigInteger>,
ISignedNumber<BigInteger>
{
private const uint kuMaskHighBit = unchecked((uint)int.MinValue);
private const int kcbitUint = 32;
private const int kcbitUlong = 64;
private const int DecimalScaleFactorMask = 0x00FF0000;
// 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 readonly int _sign; // Do not rename (binary serialization)
internal readonly uint[]? _bits; // Do not rename (binary serialization)
// 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);
public BigInteger(int value)
{
if (value == int.MinValue)
this = s_bnMinInt;
else
{
_sign = value;
_bits = null;
}
AssertValid();
}
[CLSCompliant(false)]
public BigInteger(uint value)
{
if (value <= int.MaxValue)
{
_sign = (int)value;
_bits = null;
}
else
{
_sign = +1;
_bits = new uint[1];
_bits[0] = value;
}
AssertValid();
}
public BigInteger(long value)
{
if (int.MinValue < value && value <= int.MaxValue)
{
_sign = (int)value;
_bits = null;
}
else if (value == int.MinValue)
{
this = s_bnMinInt;
}
else
{
ulong x;
if (value < 0)
{
x = unchecked((ulong)-value);
_sign = -1;
}
else
{
x = (ulong)value;
_sign = +1;
}
if (x <= uint.MaxValue)
{
_bits = new uint[1];
_bits[0] = (uint)x;
}
else
{
_bits = new uint[2];
_bits[0] = unchecked((uint)x);
_bits[1] = (uint)(x >> kcbitUint);
}
}
AssertValid();
}
[CLSCompliant(false)]
public BigInteger(ulong value)
{
if (value <= int.MaxValue)
{
_sign = (int)value;
_bits = null;
}
else if (value <= uint.MaxValue)
{
_sign = +1;
_bits = new uint[1];
_bits[0] = (uint)value;
}
else
{
_sign = +1;
_bits = new uint[2];
_bits[0] = unchecked((uint)value);
_bits[1] = (uint)(value >> kcbitUint);
}
AssertValid();
}
public BigInteger(float value) : this((double)value)
{
}
public BigInteger(double value)
{
if (!double.IsFinite(value))
{
if (double.IsInfinity(value))
{
throw new OverflowException(SR.Overflow_BigIntInfinity);
}
else // NaN
{
throw new OverflowException(SR.Overflow_NotANumber);
}
}
_sign = 0;
_bits = null;
int sign, exp;
ulong man;
NumericsHelpers.GetDoubleParts(value, out sign, out exp, out man, out _);
Debug.Assert(sign == +1 || sign == -1);
if (man == 0)
{
this = Zero;
return;
}
Debug.Assert(man < (1UL << 53));
Debug.Assert(exp <= 0 || man >= (1UL << 52));
if (exp <= 0)
{
if (exp <= -kcbitUlong)
{
this = Zero;
return;
}
this = man >> -exp;
if (sign < 0)
_sign = -_sign;
}
else if (exp <= 11)
{
this = man << exp;
if (sign < 0)
_sign = -_sign;
}
else
{
// Overflow into at least 3 uints.
// Move the leading 1 to the high bit.
man <<= 11;
exp -= 11;
// Compute cu and cbit so that exp == 32 * cu - cbit and 0 <= cbit < 32.
int cu = (exp - 1) / kcbitUint + 1;
int cbit = cu * kcbitUint - exp;
Debug.Assert(0 <= cbit && cbit < kcbitUint);
Debug.Assert(cu >= 1);
// Populate the uints.
_bits = new uint[cu + 2];
_bits[cu + 1] = (uint)(man >> (cbit + kcbitUint));
_bits[cu] = unchecked((uint)(man >> cbit));
if (cbit > 0)
_bits[cu - 1] = unchecked((uint)man) << (kcbitUint - cbit);
_sign = sign;
}
AssertValid();
}
public BigInteger(decimal value)
{
// First truncate to get scale to 0 and extract bits
Span<int> bits = stackalloc int[4];
decimal.GetBits(decimal.Truncate(value), bits);
Debug.Assert(bits.Length == 4 && (bits[3] & DecimalScaleFactorMask) == 0);
const int signMask = unchecked((int)kuMaskHighBit);
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] & signMask) != 0) ? -1 : +1;
_bits = null;
}
else
{
_bits = new uint[size];
unchecked
{
_bits[0] = (uint)bits[0];
if (size > 1)
_bits[1] = (uint)bits[1];
if (size > 2)
_bits[2] = (uint)bits[2];
}
_sign = ((bits[3] & signMask) != 0) ? -1 : +1;
}
AssertValid();
}
/// <summary>
/// Creates a BigInteger from a little-endian twos-complement byte array.
/// </summary>
/// <param name="value"></param>
[CLSCompliant(false)]
public BigInteger(byte[] value) :
this(new ReadOnlySpan<byte>(value ?? throw new ArgumentNullException(nameof(value))))
{
}
public BigInteger(ReadOnlySpan<byte> value, bool isUnsigned = false, bool isBigEndian = false)
{
int byteCount = value.Length;
bool isNegative;
if (byteCount > 0)
{
byte mostSignificantByte = isBigEndian ? value[0] : value[byteCount - 1];
isNegative = (mostSignificantByte & 0x80) != 0 && !isUnsigned;
if (mostSignificantByte == 0)
{
// Try to conserve space as much as possible by checking for wasted leading byte[] entries
if (isBigEndian)
{
int offset = 1;
while (offset < byteCount && value[offset] == 0)
{
offset++;
}
value = value.Slice(offset);
byteCount = value.Length;
}
else
{
byteCount -= 2;
while (byteCount >= 0 && value[byteCount] == 0)
{
byteCount--;
}
byteCount++;
}
}
}
else
{
isNegative = false;
}
if (byteCount == 0)
{
// BigInteger.Zero
_sign = 0;
_bits = null;
AssertValid();
return;
}
if (byteCount <= 4)
{
_sign = isNegative ? unchecked((int)0xffffffff) : 0;
if (isBigEndian)
{
for (int i = 0; i < byteCount; i++)
{
_sign = (_sign << 8) | value[i];
}
}
else
{
for (int i = byteCount - 1; i >= 0; i--)
{
_sign = (_sign << 8) | 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] { unchecked((uint)_sign) };
_sign = +1;
}
if (_sign == int.MinValue)
{
this = s_bnMinInt;
}
}
else
{
int unalignedBytes = byteCount % 4;
int dwordCount = byteCount / 4 + (unalignedBytes == 0 ? 0 : 1);
uint[] val = new uint[dwordCount];
int byteCountMinus1 = byteCount - 1;
// Copy all dwords, except don't do the last one if it's not a full four bytes
int curDword, curByte;
if (isBigEndian)
{
curByte = byteCount - sizeof(int);
for (curDword = 0; curDword < dwordCount - (unalignedBytes == 0 ? 0 : 1); curDword++)
{
for (int byteInDword = 0; byteInDword < 4; byteInDword++)
{
byte curByteValue = value[curByte];
val[curDword] = (val[curDword] << 8) | curByteValue;
curByte++;
}
curByte -= 8;
}
}
else
{
curByte = sizeof(int) - 1;
for (curDword = 0; curDword < dwordCount - (unalignedBytes == 0 ? 0 : 1); curDword++)
{
for (int byteInDword = 0; byteInDword < 4; byteInDword++)
{
byte curByteValue = value[curByte];
val[curDword] = (val[curDword] << 8) | curByteValue;
curByte--;
}
curByte += 8;
}
}
// Copy the last dword specially if it's not aligned
if (unalignedBytes != 0)
{
if (isNegative)
{
val[dwordCount - 1] = 0xffffffff;
}
if (isBigEndian)
{
for (curByte = 0; curByte < unalignedBytes; curByte++)
{
byte curByteValue = value[curByte];
val[curDword] = (val[curDword] << 8) | curByteValue;
}
}
else
{
for (curByte = byteCountMinus1; curByte >= byteCount - unalignedBytes; curByte--)
{
byte curByteValue = value[curByte];
val[curDword] = (val[curDword] << 8) | curByteValue;
}
}
}
if (isNegative)
{
NumericsHelpers.DangerousMakeTwosComplement(val); // Mutates val
// Pack _bits to remove any wasted space after the twos complement
int len = val.Length - 1;
while (len >= 0 && val[len] == 0) len--;
len++;
if (len == 1)
{
switch (val[0])
{
case 1: // abs(-1)
this = s_bnMinusOneInt;
return;
case kuMaskHighBit: // abs(Int32.MinValue)
this = s_bnMinInt;
return;
default:
if (unchecked((int)val[0]) > 0)
{
_sign = (-1) * ((int)val[0]);
_bits = null;
AssertValid();
return;
}
break;
}
}
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)
{
if ((rgu is not null) && (rgu.Length > MaxLength))
{
ThrowHelper.ThrowOverflowException();
}
_sign = n;
_bits = rgu;
AssertValid();
}
/// <summary>
/// Constructor used during bit manipulation and arithmetic.
/// When possible the value will be packed into _sign to conserve space.
/// </summary>
/// <param name="value">The absolute value of the number</param>
/// <param name="negative">The bool indicating the sign of the value.</param>
private BigInteger(ReadOnlySpan<uint> value, bool negative)
{
if (value.Length > MaxLength)
{
ThrowHelper.ThrowOverflowException();
}
int len;
// Try to conserve space as much as possible by checking for wasted leading span entries
// sometimes the span 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;
}
else if (len == 1 && value[0] < kuMaskHighBit)
{
// Values like (Int32.MaxValue+1) are stored as "0x80000000" and as such cannot be packed into _sign
_sign = negative ? -(int)value[0] : (int)value[0];
_bits = null;
if (_sign == int.MinValue)
{
// Although Int32.MinValue fits in _sign, we represent this case differently for negate
this = s_bnMinInt;
}
}
else
{
_sign = negative ? -1 : +1;
_bits = value.Slice(0, len).ToArray();
}
AssertValid();
}
/// <summary>
/// Create a BigInteger from a little-endian twos-complement UInt32 span.
/// </summary>
/// <param name="value"></param>
private BigInteger(Span<uint> value)
{
if (value.Length > MaxLength)
{
ThrowHelper.ThrowOverflowException();
}
int dwordCount = value.Length;
bool isNegative = dwordCount > 0 && ((value[dwordCount - 1] & kuMaskHighBit) == kuMaskHighBit);
// Try to conserve space as much as possible by checking for wasted leading span entries
while (dwordCount > 0 && value[dwordCount - 1] == 0) dwordCount--;
if (dwordCount == 0)
{
// BigInteger.Zero
this = s_bnZeroInt;
AssertValid();
return;
}
if (dwordCount == 1)
{
if (unchecked((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 (int.MinValue == unchecked((int)value[0]))
{
this = s_bnMinInt;
}
else
{
_sign = unchecked((int)value[0]);
_bits = null;
}
AssertValid();
return;
}
if (!isNegative)
{
// Handle the simple positive value cases where the input is already in sign magnitude
_sign = +1;
value = value.Slice(0, dwordCount);
_bits = value.ToArray();
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 && unchecked((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;
}
}
else
{
_sign = -1;
_bits = value.Slice(0, len).ToArray();
}
AssertValid();
return;
}
public static BigInteger Zero { get { return s_bnZeroInt; } }
public static BigInteger One { get { return s_bnOneInt; } }
public static BigInteger MinusOne { get { return s_bnMinusOneInt; } }
internal static int MaxLength => Array.MaxLength / sizeof(uint);
public bool IsPowerOfTwo
{
get
{
AssertValid();
if (_bits == null)
return BitOperations.IsPow2(_sign);
if (_sign != 1)
return false;
int iu = _bits.Length - 1;
if (!BitOperations.IsPow2(_bits[iu]))
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)); }
}
public static BigInteger Parse(string value)
{
return Parse(value, NumberStyles.Integer);
}
public static BigInteger Parse(string value, NumberStyles style)
{
return Parse(value, style, NumberFormatInfo.CurrentInfo);
}
public static BigInteger Parse(string value, IFormatProvider? provider)
{
return Parse(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 bool TryParse([NotNullWhen(true)] string? value, out BigInteger result)
{
return TryParse(value, NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out result);
}
public static bool TryParse([NotNullWhen(true)] string? value, NumberStyles style, IFormatProvider? provider, out BigInteger result)
{
return BigNumber.TryParseBigInteger(value, style, NumberFormatInfo.GetInstance(provider), out result) == BigNumber.ParsingStatus.OK;
}
public static BigInteger Parse(ReadOnlySpan<char> value, NumberStyles style = NumberStyles.Integer, IFormatProvider? provider = null)
{
return BigNumber.ParseBigInteger(value, style, NumberFormatInfo.GetInstance(provider));
}
public static bool TryParse(ReadOnlySpan<char> value, out BigInteger result)
{
return TryParse(value, NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out result);
}
public static bool TryParse(ReadOnlySpan<char> value, NumberStyles style, IFormatProvider? provider, out BigInteger result)
{
return BigNumber.TryParseBigInteger(value, style, NumberFormatInfo.GetInstance(provider), out result) == BigNumber.ParsingStatus.OK;
}
public static int Compare(BigInteger left, BigInteger right)
{
return left.CompareTo(right);
}
public static BigInteger Abs(BigInteger value)
{
return (value >= 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();
bool trivialDividend = dividend._bits == null;
bool trivialDivisor = divisor._bits == null;
if (trivialDividend && trivialDivisor)
{
BigInteger quotient;
(quotient, remainder) = Math.DivRem(dividend._sign, divisor._sign);
return quotient;
}
if (trivialDividend)
{
// The divisor is non-trivial
// and therefore the bigger one
remainder = dividend;
return s_bnZeroInt;
}
Debug.Assert(dividend._bits != null);
if (trivialDivisor)
{
uint rest;
uint[]? bitsFromPool = null;
int size = dividend._bits.Length;
Span<uint> quotient = ((uint)size <= BigIntegerCalculator.StackAllocThreshold
? stackalloc uint[BigIntegerCalculator.StackAllocThreshold]
: bitsFromPool = ArrayPool<uint>.Shared.Rent(size)).Slice(0, size);
try
{
// may throw DivideByZeroException
BigIntegerCalculator.Divide(dividend._bits, NumericsHelpers.Abs(divisor._sign), quotient, out rest);
remainder = dividend._sign < 0 ? -1 * rest : rest;
return new BigInteger(quotient, (dividend._sign < 0) ^ (divisor._sign < 0));
}
finally
{
if (bitsFromPool != null)
ArrayPool<uint>.Shared.Return(bitsFromPool);
}
}
Debug.Assert(divisor._bits != null);
if (dividend._bits.Length < divisor._bits.Length)
{
remainder = dividend;
return s_bnZeroInt;
}
else
{
uint[]? remainderFromPool = null;
int size = dividend._bits.Length;
Span<uint> rest = ((uint)size <= BigIntegerCalculator.StackAllocThreshold
? stackalloc uint[BigIntegerCalculator.StackAllocThreshold]
: remainderFromPool = ArrayPool<uint>.Shared.Rent(size)).Slice(0, size);
uint[]? quotientFromPool = null;
size = dividend._bits.Length - divisor._bits.Length + 1;
Span<uint> quotient = ((uint)size <= BigIntegerCalculator.StackAllocThreshold
? stackalloc uint[BigIntegerCalculator.StackAllocThreshold]
: quotientFromPool = ArrayPool<uint>.Shared.Rent(size)).Slice(0, size);
BigIntegerCalculator.Divide(dividend._bits, divisor._bits, quotient, rest);
remainder = new BigInteger(rest, dividend._sign < 0);
var result = new BigInteger(quotient, (dividend._sign < 0) ^ (divisor._sign < 0));
if (remainderFromPool != null)
ArrayPool<uint>.Shared.Return(remainderFromPool);
if (quotientFromPool != null)
ArrayPool<uint>.Shared.Return(quotientFromPool);
return result;
}
}
public static BigInteger Negate(BigInteger value)
{
return -value;
}
public static double Log(BigInteger value)
{
return 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(value._sign, baseValue);
ulong h = value._bits[value._bits.Length - 1];
ulong m = value._bits.Length > 1 ? value._bits[value._bits.Length - 2] : 0;
ulong l = value._bits.Length > 2 ? value._bits[value._bits.Length - 3] : 0;
// Measure the exact bit count
int c = BitOperations.LeadingZeroCount((uint)h);
long b = (long)value._bits.Length * 32 - c;
// Extract most significant bits
ulong x = (h << 32 + c) | (m << c) | (l >> 32 - c);
// Let v = value, b = bit count, x = v/2^b-64
// log ( v/2^b-64 * 2^b-64 ) = log ( x ) + log ( 2^b-64 )
return Math.Log(x, baseValue) + (b - 64) / Math.Log(baseValue, 2);
}
public static double Log10(BigInteger value)
{
return Log(value, 10);
}
public static BigInteger GreatestCommonDivisor(BigInteger left, BigInteger right)
{
left.AssertValid();
right.AssertValid();
bool trivialLeft = left._bits == null;
bool trivialRight = right._bits == null;
if (trivialLeft && trivialRight)
{
return BigIntegerCalculator.Gcd(NumericsHelpers.Abs(left._sign), NumericsHelpers.Abs(right._sign));
}
if (trivialLeft)
{
Debug.Assert(right._bits != null);
return left._sign != 0
? BigIntegerCalculator.Gcd(right._bits, NumericsHelpers.Abs(left._sign))
: new BigInteger(right._bits, negative: false);
}
if (trivialRight)
{
Debug.Assert(left._bits != null);
return right._sign != 0
? BigIntegerCalculator.Gcd(left._bits, NumericsHelpers.Abs(right._sign))
: new BigInteger(left._bits, negative: false);
}
Debug.Assert(left._bits != null && right._bits != null);
if (BigIntegerCalculator.Compare(left._bits, right._bits) < 0)
{
return GreatestCommonDivisor(right._bits, left._bits);
}
else
{
return GreatestCommonDivisor(left._bits, right._bits);
}
}
private static BigInteger GreatestCommonDivisor(ReadOnlySpan<uint> leftBits, ReadOnlySpan<uint> rightBits)
{
Debug.Assert(BigIntegerCalculator.Compare(leftBits, rightBits) >= 0);
uint[]? bitsFromPool = null;
BigInteger result;
// Short circuits to spare some allocations...
if (rightBits.Length == 1)
{
uint temp = BigIntegerCalculator.Remainder(leftBits, rightBits[0]);
result = BigIntegerCalculator.Gcd(rightBits[0], temp);
}
else if (rightBits.Length == 2)
{
Span<uint> bits = (leftBits.Length <= BigIntegerCalculator.StackAllocThreshold
? stackalloc uint[BigIntegerCalculator.StackAllocThreshold]
: bitsFromPool = ArrayPool<uint>.Shared.Rent(leftBits.Length)).Slice(0, leftBits.Length);
BigIntegerCalculator.Remainder(leftBits, rightBits, bits);
ulong left = ((ulong)rightBits[1] << 32) | rightBits[0];
ulong right = ((ulong)bits[1] << 32) | bits[0];
result = BigIntegerCalculator.Gcd(left, right);
}
else
{
Span<uint> bits = (leftBits.Length <= BigIntegerCalculator.StackAllocThreshold
? stackalloc uint[BigIntegerCalculator.StackAllocThreshold]
: bitsFromPool = ArrayPool<uint>.Shared.Rent(leftBits.Length)).Slice(0, leftBits.Length);
BigIntegerCalculator.Gcd(leftBits, rightBits, bits);
result = new BigInteger(bits, negative: false);
}
if (bitsFromPool != null)
ArrayPool<uint>.Shared.Return(bitsFromPool);
return result;
}
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;
}
public static BigInteger ModPow(BigInteger value, BigInteger exponent, BigInteger modulus)
{
ArgumentOutOfRangeException.ThrowIfNegative(exponent.Sign, nameof(exponent));
value.AssertValid();
exponent.AssertValid();
modulus.AssertValid();
bool trivialValue = value._bits == null;
bool trivialExponent = exponent._bits == null;
bool trivialModulus = modulus._bits == null;
BigInteger result;
if (trivialModulus)
{
uint bits = trivialValue && trivialExponent ? BigIntegerCalculator.Pow(NumericsHelpers.Abs(value._sign), NumericsHelpers.Abs(exponent._sign), NumericsHelpers.Abs(modulus._sign)) :
trivialValue ? BigIntegerCalculator.Pow(NumericsHelpers.Abs(value._sign), exponent._bits!, NumericsHelpers.Abs(modulus._sign)) :
trivialExponent ? BigIntegerCalculator.Pow(value._bits!, NumericsHelpers.Abs(exponent._sign), NumericsHelpers.Abs(modulus._sign)) :
BigIntegerCalculator.Pow(value._bits!, exponent._bits!, NumericsHelpers.Abs(modulus._sign));
result = value._sign < 0 && !exponent.IsEven ? -1 * bits : bits;
}
else
{
int size = (modulus._bits?.Length ?? 1) << 1;
uint[]? bitsFromPool = null;
Span<uint> bits = ((uint)size <= BigIntegerCalculator.StackAllocThreshold
? stackalloc uint[BigIntegerCalculator.StackAllocThreshold]
: bitsFromPool = ArrayPool<uint>.Shared.Rent(size)).Slice(0, size);
bits.Clear();
if (trivialValue)
{
if (trivialExponent)
{