/
biguintcore.d
2338 lines (2143 loc) · 73.1 KB
/
biguintcore.d
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
/** Fundamental operations for arbitrary-precision arithmetic
*
* These functions are for internal use only.
*/
/* Copyright Don Clugston 2008 - 2010.
* Distributed under the Boost Software License, Version 1.0.
* (See accompanying file LICENSE_1_0.txt or copy at
* http://www.boost.org/LICENSE_1_0.txt)
*/
/* References:
"Modern Computer Arithmetic" (MCA) is the primary reference for all
algorithms used in this library.
- R.P. Brent and P. Zimmermann, "Modern Computer Arithmetic",
Version 0.5.9, (Oct 2010).
- C. Burkinel and J. Ziegler, "Fast Recursive Division", MPI-I-98-1-022,
Max-Planck Institute fuer Informatik, (Oct 1998).
- G. Hanrot, M. Quercia, and P. Zimmermann, "The Middle Product Algorithm, I.",
INRIA 4664, (Dec 2002).
- M. Bodrato and A. Zanoni, "What about Toom-Cook Matrices Optimality?",
http://bodrato.it/papers (2006).
- A. Fog, "Optimizing subroutines in assembly language",
www.agner.org/optimize (2008).
- A. Fog, "The microarchitecture of Intel and AMD CPU's",
www.agner.org/optimize (2008).
- A. Fog, "Instruction tables: Lists of instruction latencies, throughputs
and micro-operation breakdowns for Intel and AMD CPU's.", www.agner.org/optimize (2008).
Idioms:
Many functions in this module use
'func(Tulong)(Tulong x) if (is(Tulong == ulong))' rather than 'func(ulong x)'
in order to disable implicit conversion.
*/
module std.internal.math.biguintcore;
version(D_InlineAsm_X86)
{
import std.internal.math.biguintx86;
}
else
{
import std.internal.math.biguintnoasm;
}
alias multibyteAdd = multibyteAddSub!('+');
alias multibyteSub = multibyteAddSub!('-');
private import core.cpuid;
private import std.traits : Unqual;
shared static this()
{
CACHELIMIT = core.cpuid.datacache[0].size*1024/2;
FASTDIVLIMIT = 100;
}
private:
// Limits for when to switch between algorithms.
immutable size_t CACHELIMIT; // Half the size of the data cache.
immutable size_t FASTDIVLIMIT; // crossover to recursive division
// These constants are used by shift operations
static if (BigDigit.sizeof == int.sizeof)
{
enum { LG2BIGDIGITBITS = 5, BIGDIGITSHIFTMASK = 31 };
alias BIGHALFDIGIT = ushort;
}
else static if (BigDigit.sizeof == long.sizeof)
{
alias BIGHALFDIGIT = uint;
enum { LG2BIGDIGITBITS = 6, BIGDIGITSHIFTMASK = 63 };
}
else static assert(0, "Unsupported BigDigit size");
private import std.exception : assumeUnique;
private import std.traits:isIntegral;
enum BigDigitBits = BigDigit.sizeof*8;
template maxBigDigits(T) if (isIntegral!T)
{
enum maxBigDigits = (T.sizeof+BigDigit.sizeof-1)/BigDigit.sizeof;
}
enum immutable(BigDigit) [] ZERO = [0];
enum immutable(BigDigit) [] ONE = [1];
enum immutable(BigDigit) [] TWO = [2];
enum immutable(BigDigit) [] TEN = [10];
public:
/// BigUint performs memory management and wraps the low-level calls.
struct BigUint
{
private:
pure invariant()
{
assert( data.length >= 1 && (data.length == 1 || data[$-1] != 0 ));
}
immutable(BigDigit) [] data = ZERO;
this(immutable(BigDigit) [] x) pure
{
data = x;
}
this(T)(T x) pure if (isIntegral!T)
{
opAssign(x);
}
public:
// Length in uints
size_t uintLength() pure const
{
static if (BigDigit.sizeof == uint.sizeof)
{
return data.length;
}
else static if (BigDigit.sizeof == ulong.sizeof)
{
return data.length * 2 -
((data[$-1] & 0xFFFF_FFFF_0000_0000L) ? 1 : 0);
}
}
size_t ulongLength() pure const
{
static if (BigDigit.sizeof == uint.sizeof)
{
return (data.length + 1) >> 1;
}
else static if (BigDigit.sizeof == ulong.sizeof)
{
return data.length;
}
}
// The value at (cast(ulong[])data)[n]
ulong peekUlong(int n) pure const
{
static if (BigDigit.sizeof == int.sizeof)
{
if (data.length == n*2 + 1) return data[n*2];
return data[n*2] + ((cast(ulong)data[n*2 + 1]) << 32 );
}
else static if (BigDigit.sizeof == long.sizeof)
{
return data[n];
}
}
uint peekUint(int n) pure const
{
static if (BigDigit.sizeof == int.sizeof)
{
return data[n];
}
else
{
ulong x = data[n >> 1];
return (n & 1) ? cast(uint)(x >> 32) : cast(uint)x;
}
}
public:
///
void opAssign(Tulong)(Tulong u) pure if (is (Tulong == ulong))
{
if (u == 0) data = ZERO;
else if (u == 1) data = ONE;
else if (u == 2) data = TWO;
else if (u == 10) data = TEN;
else
{
static if (BigDigit.sizeof == int.sizeof)
{
uint ulo = cast(uint)(u & 0xFFFF_FFFF);
uint uhi = cast(uint)(u >> 32);
if (uhi == 0)
{
data = [ulo];
}
else
{
data = [ulo, uhi];
}
}
else static if (BigDigit.sizeof == long.sizeof)
{
data = [u];
}
}
}
void opAssign(Tdummy = void)(BigUint y) pure
{
this.data = y.data;
}
///
int opCmp(Tdummy = void)(const BigUint y) pure const
{
if (data.length != y.data.length)
return (data.length > y.data.length) ? 1 : -1;
size_t k = highestDifferentDigit(data, y.data);
if (data[k] == y.data[k])
return 0;
return data[k] > y.data[k] ? 1 : -1;
}
///
int opCmp(Tulong)(Tulong y) pure const if(is (Tulong == ulong))
{
if (data.length > maxBigDigits!Tulong)
return 1;
foreach_reverse (i; 0 .. maxBigDigits!Tulong)
{
BigDigit tmp = cast(BigDigit)(y>>(i*BigDigitBits));
if (tmp == 0)
if (data.length >= i+1)
{
// Since ZERO is [0], so we cannot simply return 1 here, as
// data[i] would be 0 for i==0 in that case.
return (data[i] > 0) ? 1 : 0;
}
else
continue;
else
if (i+1 > data.length)
return -1;
else if (tmp != data[i])
return data[i] > tmp ? 1 : -1;
}
return 0;
}
bool opEquals(Tdummy = void)(ref const BigUint y) pure const
{
return y.data[] == data[];
}
bool opEquals(Tdummy = void)(ulong y) pure const
{
if (data.length > 2)
return false;
uint ylo = cast(uint)(y & 0xFFFF_FFFF);
uint yhi = cast(uint)(y >> 32);
if (data.length==2 && data[1]!=yhi)
return false;
if (data.length==1 && yhi!=0)
return false;
return (data[0] == ylo);
}
bool isZero() pure const nothrow @safe
{
return data.length == 1 && data[0] == 0;
}
size_t numBytes() pure const
{
return data.length * BigDigit.sizeof;
}
// the extra bytes are added to the start of the string
char [] toDecimalString(int frontExtraBytes) const pure
{
auto predictlength = 20+20*(data.length/2); // just over 19
char [] buff = new char[frontExtraBytes + predictlength];
ptrdiff_t sofar = biguintToDecimal(buff, data.dup);
return buff[sofar-frontExtraBytes..$];
}
/** Convert to a hex string, printing a minimum number of digits 'minPadding',
* allocating an additional 'frontExtraBytes' at the start of the string.
* Padding is done with padChar, which may be '0' or ' '.
* 'separator' is a digit separation character. If non-zero, it is inserted
* between every 8 digits.
* Separator characters do not contribute to the minPadding.
*/
char [] toHexString(int frontExtraBytes, char separator = 0,
int minPadding=0, char padChar = '0') const pure
{
// Calculate number of extra padding bytes
size_t extraPad = (minPadding > data.length * 2 * BigDigit.sizeof)
? minPadding - data.length * 2 * BigDigit.sizeof : 0;
// Length not including separator bytes
size_t lenBytes = data.length * 2 * BigDigit.sizeof;
// Calculate number of separator bytes
size_t mainSeparatorBytes = separator ? (lenBytes / 8) - 1 : 0;
size_t totalSeparatorBytes = separator ? ((extraPad + lenBytes + 7) / 8) - 1: 0;
char [] buff = new char[lenBytes + extraPad + totalSeparatorBytes + frontExtraBytes];
biguintToHex(buff[$ - lenBytes - mainSeparatorBytes .. $], data, separator);
if (extraPad > 0)
{
if (separator)
{
size_t start = frontExtraBytes; // first index to pad
if (extraPad &7)
{
// Do 1 to 7 extra zeros.
buff[frontExtraBytes .. frontExtraBytes + (extraPad & 7)] = padChar;
buff[frontExtraBytes + (extraPad & 7)] = (padChar == ' ' ? ' ' : separator);
start += (extraPad & 7) + 1;
}
for (int i=0; i< (extraPad >> 3); ++i)
{
buff[start .. start + 8] = padChar;
buff[start + 8] = (padChar == ' ' ? ' ' : separator);
start += 9;
}
}
else
{
buff[frontExtraBytes .. frontExtraBytes + extraPad]=padChar;
}
}
int z = frontExtraBytes;
if (lenBytes > minPadding)
{
// Strip leading zeros.
ptrdiff_t maxStrip = lenBytes - minPadding;
while (z< buff.length-1 && (buff[z]=='0' || buff[z]==padChar) && maxStrip>0)
{
++z;
--maxStrip;
}
}
if (padChar!='0')
{
// Convert leading zeros into padChars.
for (size_t k= z; k< buff.length-1 && (buff[k]=='0' || buff[k]==padChar); ++k)
{
if (buff[k]=='0') buff[k]=padChar;
}
}
return buff[z-frontExtraBytes..$];
}
// return false if invalid character found
bool fromHexString(const(char)[] s) pure
{
//Strip leading zeros
int firstNonZero = 0;
while ((firstNonZero < s.length - 1) &&
(s[firstNonZero]=='0' || s[firstNonZero]=='_'))
{
++firstNonZero;
}
auto len = (s.length - firstNonZero + 15)/4;
auto tmp = new BigDigit[len+1];
uint part = 0;
uint sofar = 0;
uint partcount = 0;
assert(s.length>0);
for (ptrdiff_t i = s.length - 1; i>=firstNonZero; --i)
{
assert(i>=0);
char c = s[i];
if (s[i]=='_') continue;
uint x = (c>='0' && c<='9') ? c - '0'
: (c>='A' && c<='F') ? c - 'A' + 10
: (c>='a' && c<='f') ? c - 'a' + 10
: 100;
if (x==100) return false;
part >>= 4;
part |= (x<<(32-4));
++partcount;
if (partcount==8)
{
tmp[sofar] = part;
++sofar;
partcount = 0;
part = 0;
}
}
if (part)
{
for ( ; partcount != 8; ++partcount) part >>= 4;
tmp[sofar] = part;
++sofar;
}
if (sofar == 0) data = ZERO;
else data = assumeUnique(tmp[0..sofar]);
return true;
}
// return true if OK; false if erroneous characters found
bool fromDecimalString(const(char)[] s) pure
{
//Strip leading zeros
int firstNonZero = 0;
while ((firstNonZero < s.length) &&
(s[firstNonZero]=='0' || s[firstNonZero]=='_'))
{
++firstNonZero;
}
if (firstNonZero == s.length && s.length >= 1)
{
data = ZERO;
return true;
}
auto predictlength = (18*2 + 2*(s.length-firstNonZero)) / 19;
auto tmp = new BigDigit[predictlength];
uint hi = biguintFromDecimal(tmp, s[firstNonZero..$]);
tmp.length = hi;
data = assumeUnique(tmp);
return true;
}
////////////////////////
//
// All of these member functions create a new BigUint.
// return x >> y
BigUint opShr(Tulong)(Tulong y) pure const if (is (Tulong == ulong))
{
assert(y>0);
uint bits = cast(uint)y & BIGDIGITSHIFTMASK;
if ((y>>LG2BIGDIGITBITS) >= data.length) return BigUint(ZERO);
uint words = cast(uint)(y >> LG2BIGDIGITBITS);
if (bits==0)
{
return BigUint(data[words..$]);
}
else
{
uint [] result = new BigDigit[data.length - words];
multibyteShr(result, data[words..$], bits);
if (result.length>1 && result[$-1]==0) return BigUint(assumeUnique(result[0..$-1]));
else return BigUint(assumeUnique(result));
}
}
// return x << y
BigUint opShl(Tulong)(Tulong y) pure const if (is (Tulong == ulong))
{
assert(y>0);
if (isZero()) return this;
uint bits = cast(uint)y & BIGDIGITSHIFTMASK;
assert ((y>>LG2BIGDIGITBITS) < cast(ulong)(uint.max));
uint words = cast(uint)(y >> LG2BIGDIGITBITS);
BigDigit [] result = new BigDigit[data.length + words+1];
result[0..words] = 0;
if (bits==0)
{
result[words..words+data.length] = data[];
return BigUint(assumeUnique(result[0..words+data.length]));
}
else
{
uint c = multibyteShl(result[words..words+data.length], data, bits);
if (c==0) return BigUint(assumeUnique(result[0..words+data.length]));
result[$-1] = c;
return BigUint(assumeUnique(result));
}
}
// If wantSub is false, return x + y, leaving sign unchanged
// If wantSub is true, return abs(x - y), negating sign if x < y
static BigUint addOrSubInt(Tulong)(const BigUint x, Tulong y,
bool wantSub, ref bool sign) pure if (is(Tulong == ulong))
{
BigUint r;
if (wantSub)
{ // perform a subtraction
if (x.data.length > 2)
{
r.data = subInt(x.data, y);
}
else
{ // could change sign!
ulong xx = x.data[0];
if (x.data.length > 1)
xx += (cast(ulong)x.data[1]) << 32;
ulong d;
if (xx <= y)
{
d = y - xx;
sign = !sign;
}
else
{
d = xx - y;
}
if (d == 0)
{
r = 0UL;
sign = false;
return r;
}
if (d > uint.max)
{
r.data = [cast(uint)(d & 0xFFFF_FFFF), cast(uint)(d>>32)];
}
else
{
r.data = [cast(uint)(d & 0xFFFF_FFFF)];
}
}
}
else
{
r.data = addInt(x.data, y);
}
return r;
}
// If wantSub is false, return x + y, leaving sign unchanged.
// If wantSub is true, return abs(x - y), negating sign if x<y
static BigUint addOrSub(BigUint x, BigUint y, bool wantSub, bool *sign)
pure
{
BigUint r;
if (wantSub)
{ // perform a subtraction
bool negative;
r.data = sub(x.data, y.data, &negative);
*sign ^= negative;
if (r.isZero())
{
*sign = false;
}
}
else
{
r.data = add(x.data, y.data);
}
return r;
}
// return x*y.
// y must not be zero.
static BigUint mulInt(T = ulong)(BigUint x, T y) pure
{
if (y==0 || x == 0) return BigUint(ZERO);
uint hi = cast(uint)(y >>> 32);
uint lo = cast(uint)(y & 0xFFFF_FFFF);
uint [] result = new BigDigit[x.data.length+1+(hi!=0)];
result[x.data.length] = multibyteMul(result[0..x.data.length], x.data, lo, 0);
if (hi!=0)
{
result[x.data.length+1] = multibyteMulAdd!('+')(result[1..x.data.length+1],
x.data, hi, 0);
}
return BigUint(removeLeadingZeros(assumeUnique(result)));
}
/* return x * y.
*/
static BigUint mul(BigUint x, BigUint y) pure
{
if (y==0 || x == 0)
return BigUint(ZERO);
auto len = x.data.length + y.data.length;
BigDigit [] result = new BigDigit[len];
if (y.data.length > x.data.length)
{
mulInternal(result, y.data, x.data);
}
else
{
if (x.data[]==y.data[]) squareInternal(result, x.data);
else mulInternal(result, x.data, y.data);
}
// the highest element could be zero,
// in which case we need to reduce the length
return BigUint(removeLeadingZeros(assumeUnique(result)));
}
// return x / y
static BigUint divInt(T)(BigUint x, T y_) pure if ( is(Unqual!T == uint) )
{
uint y = y_;
if (y == 1)
return x;
uint [] result = new BigDigit[x.data.length];
if ((y&(-y))==y)
{
assert(y!=0, "BigUint division by zero");
// perfect power of 2
uint b = 0;
for (;y!=1; y>>=1)
{
++b;
}
multibyteShr(result, x.data, b);
}
else
{
result[] = x.data[];
uint rem = multibyteDivAssign(result, y, 0);
}
return BigUint(removeLeadingZeros(assumeUnique(result)));
}
// return x % y
static uint modInt(T)(BigUint x, T y_) pure if ( is(Unqual!T == uint) )
{
uint y = y_;
assert(y!=0);
if ((y&(-y)) == y)
{ // perfect power of 2
return x.data[0] & (y-1);
}
else
{
// horribly inefficient - malloc, copy, & store are unnecessary.
uint [] wasteful = new BigDigit[x.data.length];
wasteful[] = x.data[];
uint rem = multibyteDivAssign(wasteful, y, 0);
delete wasteful;
return rem;
}
}
// return x / y
static BigUint div(BigUint x, BigUint y) pure
{
if (y.data.length > x.data.length)
return BigUint(ZERO);
if (y.data.length == 1)
return divInt(x, y.data[0]);
BigDigit [] result = new BigDigit[x.data.length - y.data.length + 1];
divModInternal(result, null, x.data, y.data);
return BigUint(removeLeadingZeros(assumeUnique(result)));
}
// return x % y
static BigUint mod(BigUint x, BigUint y) pure
{
if (y.data.length > x.data.length) return x;
if (y.data.length == 1)
{
return BigUint([modInt(x, y.data[0])]);
}
BigDigit [] result = new BigDigit[x.data.length - y.data.length + 1];
BigDigit [] rem = new BigDigit[y.data.length];
divModInternal(result, rem, x.data, y.data);
return BigUint(removeLeadingZeros(assumeUnique(rem)));
}
// return x op y
static BigUint bitwiseOp(string op)(BigUint x, BigUint y, bool xSign, bool ySign, ref bool resultSign) pure if (op == "|" || op == "^" || op == "&")
{
auto d1 = includeSign(x.data, y.uintLength, xSign);
auto d2 = includeSign(y.data, x.uintLength, ySign);
foreach (i; 0..d1.length)
{
mixin("d1[i] " ~ op ~ "= d2[i];");
}
mixin("resultSign = xSign " ~ op ~ " ySign;");
if (resultSign) {
twosComplement(d1, d1);
}
return BigUint(removeLeadingZeros(assumeUnique(d1)));
}
/**
* Return a BigUint which is x raised to the power of y.
* Method: Powers of 2 are removed from x, then left-to-right binary
* exponentiation is used.
* Memory allocation is minimized: at most one temporary BigUint is used.
*/
static BigUint pow(BigUint x, ulong y) pure
{
// Deal with the degenerate cases first.
if (y==0) return BigUint(ONE);
if (y==1) return x;
if (x==0 || x==1) return x;
BigUint result;
// Simplify, step 1: Remove all powers of 2.
uint firstnonzero = firstNonZeroDigit(x.data);
// Now we know x = x[firstnonzero..$] * (2^^(firstnonzero*BigDigitBits))
// where BigDigitBits = BigDigit.sizeof * 8
// See if x[firstnonzero..$] can now fit into a single digit.
bool singledigit = ((x.data.length - firstnonzero) == 1);
// If true, then x0 is that digit
// and the result will be (x0 ^^ y) * (2^^(firstnonzero*y*BigDigitBits))
BigDigit x0 = x.data[firstnonzero];
assert(x0 !=0);
// Length of the non-zero portion
size_t nonzerolength = x.data.length - firstnonzero;
ulong y0;
uint evenbits = 0; // number of even bits in the bottom of x
while (!(x0 & 1))
{
x0 >>= 1;
++evenbits;
}
if ((x.data.length- firstnonzero == 2))
{
// Check for a single digit straddling a digit boundary
BigDigit x1 = x.data[firstnonzero+1];
if ((x1 >> evenbits) == 0)
{
x0 |= (x1 << (BigDigit.sizeof * 8 - evenbits));
singledigit = true;
}
}
// Now if (singledigit), x^^y = (x0 ^^ y) * 2^^(evenbits * y) * 2^^(firstnonzero*y*BigDigitBits))
uint evenshiftbits = 0; // Total powers of 2 to shift by, at the end
// Simplify, step 2: For singledigits, see if we can trivially reduce y
BigDigit finalMultiplier = 1UL;
if (singledigit)
{
// x fits into a single digit. Raise it to the highest power we can
// that still fits into a single digit, then reduce the exponent accordingly.
// We're quite likely to have a residual multiply at the end.
// For example, 10^^100 = (((5^^13)^^7) * 5^^9) * 2^^100.
// and 5^^13 still fits into a uint.
evenshiftbits = cast(uint)( (evenbits * y) & BIGDIGITSHIFTMASK);
if (x0 == 1)
{ // Perfect power of 2
result = 1UL;
return result << (evenbits + firstnonzero * 8 * BigDigit.sizeof) * y;
}
int p = highestPowerBelowUintMax(x0);
if (y <= p)
{ // Just do it with pow
result = cast(ulong)intpow(x0, y);
if (evenbits + firstnonzero == 0)
return result;
return result << (evenbits + firstnonzero * 8 * BigDigit.sizeof) * y;
}
y0 = y / p;
finalMultiplier = intpow(x0, y - y0*p);
x0 = intpow(x0, p);
// Result is x0
nonzerolength = 1;
}
// Now if (singledigit), x^^y = finalMultiplier * (x0 ^^ y0) * 2^^(evenbits * y) * 2^^(firstnonzero*y*BigDigitBits))
// Perform a crude check for overflow and allocate result buffer.
// The length required is y * lg2(x) bits.
// which will always fit into y*x.length digits. But this is
// a gross overestimate if x is small (length 1 or 2) and the highest
// digit is nearly empty.
// A better estimate is:
// y * lg2(x[$-1]/BigDigit.max) + y * (x.length - 1) digits,
// and the first term is always between
// y * (bsr(x.data[$-1]) + 1) / BIGDIGITBITS and
// y * (bsr(x.data[$-1]) + 2) / BIGDIGITBITS
// For single digit payloads, we already have
// x^^y = finalMultiplier * (x0 ^^ y0) * 2^^(evenbits * y) * 2^^(firstnonzero*y*BigDigitBits))
// and x0 is almost a full digit, so it's a tight estimate.
// Number of digits is therefore 1 + x0.length*y0 + (evenbits*y)/BIGDIGIT + firstnonzero*y
// Note that the divisions must be rounded up.
// Estimated length in BigDigits
ulong estimatelength = singledigit
? 1 + y0 + ((evenbits*y + BigDigit.sizeof * 8 - 1) / (BigDigit.sizeof *8)) + firstnonzero*y
: x.data.length * y;
// Imprecise check for overflow. Makes the extreme cases easier to debug
// (less extreme overflow will result in an out of memory error).
if (estimatelength > uint.max/(4*BigDigit.sizeof))
assert(0, "Overflow in BigInt.pow");
// The result buffer includes space for all the trailing zeros
BigDigit [] resultBuffer = new BigDigit[cast(size_t)estimatelength];
// Do all the powers of 2!
size_t result_start = cast(size_t)( firstnonzero * y
+ (singledigit ? ((evenbits * y) >> LG2BIGDIGITBITS) : 0));
resultBuffer[0..result_start] = 0;
BigDigit [] t1 = resultBuffer[result_start..$];
BigDigit [] r1;
if (singledigit)
{
r1 = t1[0..1];
r1[0] = x0;
y = y0;
}
else
{
// It's not worth right shifting by evenbits unless we also shrink the length after each
// multiply or squaring operation. That might still be worthwhile for large y.
r1 = t1[0..x.data.length - firstnonzero];
r1[0..$] = x.data[firstnonzero..$];
}
if (y>1)
{ // Set r1 = r1 ^^ y.
// The secondary buffer only needs space for the multiplication results
BigDigit [] secondaryBuffer = new BigDigit[resultBuffer.length - result_start];
BigDigit [] t2 = secondaryBuffer;
BigDigit [] r2;
int shifts = 63; // num bits in a long
while(!(y & 0x8000_0000_0000_0000L))
{
y <<= 1;
--shifts;
}
y <<=1;
while(y!=0)
{
// For each bit of y: Set r1 = r1 * r1
// If the bit is 1, set r1 = r1 * x
// Eg, if y is 0b101, result = ((x^^2)^^2)*x == x^^5.
// Optimization opportunity: if more than 2 bits in y are set,
// it's usually possible to reduce the number of multiplies
// by caching odd powers of x. eg for y = 54,
// (0b110110), set u = x^^3, and result is ((u^^8)*u)^^2
r2 = t2[0 .. r1.length*2];
squareInternal(r2, r1);
if (y & 0x8000_0000_0000_0000L)
{
r1 = t1[0 .. r2.length + nonzerolength];
if (singledigit)
{
r1[$-1] = multibyteMul(r1[0 .. $-1], r2, x0, 0);
}
else
{
mulInternal(r1, r2, x.data[firstnonzero..$]);
}
}
else
{
r1 = t1[0 .. r2.length];
r1[] = r2[];
}
y <<=1;
shifts--;
}
while (shifts>0)
{
r2 = t2[0 .. r1.length * 2];
squareInternal(r2, r1);
r1 = t1[0 .. r2.length];
r1[] = r2[];
--shifts;
}
}
if (finalMultiplier!=1)
{
BigDigit carry = multibyteMul(r1, r1, finalMultiplier, 0);
if (carry)
{
r1 = t1[0 .. r1.length + 1];
r1[$-1] = carry;
}
}
if (evenshiftbits)
{
BigDigit carry = multibyteShl(r1, r1, evenshiftbits);
if (carry!=0)
{
r1 = t1[0 .. r1.length + 1];
r1[$ - 1] = carry;
}
}
while(r1[$ - 1]==0)
{
r1=r1[0 .. $ - 1];
}
return BigUint(assumeUnique(resultBuffer[0 .. result_start + r1.length]));
}
// Implement toHash so that BigUint works properly as an AA key.
size_t toHash() const @trusted nothrow
{
return typeid(data).getHash(&data);
}
} // end BigUint
unittest
{
// ulong comparison test
BigUint a = [1];
assert(a == 1);
assert(a < 0x8000_0000_0000_0000UL); // bug 9548
// bug 12234
BigUint z = [0];
assert(z == 0UL);
assert(!(z > 0UL));
assert(!(z < 0UL));
}
// Remove leading zeros from x, to restore the BigUint invariant
inout(BigDigit) [] removeLeadingZeros(inout(BigDigit) [] x) pure
{
size_t k = x.length;
while(k>1 && x[k - 1]==0) --k;
return x[0 .. k];
}
unittest
{
BigUint r = BigUint([5]);
BigUint t = BigUint([7]);
BigUint s = BigUint.mod(r, t);
assert(s==5);
}
unittest
{
BigUint r;
r = 5UL;
assert(r.peekUlong(0) == 5UL);
assert(r.peekUint(0) == 5U);
r = 0x1234_5678_9ABC_DEF0UL;
assert(r.peekUlong(0) == 0x1234_5678_9ABC_DEF0UL);
assert(r.peekUint(0) == 0x9ABC_DEF0U);
}
// Pow tests
unittest
{
BigUint r, s;
r.fromHexString("80000000_00000001");
s = BigUint.pow(r, 5);
r.fromHexString("08000000_00000000_50000000_00000001_40000000_00000002_80000000"
~ "_00000002_80000000_00000001");
assert(s == r);
s = 10UL;
s = BigUint.pow(s, 39);
r.fromDecimalString("1000000000000000000000000000000000000000");
assert(s == r);
r.fromHexString("1_E1178E81_00000000");
s = BigUint.pow(r, 15); // Regression test: this used to overflow array bounds
r.fromDecimalString("000_000_00");
assert(r == 0);
r.fromDecimalString("0007");
assert(r == 7);
r.fromDecimalString("0");
assert(r == 0);
}
// Radix conversion tests
unittest
{
BigUint r;
r.fromHexString("1_E1178E81_00000000");
assert(r.toHexString(0, '_', 0) == "1_E1178E81_00000000");
assert(r.toHexString(0, '_', 20) == "0001_E1178E81_00000000");
assert(r.toHexString(0, '_', 16+8) == "00000001_E1178E81_00000000");
assert(r.toHexString(0, '_', 16+9) == "0_00000001_E1178E81_00000000");
assert(r.toHexString(0, '_', 16+8+8) == "00000000_00000001_E1178E81_00000000");
assert(r.toHexString(0, '_', 16+8+8+1) == "0_00000000_00000001_E1178E81_00000000");
assert(r.toHexString(0, '_', 16+8+8+1, ' ') == " 1_E1178E81_00000000");
assert(r.toHexString(0, 0, 16+8+8+1) == "00000000000000001E1178E8100000000");
r = 0UL;
assert(r.toHexString(0, '_', 0) == "0");
assert(r.toHexString(0, '_', 7) == "0000000");
assert(r.toHexString(0, '_', 7, ' ') == " 0");
assert(r.toHexString(0, '#', 9) == "0#00000000");
assert(r.toHexString(0, 0, 9) == "000000000");
}
private:
void twosComplement(const(BigDigit) [] x, BigDigit[] result) pure
{
foreach (i; 0..x.length)
{
result[i] = ~x[i];
}
result[x.length..$] = BigDigit.max;
bool sgn = false;
foreach (i; 0..result.length) {
if (result[i] == BigDigit.max) {
result[i] = 0;
} else {
result[i] += 1;
break;
}
}
}
// Encode BigInt as BigDigit array (sign and 2's complement)
BigDigit[] includeSign(const(BigDigit) [] x, size_t minSize, bool sign) pure
{
size_t length = (x.length > minSize) ? x.length : minSize;
BigDigit [] result = new BigDigit[length];