-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathbigint.pas
2106 lines (1972 loc) · 70.2 KB
/
bigint.pas
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
UNIT bigint;
INTERFACE
USES sysutils,
math,
myGenerics,
serializationUtil;
TYPE
DigitType=dword;
CarryType=qword;
DigitTypeArray=array of DigitType;
CONST
BITS_PER_DIGIT=32;
DIGIT_MAX_VALUE:int64=(1 shl BITS_PER_DIGIT)-1;
UPPER_DIGIT_BIT=1 shl (BITS_PER_DIGIT-1);
WORD_BIT:array[0..BITS_PER_DIGIT-1] of DigitType=
( 1, 2, 4, 8, 16, 32, 64, 128,
256, 512, 1024, 2048, 4096, 8192, 16384, 32768,
65536, 131072, 262144, 524288, 1048576, 2097152, 4194304, 8388608,
16777216,33554432,67108864,134217728,268435456,536870912,1073741824,2147483648);
TYPE
T_comparisonResult=(CR_EQUAL,
CR_LESSER,
CR_GREATER,
CR_INVALID_COMPARAND);
T_roundingMode=(RM_DEFAULT,RM_UP,RM_DOWN);
CONST
C_FLIPPED:array[T_comparisonResult] of T_comparisonResult=(CR_EQUAL,CR_GREATER,CR_LESSER,CR_INVALID_COMPARAND);
TYPE
F_rand32Source =FUNCTION:dword;
F_rand32SourceOfObject=FUNCTION:dword of object;
T_arrayOfByte=array of byte;
T_bigInt=object
private
negative:boolean;
digits:DigitTypeArray;
PROCEDURE createFromRawData(CONST negative_:boolean; CONST digits_:DigitTypeArray);
PROCEDURE nullBits(CONST numberOfBitsToKeep:longint);
PROCEDURE shlInc(CONST incFirstBit:boolean);
PROCEDURE setBit(CONST index:longint; CONST value:boolean);
FUNCTION compareAbsValue(CONST big:T_bigInt):T_comparisonResult; inline;
FUNCTION compareAbsValue(CONST int:int64):T_comparisonResult; inline;
PROCEDURE multWith(CONST l:longint);
PROCEDURE multWith(CONST b:T_bigInt);
PROCEDURE divBy(CONST divisor:DigitType; OUT rest:DigitType);
PROCEDURE incAbsValue(CONST positiveIncrement:DigitType);
PROCEDURE shiftRightOneBit;
public
FUNCTION relevantBits:longint;
PROCEDURE shiftRight(CONST rightShift:longint);
PROPERTY isNegative:boolean read negative;
PROCEDURE createZero;
PROCEDURE create(CONST negativeNumber:boolean; CONST digitCount_:longint);
PROCEDURE fromInt(CONST i:int64);
PROCEDURE fromString(CONST s:string);
PROCEDURE fromFloat(CONST f:extended; CONST rounding:T_roundingMode);
PROCEDURE create(CONST toClone:T_bigInt);
PROCEDURE createFromDigits(CONST base:longint; CONST digits_:T_arrayOfLongint);
PROCEDURE clear;
FUNCTION toInt:int64;
FUNCTION toFloat:extended;
{if examineNicheCase is true, the case of -2^63 is considered; otherwise the function is symmetrical}
FUNCTION canBeRepresentedAsInt64(CONST examineNicheCase: boolean=true): boolean;
FUNCTION canBeRepresentedAsInt62:boolean;
FUNCTION canBeRepresentedAsInt32(CONST examineNicheCase: boolean=true): boolean;
FUNCTION getBit(CONST index:longint):boolean;
FUNCTION getDigits(CONST base:longint):T_arrayOfLongint;
PROCEDURE flipSign;
FUNCTION negated:T_bigInt;
FUNCTION compare(CONST big:T_bigInt):T_comparisonResult; inline;
FUNCTION compare(CONST int:int64 ):T_comparisonResult; inline;
FUNCTION compare(CONST f:extended ):T_comparisonResult; inline;
FUNCTION minus(CONST small:DigitType):T_bigInt;
FUNCTION pow (power:dword ):T_bigInt;
FUNCTION powMod(CONST power,modul:T_bigInt):T_bigInt;
FUNCTION isOdd:boolean;
FUNCTION bitAnd(CONST big:T_bigInt):T_bigInt;
FUNCTION bitAnd(CONST small:int64 ):T_bigInt;
FUNCTION bitOr (CONST big:T_bigInt):T_bigInt;
FUNCTION bitOr (CONST small:int64 ):T_bigInt;
FUNCTION bitXor(CONST big:T_bigInt):T_bigInt;
FUNCTION bitXor(CONST small:int64 ):T_bigInt;
FUNCTION bitNegate(CONST consideredBits:longint):T_bigInt;
{returns true on success, false on division by zero}
FUNCTION divMod(CONST divisor:T_bigInt; OUT quotient,rest:T_bigInt):boolean;
FUNCTION divide(CONST divisor:T_bigInt):T_bigInt;
FUNCTION modulus(CONST divisor:T_bigInt):T_bigInt;
FUNCTION toString:string;
FUNCTION toHexString:string;
FUNCTION equals(CONST b:T_bigInt):boolean;
FUNCTION isZero:boolean;
FUNCTION isOne:boolean;
FUNCTION isBetween(CONST lowerBoundInclusive,upperBoundInclusive:longint):boolean;
PROCEDURE writeToStream(CONST stream:P_outputStreamWrapper);
PROCEDURE readFromStream(CONST stream:P_inputStreamWrapper);
PROCEDURE readFromStream(CONST markerByte:byte; CONST stream:P_inputStreamWrapper);
FUNCTION lowDigit:DigitType;
FUNCTION sign:shortint;
FUNCTION greatestCommonDivider(CONST other:T_bigInt):T_bigInt;
FUNCTION greatestCommonDivider(CONST other:int64):int64;
FUNCTION modularInverse(CONST modul:T_bigInt; OUT thereIsAModularInverse:boolean):T_bigInt;
FUNCTION iSqrt (CONST computeEvenIfNotSquare:boolean; CONST roundingMode:T_roundingMode; OUT isSquare:boolean):T_bigInt;
FUNCTION iLog2(OUT isPowerOfTwo:boolean):longint;
FUNCTION hammingWeight:longint;
FUNCTION getRawBytes:T_arrayOfByte;
FUNCTION hash:dword;
end;
T_arrayOfBigint=array of T_bigInt;
T_factorizationResult=record
smallFactors:T_arrayOfLongint;
bigFactors:T_arrayOfBigint;
end;
T_dynamicContinueFlag=FUNCTION:boolean of object;
FUNCTION randomInt(CONST randomSource:F_rand32Source ; CONST maxValExclusive:T_bigInt):T_bigInt;
FUNCTION randomInt(CONST randomSource:F_rand32SourceOfObject; CONST maxValExclusive:T_bigInt):T_bigInt;
{This function works safely for n<=2^45; for larger numbers arithmetic overflows may occur}
FUNCTION factorizeSmall(n:int64):T_factorizationResult;
FUNCTION factorize(CONST B:T_bigInt; CONST continue:T_dynamicContinueFlag):T_factorizationResult;
FUNCTION isPrime(CONST n:int64 ):boolean;
FUNCTION isPrime(CONST B:T_bigInt):boolean;
FUNCTION bigDigits(CONST value,base:T_bigInt):T_arrayOfBigint;
FUNCTION newFromBigDigits(CONST digits:T_arrayOfBigint; CONST base:T_bigInt):T_bigInt;
{For compatibility with constructor T_bigInt.readFromStream}
FUNCTION readLongintFromStream(CONST markerByte:byte; CONST stream:P_inputStreamWrapper):longint;
PROCEDURE writeLongintToStream(CONST value:longint; CONST stream:P_outputStreamWrapper);
OPERATOR +(CONST x:T_bigInt; CONST y:int64):T_bigInt;
OPERATOR +(CONST x,y:T_bigInt):T_bigInt;
OPERATOR -(CONST x:T_bigInt; CONST y:int64):T_bigInt;
OPERATOR -(CONST x:int64; CONST y:T_bigInt):T_bigInt;
OPERATOR -(CONST x,y:T_bigInt):T_bigInt;
OPERATOR *(CONST x:T_bigInt; CONST y:int64):T_bigInt;
OPERATOR *(CONST x,y:T_bigInt):T_bigInt;
FUNCTION divide (CONST x:T_bigInt; CONST y:int64):T_bigInt;
FUNCTION divide (CONST x:int64; CONST y:T_bigInt):T_bigInt;
OPERATOR mod(CONST x:T_bigInt; CONST y:int64):int64;
FUNCTION modulus(CONST x:int64; CONST y:T_bigInt):T_bigInt;
IMPLEMENTATION
FUNCTION randomInt(CONST randomSource:F_rand32Source; CONST maxValExclusive:T_bigInt):T_bigInt;
VAR k:longint;
temp:T_bigInt;
begin
if maxValExclusive.isZero then begin
result.createZero;
exit;
end;
temp.create(false,length(maxValExclusive.digits));
for k:=0 to length(temp.digits)-1 do temp.digits[k]:=randomSource();
result:=temp.modulus(maxValExclusive);
end;
FUNCTION randomInt(CONST randomSource:F_rand32SourceOfObject; CONST maxValExclusive:T_bigInt):T_bigInt;
VAR k:longint;
temp:T_bigInt;
begin
if maxValExclusive.isZero then begin
result.createZero;
exit;
end;
temp.create(false,length(maxValExclusive.digits));
for k:=0 to length(temp.digits)-1 do temp.digits[k]:=randomSource();
result:=temp.modulus(maxValExclusive);
end;
OPERATOR +(CONST x:T_bigInt; CONST y:int64):T_bigInt;
VAR bigY:T_bigInt;
begin
bigY.fromInt(y);
result:=x+bigY;
end;
FUNCTION rawDataPlus(CONST xDigits,yDigits:DigitTypeArray):DigitTypeArray;
VAR carry:CarryType=0;
i :longint;
begin
i:=length(xDigits);
if i< length(yDigits) then
i:=length(yDigits);
initialize(result);
setLength(result,i);
for i:=0 to length(result)-1 do begin
if i<length(xDigits) then carry+=xDigits[i];
if i<length(yDigits) then carry+=yDigits[i];
result[i]:=carry and DIGIT_MAX_VALUE;
carry:=carry shr BITS_PER_DIGIT;
end;
if carry>0 then begin
setLength(result,length(result)+1);
result[length(result)-1]:=carry;
end;
end;
PROCEDURE trimLeadingZeros(VAR digits:DigitTypeArray); inline;
VAR i:longint;
begin
i:=length(digits);
while (i>0) and (digits[i-1]=0) do dec(i);
if i<>length(digits) then setLength(digits,i);
end;
{Precondition: x>y}
FUNCTION rawDataMinus(CONST xDigits,yDigits:DigitTypeArray):DigitTypeArray; inline;
VAR carry:CarryType=0;
i :longint;
begin
initialize(result);
setLength(result,length(xDigits));
for i:=0 to length(yDigits)-1 do begin
carry+=yDigits[i];
if carry>xDigits[i] then begin
result[i]:=((DIGIT_MAX_VALUE+1)-carry+xDigits[i]) and DIGIT_MAX_VALUE;
carry:=1;
end else begin
result[i]:=xDigits[i]-carry;
carry:=0;
end;
end;
for i:=length(yDigits) to length(xDigits)-1 do begin
if carry>xDigits[i] then begin
result[i]:=((DIGIT_MAX_VALUE+1)-carry+xDigits[i]) and DIGIT_MAX_VALUE;
carry:=1;
end else begin
result[i]:=xDigits[i]-carry;
carry:=0;
end;
end;
trimLeadingZeros(result);
end;
OPERATOR +(CONST x,y:T_bigInt):T_bigInt;
begin
if x.negative=y.negative
then result.createFromRawData(x.negative,rawDataPlus(x.digits,y.digits))
else case x.compareAbsValue(y) of
CR_EQUAL : result.createZero;
CR_LESSER : result.createFromRawData(y.negative,rawDataMinus(y.digits,x.digits));
CR_GREATER: result.createFromRawData(x.negative,rawDataMinus(x.digits,y.digits));
end;
end;
OPERATOR -(CONST x:T_bigInt; CONST y:int64):T_bigInt;
VAR bigY:T_bigInt;
begin
bigY.fromInt(y);
result:=x-bigY;
end;
OPERATOR -(CONST x:int64; CONST y:T_bigInt):T_bigInt;
VAR bigX:T_bigInt;
begin
bigX.fromInt(x);
result:=bigX-y;
end;
OPERATOR -(CONST x,y:T_bigInt):T_bigInt;
begin
if x.negative xor y.negative then
//(-x)-y = -(x+y)
//x-(-y) = x+y
result.createFromRawData(x.negative,rawDataPlus(x.digits,y.digits))
else case x.compareAbsValue(y) of
CR_EQUAL : result.createZero;
CR_LESSER : // x-y = -(y-x) //opposed sign as y
result.createFromRawData(not(y.negative),rawDataMinus(y.digits,x.digits));
CR_GREATER: result.createFromRawData(x.negative ,rawDataMinus(x.digits,y.digits));
end;
end;
OPERATOR *(CONST x:T_bigInt; CONST y:int64):T_bigInt;
VAR bigY:T_bigInt;
begin
bigY.fromInt(y);
result:=x*bigY;
end;
OPERATOR *(CONST x,y:T_bigInt):T_bigInt;
VAR i,j,k:longint;
carry:CarryType=0;
begin
{$ifndef debugMode}
if x.canBeRepresentedAsInt32() then begin
if y.canBeRepresentedAsInt32() then begin
result.fromInt(x.toInt*y.toInt);
exit(result);
end else begin
result.create(y);
result.multWith(x);
exit(result);
end;
end else if y.canBeRepresentedAsInt32() then begin
result.create(x);
result.multWith(y.toInt);
exit(result);
end;
{$endif}
result.create(x.negative xor y.negative,length(x.digits)+length(y.digits));
for k:=0 to length(result.digits)-1 do result.digits[k]:=0;
for i:=0 to length(x.digits)-1 do
for j:=0 to length(y.digits)-1 do begin
k:=i+j;
carry:=CarryType(x.digits[i])*CarryType(y.digits[j]);
while carry>0 do begin
//x[i]*y[i]+r[i] <= (2^n-1)*(2^n-1)+2^n-1
// = (2^n)^2 - 2*2^n + 1 + 2^n-1
// = (2^n)^2 - 2*2^n + 1
// < (2^n)^2 - 2 + 1 = (max value of carry type)
carry+=result.digits[k];
result.digits[k]:=carry and DIGIT_MAX_VALUE;
carry:=carry shr BITS_PER_DIGIT;
inc(k);
end;
end;
trimLeadingZeros(result.digits);
end;
FUNCTION divide (CONST x:T_bigInt; CONST y:int64):T_bigInt;
VAR bigY:T_bigInt;
begin
bigY.fromInt(y);
result:=x.divide(bigY);
end;
FUNCTION divide (CONST x:int64; CONST y:T_bigInt):T_bigInt;
VAR bigX:T_bigInt;
begin
bigX.fromInt(x);
result:=bigX.divide(y);
end;
OPERATOR mod(CONST x:T_bigInt; CONST y:int64):int64;
FUNCTION digitValue(CONST index:longint):int64; inline;
VAR f:int64;
i:longint;
begin
result:=x.digits[index] mod y;
i:=index;
f:=(DIGIT_MAX_VALUE+1) mod y;
while i>0 do begin
if odd(i) then begin
result:=(result * f) mod y;
end;
f:=(f*f) mod y;
i:=i shr 1;
end;
end;
VAR bigY,bigResult,bigQuotient:T_bigInt;
k:longint;
begin
if (y>-3025451648) and (y<3025451648) then begin
result:=0;
for k:=0 to length(x.digits)-1 do result:=(result+digitValue(k)) mod y;
end else begin
bigY.fromInt(y);
x.divMod(bigY,bigQuotient,bigResult);
result:=bigResult.toInt;
end;
end;
FUNCTION modulus(CONST x:int64; CONST y:T_bigInt):T_bigInt;
VAR bigX:T_bigInt;
begin
if y.canBeRepresentedAsInt64() then result.fromInt(x) else begin
bigX.fromInt(x);
result:=bigX.modulus(y);
end;
end;
FUNCTION T_bigInt.isOdd:boolean; begin result:=(length(digits)>0) and odd(digits[0]); end;
PROCEDURE T_bigInt.createFromRawData(CONST negative_:boolean; CONST digits_:DigitTypeArray);
begin
negative :=negative_ and (length(digits_)>0); //no such thing as a negative zero
digits :=digits_;
end;
PROCEDURE T_bigInt.nullBits(CONST numberOfBitsToKeep:longint);
VAR i:longint;
begin
for i:=length(digits)*BITS_PER_DIGIT-1 downto numberOfBitsToKeep do setBit(i,false);
end;
PROCEDURE T_bigInt.shlInc(CONST incFirstBit: boolean);
VAR k:longint;
carryBit:boolean;
nextCarry:boolean;
begin
carryBit:=incFirstBit;
nextCarry:=carryBit;
for k:=0 to length(digits)-1 do begin
nextCarry:=(digits[k] and UPPER_DIGIT_BIT)<>0;
{$R-}
digits[k]:=digits[k] shl 1;
{$R+}
if carryBit then inc(digits[k]);
carryBit:=nextCarry;
end;
if nextCarry then begin
k:=length(digits);
setLength(digits,k+1);
digits[k]:=1;
end;
end;
FUNCTION T_bigInt.relevantBits: longint;
VAR upperDigit:DigitType;
k:longint;
begin
if length(digits)=0 then exit(0);
upperDigit:=digits[length(digits)-1];
result:=BITS_PER_DIGIT*length(digits);
for k:=BITS_PER_DIGIT-1 downto 0 do
if upperDigit<WORD_BIT[k]
then dec (result)
else exit(result);
end;
FUNCTION T_bigInt.getBit(CONST index: longint): boolean;
VAR digitIndex:longint;
bitIndex :longint;
begin
digitIndex:=index div BITS_PER_DIGIT;
if digitIndex>=length(digits) then exit(false);
bitIndex :=index mod BITS_PER_DIGIT;
result:=(digits[digitIndex] and WORD_BIT[bitIndex])<>0;
end;
PROCEDURE T_bigInt.setBit(CONST index: longint; CONST value: boolean);
VAR digitIndex:longint;
bitIndex :longint;
oldLength:longint;
k:longint;
begin
digitIndex:=index div BITS_PER_DIGIT;
bitIndex:=index and (BITS_PER_DIGIT-1);
if value then begin
//setting a true bit means, we might have to increase the number of digits
if (digitIndex>=length(digits)) and value then begin
oldLength:=length(digits);
setLength(digits,digitIndex+1);
for k:=length(digits)-1 downto oldLength do digits[k]:=0;
end;
digits[digitIndex]:=digits[digitIndex] or WORD_BIT[bitIndex];
end else begin
//setting a false bit means, we might have to decrease the number of digits
if digitIndex>=length(digits) then exit;
digits[digitIndex]:=digits[digitIndex] and not(WORD_BIT[bitIndex]);
trimLeadingZeros(digits);
end;
end;
PROCEDURE T_bigInt.createZero;
begin
create(false,0);
end;
PROCEDURE T_bigInt.create(CONST negativeNumber: boolean; CONST digitCount_: longint);
begin
negative:=negativeNumber;
setLength(digits,digitCount_);
end;
PROCEDURE T_bigInt.fromInt(CONST i: int64);
VAR unsigned:int64;
d0,d1:DigitType;
begin
negative:=i<0;
if negative
then unsigned:=-i
else unsigned:= i;
d0:=(unsigned ) and DIGIT_MAX_VALUE;
d1:=(unsigned shr (BITS_PER_DIGIT )) and DIGIT_MAX_VALUE;
if d1=0 then begin
if d0=0
then setLength(digits,0)
else setLength(digits,1);
end else setLength(digits,2);
if length(digits)>0 then digits[0]:=d0;
if length(digits)>1 then digits[1]:=d1;
end;
PROCEDURE T_bigInt.fromString(CONST s: string);
CONST MAX_CHUNK_SIZE=9;
CHUNK_FACTOR:array[1..MAX_CHUNK_SIZE] of longint=(10,100,1000,10000,100000,1000000,10000000,100000000,1000000000);
VAR i:longint=1;
chunkSize:longint;
chunkValue:DigitType;
begin
createZero;
if length(s)=0 then raise Exception.create('Cannot parse empty string');
if s[1]='-' then begin
negative:=true;
inc(i);
end;
while i<=length(s) do begin
chunkSize:=length(s)-i+1;
if chunkSize>MAX_CHUNK_SIZE then chunkSize:=MAX_CHUNK_SIZE;
chunkValue:=strToInt(copy(s,i,chunkSize));
multWith(CHUNK_FACTOR[chunkSize]);
incAbsValue(chunkValue);
inc(i,chunkSize);
end;
end;
PROCEDURE T_bigInt.fromFloat(CONST f: extended; CONST rounding: T_roundingMode);
VAR r:TDoubleRec;
fraction:double;
begin
r.value:=f;
fromInt(r.Mantissa+4503599627370496);
shiftRight(52-r.exponent);
case rounding of
RM_DEFAULT: begin fraction:=frac(abs(f)); if (fraction>0.5) or (fraction=0.5) and getBit(0) then incAbsValue(1); end;
RM_UP : if not(r.sign) and (frac(f)<>0) then incAbsValue(1);
RM_DOWN : if r.sign and (frac(f)<>0) then incAbsValue(1);
end;
negative:=r.sign;
end;
PROCEDURE T_bigInt.create(CONST toClone: T_bigInt);
VAR k:longint;
begin
create(toClone.negative,length(toClone.digits));
for k:=0 to length(digits)-1 do digits[k]:=toClone.digits[k];
end;
PROCEDURE T_bigInt.createFromDigits(CONST base: longint; CONST digits_:T_arrayOfLongint);
VAR i:longint;
begin
createZero;
for i:=0 to length(digits_)-1 do begin
multWith(base);
incAbsValue(digits_[i]);
end;
end;
PROCEDURE T_bigInt.clear;
begin
setLength(digits,0);
end;
FUNCTION newFromBigDigits(CONST digits:T_arrayOfBigint; CONST base:T_bigInt):T_bigInt;
VAR i:longint;
tmp:T_bigInt;
allSmall:boolean;
baseAsInt:longint;
begin
allSmall:=(base.canBeRepresentedAsInt32()) and not(base.negative);
for i:=0 to length(digits)-1 do allSmall:=allSmall and (length(digits[i].digits)<=1) and not(digits[i].negative);
result.createZero;
if allSmall then begin
baseAsInt:=base.toInt;
for i:=0 to length(digits)-1 do begin
result.multWith(baseAsInt);
if length(digits[i].digits)>0 then result.incAbsValue(digits[i].digits[0]);
end;
end else begin
for i:=0 to length(digits)-1 do begin
tmp:=result*base;
result:=tmp + digits[i];
end;
end;
end;
FUNCTION T_bigInt.toInt: int64;
begin
if length(digits)>0 then begin
result:=digits[0];
{$Q-}{$R-}
if length(digits)>1 then inc(result,int64(digits[1]) shl BITS_PER_DIGIT);
if negative then result:=-result;
{$Q+}{$R+}
end else result:=0;
end;
FUNCTION T_bigInt.toFloat: extended;
VAR k:longint;
begin
result:=0;
for k:=length(digits)-1 downto 0 do result:=result*(DIGIT_MAX_VALUE+1)+digits[k];
if negative then result:=-result;
end;
FUNCTION T_bigInt.canBeRepresentedAsInt64(CONST examineNicheCase: boolean): boolean;
begin
if length(digits)*BITS_PER_DIGIT>64 then exit(false);
if length(digits)*BITS_PER_DIGIT<64 then exit(true);
if not(getBit(63)) then exit(true);
if negative and examineNicheCase then begin
//in this case we can still represent -(2^63), so there is one special case to consider:
result:=(digits[1]=UPPER_DIGIT_BIT) and (digits[0]=0);
end else
result:=false;
end;
FUNCTION T_bigInt.canBeRepresentedAsInt62:boolean;
CONST UPPER_TWO_BITS=3 shl (BITS_PER_DIGIT-2);
begin
if length(digits)*BITS_PER_DIGIT>62 then exit(false);
if length(digits)*BITS_PER_DIGIT<62 then exit(true);
result:=digits[1] and UPPER_TWO_BITS=0;
end;
FUNCTION T_bigInt.canBeRepresentedAsInt32(CONST examineNicheCase: boolean): boolean;
begin
if length(digits)*BITS_PER_DIGIT>32 then exit(false);
if length(digits)*BITS_PER_DIGIT<32 then exit(true);
if not(getBit(31)) then exit(true);
if negative and examineNicheCase then begin
//in this case we can still represent -(2^31), so there is one special case to consider:
result:=(digits[0]=UPPER_DIGIT_BIT);
end else
result:=false;
end;
PROCEDURE T_bigInt.flipSign;
begin
negative:=not(negative);
end;
FUNCTION T_bigInt.negated: T_bigInt;
begin
result.create(self);
result.flipSign;
end;
FUNCTION T_bigInt.compareAbsValue(CONST big: T_bigInt): T_comparisonResult;
VAR i:longint;
begin
if length(digits)<length(big.digits) then exit(CR_LESSER);
if length(digits)>length(big.digits) then exit(CR_GREATER);
//compare highest value digits first
for i:=length(digits)-1 downto 0 do begin
if digits[i]<big.digits[i] then exit(CR_LESSER);
if digits[i]>big.digits[i] then exit(CR_GREATER);
end;
result:=CR_EQUAL;
end;
FUNCTION T_bigInt.compareAbsValue(CONST int: int64): T_comparisonResult;
VAR s,i:int64;
begin
if not(canBeRepresentedAsInt64(false)) then exit(CR_GREATER);
s:=toInt; if s<0 then s:=-s;
i:= int; if i<0 then i:=-i;
if s>i then exit(CR_GREATER);
if s<i then exit(CR_LESSER);
result:=CR_EQUAL;
end;
FUNCTION T_bigInt.compare(CONST big: T_bigInt): T_comparisonResult;
begin
if negative and not(big.negative) then exit(CR_LESSER);
if not(negative) and big.negative then exit(CR_GREATER);
if negative then exit(C_FLIPPED[compareAbsValue(big)])
else exit( compareAbsValue(big) );
end;
FUNCTION T_bigInt.compare(CONST int: int64): T_comparisonResult;
VAR s:int64;
begin
if int=0 then begin
if length(digits)=0 then exit(CR_EQUAL)
else if negative then exit(CR_LESSER)
else exit(CR_GREATER);
end;
if not(canBeRepresentedAsInt64) then begin
if negative then exit(CR_LESSER)
else exit(CR_GREATER);
end;
s:=toInt;
if s>int then exit(CR_GREATER);
if s<int then exit(CR_LESSER);
result:=CR_EQUAL;
end;
FUNCTION T_bigInt.compare(CONST f: extended): T_comparisonResult;
VAR unsigned:extended;
fraction:extended;
d:DigitType;
k:longint;
begin
if isNan(f) then exit(CR_INVALID_COMPARAND);
if isInfinite(f) then begin
if f>0 then exit(CR_LESSER)
else exit(CR_GREATER);
end;
if negative and (f>=0) then exit(CR_LESSER);
if not(negative) and (f< 0) then exit(CR_GREATER);
//both have same sign; none is infinite
if negative then unsigned:=-f else unsigned:=f;
fraction:=frac(unsigned);
k:=0;
while unsigned>=1 do begin
inc(k);
unsigned/=(DIGIT_MAX_VALUE+1);
end;
if k>length(digits) then begin
if negative then exit(CR_GREATER)
else exit(CR_LESSER);
end else if k<length(digits) then begin
if negative then exit(CR_LESSER)
else exit(CR_GREATER);
end;
for k:=length(digits)-1 downto 0 do begin
unsigned*=(DIGIT_MAX_VALUE+1);
d:=trunc(unsigned);
if d<digits[k] then begin
if negative then exit(CR_LESSER)
else exit(CR_GREATER);
end else if d>digits[k] then begin
if negative then exit(CR_GREATER)
else exit(CR_LESSER);
end;
unsigned-=d;
end;
// all integer digits are equal; maybe there is a nonzero fraction...
if fraction>0 then begin
if negative then exit(CR_GREATER)
else exit(CR_LESSER);
end;
result:=CR_EQUAL;
end;
FUNCTION T_bigInt.minus(CONST small:DigitType):T_bigInt;
VAR smallAsArray:DigitTypeArray=();
begin
setLength(smallAsArray,1);
smallAsArray[0]:=small;
if negative then
//(-x)-y = -(x+y)
//x-(-y) = x+y
result.createFromRawData(negative,rawDataPlus(digits,smallAsArray))
else case compareAbsValue(small) of
CR_EQUAL : result.createZero;
CR_LESSER : // x-y = -(y-x) //opposed sign as y
result.createFromRawData(true ,rawDataMinus(smallAsArray,digits));
CR_GREATER: result.createFromRawData(false,rawDataMinus(digits,smallAsArray));
end;
end;
FUNCTION T_bigInt.pow(power: dword): T_bigInt;
CONST BASE_THRESHOLD_FOR_EXPONENT:array[2..62] of longint=(maxLongint,2097151,55108,6208,1448,511,234,127,78,52,38,28,22,18,15,13,11,9,8,7,7,6,6,5,5,5,4,4,4,4,3,3,3,3,3,3,3,3,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2);
VAR multiplicand:T_bigInt;
m:int64;
r:int64;
begin
// x ** 0 = 1
if power=0 then begin
result.create(false,1);
result.digits[0]:=1;
exit(result);
end;
// x^1 = x
if power=1 then begin
result.create(self);
exit(result);
end;
if (power<=62) and (compareAbsValue(BASE_THRESHOLD_FOR_EXPONENT[power]) in [CR_EQUAL,CR_LESSER]) then begin
r:=1;
m:=toInt;
{$R-}{$Q-}
while power>0 do begin
if odd(power) then r*=m;
m*=m;
power:=power shr 1;
end;
{$R+}{$Q+}
result.fromInt(r);
end else begin
result.create(false,1); result.digits[0]:=1;
multiplicand.create(self);
while power>0 do begin
if odd(power) then result.multWith(multiplicand);
multiplicand.multWith(multiplicand);
power:=power shr 1;
end;
end;
end;
FUNCTION T_bigInt.powMod(CONST power,modul:T_bigInt):T_bigInt;
PROCEDURE doModulus(VAR inOut:T_bigInt);
VAR temp:T_bigInt;
begin
if inOut.compareAbsValue(modul)=CR_LESSER then exit;
temp:=inOut.modulus(modul);
inOut:=temp;
end;
VAR p,f:T_bigInt;
begin
if (power.isZero) or (power.negative) or
(modul.negative) or (modul.isZero) then begin
result.fromInt(1);
exit(result);
end;
if (power.compare(1)=CR_EQUAL) or (modul.compare(1)=CR_EQUAL) then begin
result:=modulus(modul);
exit(result);
end;
p.create(power);
f:=modulus(modul);
result.fromInt(1);
while not(p.isZero) do begin
if p.getBit(0) then begin
result.multWith(f); doModulus(result);
end;
f.multWith(f); doModulus(f);
p.shiftRightOneBit;
end;
end;
FUNCTION T_bigInt.bitAnd(CONST big: T_bigInt): T_bigInt;
VAR k,i:longint;
begin
k:=min(length(digits),length(big.digits));
result.create(isNegative and big.isNegative,k);
for i:=0 to length(result.digits)-1 do result.digits[i]:=digits[i] and big.digits[i];
trimLeadingZeros(result.digits);
end;
FUNCTION T_bigInt.bitOr(CONST big: T_bigInt): T_bigInt;
VAR k,i:longint;
begin
k:=max(length(digits),length(big.digits));
result.create(isNegative or big.isNegative,k);
for i:=0 to length(result.digits)-1 do begin
if (i< length(digits)) then result.digits[i]:=digits[i]
else result.digits[i]:=0;
if (i<length(big.digits)) then result.digits[i]:=result.digits[i] or big.digits[i];
end;
trimLeadingZeros(result.digits);
end;
FUNCTION T_bigInt.bitXor(CONST big: T_bigInt): T_bigInt;
VAR k,i:longint;
begin
k:=max(length(digits),length(big.digits));
result.create(isNegative xor big.isNegative,k);
for i:=0 to length(result.digits)-1 do begin
if (i< length(digits)) then result.digits[i]:=digits[i]
else result.digits[i]:=0;
if (i<length(big.digits)) then result.digits[i]:=result.digits[i] xor big.digits[i];
end;
trimLeadingZeros(result.digits);
end;
FUNCTION T_bigInt.bitAnd(CONST small:int64): T_bigInt; VAR big:T_bigInt; begin big.fromInt(small); result:=bitAnd(big); end;
FUNCTION T_bigInt.bitOr (CONST small:int64): T_bigInt; VAR big:T_bigInt; begin big.fromInt(small); result:=bitOr (big); end;
FUNCTION T_bigInt.bitXor(CONST small:int64): T_bigInt; VAR big:T_bigInt; begin big.fromInt(small); result:=bitXor(big); end;
FUNCTION T_bigInt.bitNegate(CONST consideredBits:longint):T_bigInt;
VAR k,i:longint;
begin
if consideredBits<=0 then k:=relevantBits
else k:=consideredBits;
result.create(false,length(digits));
for i:=0 to min(length(digits),length(result.digits))-1 do result.digits[i]:=not(digits[i]);
result.nullBits(k);
end;
FUNCTION isPowerOf2(CONST i:DigitType; OUT log2:longint):boolean; inline;
VAR k:longint;
begin
result:=false;
for k:=0 to length(WORD_BIT)-1 do if i=WORD_BIT[k] then begin
log2:=k;
exit(true);
end;
end;
PROCEDURE T_bigInt.multWith(CONST l: longint);
VAR carry:CarryType=0;
factor:DigitType;
i:longint;
k:longint;
begin
if l=0 then begin
setLength(digits,0);
negative:=false;
exit;
end;
if l<0 then begin
factor:=-l;
negative:=not(negative);
end else factor:=l;
if isPowerOf2(factor,k) then begin
shiftRight(-k);
exit;
end;
for k:=0 to length(digits)-1 do begin
carry+=CarryType(factor)*CarryType(digits[k]);
digits[k]:=carry and DIGIT_MAX_VALUE;
carry:=carry shr BITS_PER_DIGIT;
end;
if carry>0 then begin
k:=length(digits)+1;
//need to grow... but how much ?
if carry shr BITS_PER_DIGIT>0 then begin
inc(k);
if carry shr (2*BITS_PER_DIGIT)>0 then inc(k);
end;
i:=length(digits);
setLength(digits,k);
while i<k do begin
digits[i]:=carry and DIGIT_MAX_VALUE;
carry:=carry shr BITS_PER_DIGIT;
inc(i);
end;
end;
end;
PROCEDURE T_bigInt.multWith(CONST b: T_bigInt);
VAR temp:T_bigInt;
begin
temp :=self*b;
setLength(digits,0);
digits :=temp.digits;
negative :=temp.negative;
end;
PROCEDURE T_bigInt.incAbsValue(CONST positiveIncrement: DigitType);
VAR carry:CarryType;
k:longint;
begin
carry:=positiveIncrement;
k:=0;
while carry>0 do begin
if k>=length(digits) then begin
setLength(digits,length(digits)+1);
digits[k]:=0;
end;
carry+=digits[k];
digits[k]:=carry and DIGIT_MAX_VALUE;
carry:=carry shr BITS_PER_DIGIT;
inc(k);
end;
end;
FUNCTION T_bigInt.divMod(CONST divisor: T_bigInt; OUT quotient, rest: T_bigInt): boolean;
PROCEDURE rawDec; inline;
VAR carry:CarryType=0;
i :longint;
begin
for i:=0 to length(divisor.digits)-1 do begin
carry+=divisor.digits[i];
if carry>rest.digits[i] then begin
rest.digits[i]:=((DIGIT_MAX_VALUE+1)-carry+rest.digits[i]) and DIGIT_MAX_VALUE;
carry:=1;
end else begin
rest.digits[i]-=carry;
carry:=0;
end;
end;
for i:=length(divisor.digits) to length(rest.digits)-1 do begin
if carry>rest.digits[i] then begin
rest.digits[i]:=((DIGIT_MAX_VALUE+1)-carry+rest.digits[i]) and DIGIT_MAX_VALUE;
carry:=1;
end else begin
rest.digits[i]-=carry;
carry:=0;
end;
end;
end;
FUNCTION restGeqDivisor:boolean; inline;
VAR i:longint;
begin
if length(divisor.digits)>length(rest.digits) then exit(false);
for i:=length(rest.digits)-1 downto length(divisor.digits) do if rest.digits[i]>0 then exit(true);
for i:=length(divisor.digits)-1 downto 0 do
if divisor.digits[i]<rest.digits[i] then exit(true)
else if divisor.digits[i]>rest.digits[i] then exit(false);
result:=true;
end;
VAR bitIdx:longint;
divIsPow2:boolean;
begin
if length(divisor.digits)=0 then exit(false);
bitIdx:=divisor.iLog2(divIsPow2);
if divIsPow2 then begin
rest.create(self);
rest.nullBits(bitIdx);
quotient.create(self);
quotient.shiftRight(bitIdx);