/
BigInt.java
2584 lines (2471 loc) · 64.5 KB
/
BigInt.java
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
package org.huldra.math;
/*
Copyright (c) 2015-2016 The Huldra Project.
See the LICENSE file for too long unnecessary boring license bullshit that otherwise would be written here.
Tl;dr: Use this possibly broken code however you like.
Representation:
Base is 2^32.
Magnitude as array in little endian order.
The len first ints count as the number.
Sign is represented by a sign int (-1 or 1).
Internally zero is allowed to have either sign. (Otherwise one would have to remember to check for sign-swap for div/mul etc...)
Zero has length 1 and dig[0]==0.
Principle: No Exceptions.
If a programmer divides by zero he has only himself to blame. It is OK to have undefined behavior.
Beware:
Nothing should be assumed about a position of the internal array that is not part of the number, e.g. that it is 0.
Beware of signed extensions!
Organization: Locality of reference
Stuff that has something in common should generally be close to oneanother in the code.
So stuff regarding multiplication is bunched together.
Coding style: Klein / As long as it looks good
Generally brackets on new line, but exception can be made for small special cases, then they may be aligned on the same line.
Never space after for or if or akin, it looks ugly.
Bracketless loops may be on one line. For nested bracketless loops each should be indented on a new line.
*/
import java.math.BigInteger;
import java.util.*;
import java.io.*;
import java.util.concurrent.*;
//import java.math.BigInteger;
/**
* <p>A class for arbitrary-precision integer arithmetic purely written in Java.</p>
* <p>This class does what {@link java.math.BigInteger} doesn't.<br />
* It is <b>faster</b>, and it is <b>mutable</b>!<br />
* It supports <b>ints</b> and <b>longs</b> as parameters!<br />
* It has a way faster {@link #toString()} method!<br />
* It utilizes a faster multiplication algorithm for those nasty big numbers!</p>
*
* <p>Get it today! Because performance matters (and we like Java).</p>
*
* @author Simon Klein
* @version 0.7
*/
public class BigInt extends Number implements Comparable<BigInt>
{
/**
* Used to cast a (base 2^32) digit to a long without getting unwanted sign extension.
*/
private static final long mask = (1L<<32) - 1;
/**
* The sign of this number.
* 1 for positive numbers and -1 for negative numbers.
* Zero can have either sign.
*/
private int sign;
/**
* The number of digits of the number (in base 2^32).
*/
private int len;
/**
* The digits of the number, i.e., the magnitude array.
*/
private int[] dig;
/*** <Constructors> ***/
/**
* Creates a BigInt from the given parameters.
* The input-array will be used as is and not be copied.
*
* @param sign The sign of the number.
* @param v The magnitude of the number, the first position gives the least significant 32 bits.
* @param len The (first) number of entries of v that are considered part of the number.
* @complexity O(1)
*/
public BigInt(final int sign, final int[] v, final int len)
{
assign(sign,v,len);
}
/**
* Creates a BigInt from the given parameters.
* The contents of the input-array will be copied.
*
* @param sign The sign of the number.
* @param v The magnitude of the number, the first position gives the least significant 8 bits.
* @param len The (first) number of entries of v that are considered part of the number.
* @complexity O(n)
*/
public BigInt(final int sign, final byte[] v, int vlen)
{
while(vlen>1 && v[vlen-1]==0) --vlen;
dig = new int[(vlen+3)/4];
assign(sign,v,vlen);
}
/**
* Creates a BigInt from the given parameters.
* The input-value will be interpreted as unsigned.
*
* @param sign The sign of the number.
* @param val The magnitude of the number.
* @complexity O(1)
*/
public BigInt(final int sign, final int val)
{
dig = new int[1];
uassign(sign,val);
}
/**
* Creates a BigInt from the given parameters.
* The input-value will be interpreted as unsigned.
*
* @param sign The sign of the number.
* @param val The magnitude of the number.
* @complexity O(1)
*/
public BigInt(final int sign, final long val)
{
dig = new int[2];
uassign(sign,val);
}
/**
* Creates a BigInt from the given int.
* The input-value will be interpreted a signed value.
*
* @param val The value of the number.
* @complexity O(1)
*/
public BigInt(final int val)
{
dig = new int[1];
assign(val);
}
/**
* Creates a BigInt from the given long.
* The input-value will be interpreted a signed value.
*
* @param val The value of the number.
* @complexity O(1)
*/
public BigInt(final long val)
{
dig = new int[2];
assign(val);
}
/**
* Creates a BigInt from the given string.
*
* @param s A string representing the number in decimal.
* @complexity O(n^2)
*/
public BigInt(final String s)
{
assign(s);
}
/**
* Creates a BigInt from the given char-array.
*
* @param s A char array representing the number in decimal.
* @complexity O(n^2)
*/
public BigInt(final char[] s)
{
assign(s);
}
/*** </Constructors> ***/
/*** <General Helper> ***/
/**
* Parses a part of a char array as an unsigned decimal number.
*
* @param s A char array representing the number in decimal.
* @param from The index (inclusive) where we start parsing.
* @param to The index (exclusive) where we stop parsing.
* @return The parsed number.
* @complexity O(n)
*/
private int parse(final char[] s, int from, final int to)
{
int res = s[from]-'0';
while(++from<to) res = res*10 + s[from]-'0';
return res;
}
/**
* Multiplies this number and then adds something to it.
* I.e. sets this = this*mul + add.
*
* @param mul The value we multiply our number with, mul < 2^31.
* @param add The value we add to our number, add < 2^31.
* @complexity O(n)
*/
private void mulAdd(final int mul, final int add)
{
long carry = 0;
for(int i = 0; i<len; i++)
{
carry = mul * (dig[i]&mask) + carry;
dig[i] = (int)carry;
carry >>>= 32;
}
if(carry!=0) dig[len++] = (int)carry;
carry = (dig[0]&mask) + add;
dig[0] = (int)carry;
if((carry >>> 32)!=0)
{
int i = 1;
for(; i<len && ++dig[i]==0; ++i);
if(i==len) dig[len++] = 1; //Todo: realloc() for general case?
}
}
/**
* Reallocates the magnitude array to one twice its size.
*
* @complexity O(n)
*/
private void realloc()
{
final int[] res = new int[dig.length*2];
System.arraycopy(dig,0,res,0,len);
dig = res;
}
/**
* Reallocates the magnitude array to one of the given size.
*
* @param newLen The new size of the magnitude array.
* @complexity O(n)
*/
private void realloc(final int newLen)
{
final int[] res = new int[newLen];
System.arraycopy(dig,0,res,0,len);
dig = res;
}
/*** </General Helper> ***/
/*** <General functions> ***/
/**
* Creates a copy of this number.
*
* @return The BigInt copy.
* @complexity O(n)
*/
public BigInt copy()
{
return new BigInt(sign, Arrays.copyOf(dig,len), len);
}
/**
* Assigns the given number to this BigInt object.
*
* @param The BigInt to copy/assign to this BigInt.
* @complexity O(n)
*/
public void assign(final BigInt other)
{
sign = other.sign;
assign(other.dig, other.len);
}
/**
* Assigns the content of the given magnitude array and the length to this number.
* The contents of the input will be copied.
*
* @param v The new magnitude array content.
* @param vlen The length of the content, vlen > 0.
* @complexity O(n)
*/
private void assign(final int[] v, final int vlen) //Todo: Better and more consistent naming.
{
if(vlen>dig.length) dig = new int[vlen+2];
System.arraycopy(v,0,dig,0,len=vlen);
}
/**
* Assigns the given BigInt parameter to this number.
* The input magnitude array will be used as is and not copied.
*
* @param sign The sign of the number.
* @param v The magnitude of the number.
* @param len The length of the magnitude array to be used.
* @complexity O(1)
*/
public void assign(final int sign, final int[] v, final int len)
{
this.sign = sign; this.len = len;
dig = v;
}
/**
* Assigns the given BigInt parameter to this number.
* Assumes no leading zeroes of the input-array, i.e. that v[vlen-1]!=0, except for the case when vlen==1.
*
* @param sign The sign of the number.
* @param v The magnitude of the number.
* @param vlen The length of the magnitude array to be used.
* @complexity O(n)
*/
public void assign(final int sign, final byte[] v, final int vlen)
{
len = (vlen+3)/4;
if(len>dig.length) dig = new int[len+2];
this.sign = sign;
int tmp = vlen/4, j = 0;
for(int i = 0; i<tmp; i++, j+=4) dig[i] = v[j+3]<<24|(v[j+2]&0xFF)<<16|(v[j+1]&0xFF)<<8|v[j]&0xFF;
if(tmp!=len)
{
tmp = v[j++]&0xFF;
if(j<vlen)
{
tmp |= (v[j++]&0xFF)<<8;
if(j<vlen) tmp |= (v[j]&0xFF)<<16;
}
dig[len-1] = tmp;
}
}
/**
* Assigns the given number to this BigInt object.
*
* @param s A string representing the number in decimal.
* @complexity O(n^2)
*/
public void assign(final String s)
{
assign(s.toCharArray());
}
/**
* Assigns the given number to this BigInt object.
*
* @param s A char array representing the number in decimal.
* @complexity O(n^2)
*/
public void assign(final char[] s)
{
sign = s[0]=='-' ? -1 : 1;
len = s.length + (sign-1>>1);
final int alloc = len<10 ? 1 : (int)(len*3402L >>> 10) + 32 >>> 5; //3402 = bits per digit * 1024
if(dig==null || alloc>dig.length) dig = new int[alloc];
int j = len%9;
if(j==0) j = 9;
j -= (sign-1>>1);
dig[0] = parse(s, 0-(sign-1>>1), j);
for(len = 1; j<s.length;)
mulAdd(1_000_000_000, parse(s,j,j+=9));
}
/**
* Assigns the given number to this BigInt object.
*
* @param s The sign of the number.
* @param val The magnitude of the number (will be intepreted as unsigned).
* @complexity O(1)
*/
public void uassign(final int s, final int val)
{
sign = s;
len = 1;
dig[0] = val;
}
/**
* Assigns the given number to this BigInt object.
*
* @param s The sign of the number.
* @param val The magnitude of the number (will be intepreted as unsigned).
* @complexity O(1)
*/
public void uassign(final int s, final long val)
{
sign = s;
if(dig.length<2) realloc(2);
len = 2;
dig[0] = (int)(val&mask);
dig[1] = (int)(val>>>32);
if(dig[1]==0) --len;
}
/**
* Assigns the given non-negative number to this BigInt object.
*
* @param val The number interpreted as unsigned.
* @complexity O(1)
*/
public void uassign(final int val)
{
uassign(1, val);
}
/**
* Assigns the given non-negative number to this BigInt object.
*
* @param val The number interpreted as unsigned.
* @complexity O(1)
*/
public void uassign(final long val)
{
uassign(1, val);
}
/**
* Assigns the given number to this BigInt object.
*
* @param val The number to be assigned.
* @complexity O(1)
*/
public void assign(final int val)
{
uassign(val<0 ? -1 : 1, val<0 ? -val : val);
}
/**
* Assigns the given number to this BigInt object.
*
* @param val The number to be assigned.
* @complexity O(1)
*/
public void assign(final long val)
{
uassign(val<0 ? -1 : 1, val<0 ? -val : val);
}
/**
* Tells whether this number is zero or not.
*
* @return true if this number is zero, false otherwise
* @complexity O(1)
*/
public boolean isZero()
{
return len==1 && dig[0]==0;
}
/**
* Sets this number to zero.
*
* @complexity O(1)
*/
private void setToZero()
{
dig[0] = 0;
len = 1; sign = 1; //Remove?
}
/**
* Compares the absolute value of this and the given number.
*
* @param a The number to be compared with.
* @return -1 if the absolute value of this number is less, 0 if it's equal, 1 if it's greater.
* @complexity O(n)
*/
public int compareAbsTo(final BigInt a)
{
if(len>a.len) return 1;
if(len<a.len) return -1;
for(int i = len-1; i>=0; i--)
if(dig[i]!=a.dig[i])
if((dig[i]&mask)>(a.dig[i]&mask)) return 1;
else return -1;
return 0;
}
/**
* Compares the value of this and the given number.
*
* @param a The number to be compared with.
* @return -1 if the value of this number is less, 0 if it's equal, 1 if it's greater.
* @complexity O(n)
*/
public int compareTo(final BigInt a)
{
if(sign<0)
{
if(a.sign<0 || a.isZero()) return -compareAbsTo(a);
return -1;
}
if(a.sign>0 || a.isZero()) return compareAbsTo(a);
return 1;
}
/**
* Tests equality of this number and the given one.
*
* @param a The number to be compared with.
* @return true if the two numbers are equal, false otherwise.
* @complexity O(n)
*/
public boolean equals(final BigInt a)
{
if(len!=a.len) return false;
if(isZero() && a.isZero()) return true;
if((sign^a.sign)<0) return false; //In case definition of sign would change...
for(int i = 0; i<len; i++) if(dig[i]!=a.dig[i]) return false;
return true;
}
/** {@inheritDoc}
*/
@Override
public boolean equals(final Object o) //Todo: Equality on other Number objects?
{
if(o instanceof BigInt) return equals((BigInt)o);
return false;
}
/** {@inheritDoc}
*/
@Override
public int hashCode()
{
int hash = 0; //Todo: Opt and improve.
for(int i = 0; i<len; i++) hash = (int)(31*hash + (dig[i]&mask));
return sign*hash; //relies on 0 --> hash==0.
}
/*** </General functions> ***/
/*** <Number Override> ***/
/** {@inheritDoc}
* Returns this BigInt as a {@code byte}.
*
* @return {@code sign * (this & 0x7F)}
*/
@Override
public byte byteValue()
{
return (byte)(sign*(dig[0]&0x7F));
}
/** {@inheritDoc}
* Returns this BigInt as a {@code short}.
*
* @return {@code sign * (this & 0x7FFF)}
*/
@Override
public short shortValue()
{
return (short)(sign*(dig[0]&0x7FFF));
}
/** {@inheritDoc}
* Returns this BigInt as an {@code int}.
*
* @return {@code sign * (this & 0x7FFFFFFF)}
*/
@Override
public int intValue()
{
return sign*(dig[0]&0x7FFFFFFF); //relies on that sign always is either 1/-1.
}
/** {@inheritDoc}
* Returns this BigInt as a {@code long}.
*
* @return {@code sign * (this & 0x7FFFFFFFFFFFFFFF)}
*/
@Override
public long longValue()
{
return len==1 ? sign*(dig[0]&mask) : sign*((dig[1]&0x7FFFFFFFL)<<32|(dig[0]&mask));
}
/** {@inheritDoc}
* Returns this BigInt as a {@code float}.
*
* @return the most significant 24 bits in the mantissa (the highest order bit obviously being implicit),
* the exponent value which will be consistent for {@code BigInt}s up to 128 bits (should it not fit it'll be calculated modulo 256),
* and the sign bit set if this number is negative.
*/
@Override
public float floatValue()
{
final int s = Integer.numberOfLeadingZeros(dig[len-1]);
if(len==1 && s>=8) return sign*dig[0];
int bits = dig[len-1]; //Mask out the 24 MSBits.
if(s<=8) bits >>>= 8-s;
else bits = bits<<s-8 | dig[len-2]>>>32-(s-8); //s-8==additional bits we need.
bits ^= 1L<<23; //The leading bit is implicit, cancel it out.
final int exp = (int)(((32-s + 32L*(len-1)) - 1 + 127)&0xFF);
bits |= exp<<23; //Add exponent.
bits |= sign&(1<<31); //Add sign-bit.
return Float.intBitsToFloat(bits);
}
/** {@inheritDoc}
* Returns this BigInt as a {@code double}.
*
* @return the most significant 53 bits in the mantissa (the highest order bit obviously being implicit),
* the exponent value which will be consistent for {@code BigInt}s up to 1024 bits (should it not fit it'll be calculated modulo 2048),
* and the sign bit set if this number is negative.
*/
@Override
public double doubleValue()
{
if(len==1) return sign*(dig[0]&mask);
final int s = Integer.numberOfLeadingZeros(dig[len-1]);
if(len==2 && 32-s+32<=53) return sign*((long)dig[1]<<32|(dig[0]&mask));
long bits = (long)dig[len-1]<<32 | (dig[len-2]&mask); //Mask out the 53 MSBits.
if(s<=11) bits >>>= 11-s;
else bits = bits<<s-11 | dig[len-3]>>>32-(s-11); //s-11==additional bits we need.
bits ^= 1L<<52; //The leading bit is implicit, cancel it out.
final long exp = ((32-s + 32L*(len-1)) - 1 + 1023)&0x7FF;
bits |= exp<<52; //Add exponent.
bits |= (long)sign&(1L<<63); //Add sign-bit.
return Double.longBitsToDouble(bits);
}
/*** </Number Override> ***/
/*** <Unsigned Int Num> ***/
/**
* Increases the magnitude of this number.
*
* @param a The amount of the increase (treated as unsigned).
* @complexity O(n)
* @amortized O(1)
*/
private void uaddMag(final int a)
{
long tmp = (dig[0]&mask) + (a&mask);
dig[0] = (int)tmp;
if((tmp>>>32)!=0)
{
int i = 1;
for(; i<len && ++dig[i]==0; i++);
if(i==len)
{
if(len==dig.length) realloc();
dig[len++] = 1;
}
}
}
/**
* Decreases the magnitude of this number.
* If s > this behaviour is undefined.
*
* @param s The amount of the decrease (treated as unsigned).
* @complexity O(n)
* @amortized O(1)
*/
private void usubMag(final int s)
{
long dif = (dig[0]&mask) - (s&mask);
dig[0] = (int)dif;
if((dif>>32)!=0)
{
int i = 1;
for(; dig[i]==0; i++) --dig[i];
if(--dig[i]==0 && i+1==len) --len;
}
}
/**
* Adds an unsigned int to this number.
*
* @param a The amount to add (treated as unsigned).
* @complexity O(n)
* @amortized O(1)
*/
public void uadd(final int a)
{
if(sign<0)
{
if(len>1 || (dig[0]&mask)>(a&mask)){ usubMag(a); return; }
sign = 1;
dig[0] = a-dig[0]; return;
}
uaddMag(a);
}
/**
* Subtracts an unsigned int from this number.
*
* @param s The amount to subtract (treated as unsigned).
* @complexity O(n)
* @amortized O(1)
*/
public void usub(final int s)
{
if(sign<0)
{
uaddMag(s);
return;
}
if(len==1 && (dig[0]&mask)<(s&mask)){ sign = -1; dig[0] = s-dig[0]; return; }
usubMag(s);
}
/**
* Multiplies this number with an unsigned int.
*
* @param mul The amount to multiply (treated as unsigned).
* @complexity O(n)
*/
public void umul(final int mul) //mul is interpreted as unsigned
{
if(mul==0){ setToZero(); return; } //To be removed?
long carry = 0; final long m = mul&mask;
for(int i = 0; i<len; i++)
{
carry = (dig[i]&mask)*m + carry;
dig[i] = (int)carry;
carry >>>= 32;
}
if(carry!=0)
{
if(len==dig.length) realloc();
dig[len++] = (int)carry;
}
}
/**
* Divides this number with an unsigned int and returns the remainder.
*
* @param div The amount to divide with (treated as unsigned).
* @return The absolute value of the remainder as an unsigned int.
* @complexity O(n)
*/
public int udiv(final int div) //returns the unsigned remainder!
{
if(div<0) return safeUdiv(div);
else return unsafeUdiv(div);
}
// Assumes div > 0.
private int unsafeUdiv(final int div)
{
final long d = div&mask;
long rem = 0;
for(int i = len-1; i>=0; i--)
{
rem <<= 32;
rem = rem + (dig[i]&mask);
dig[i] = (int)(rem/d); //Todo: opt?
rem = rem%d;
}
if(dig[len-1]==0 && len>1) --len;
if(len==1 && dig[0]==0) sign = 1;
return (int)rem;
}
// Assumes div < 0.
private int safeUdiv(final int div)
{
final long d = div&mask, hbit = Long.MIN_VALUE;
long hq = (hbit-1)/d;
if(hq*d + d == hbit) ++hq;
final long hrem = hbit - hq*d;
long rem = 0;
for(int i = len-1; i>=0; i--)
{
rem = (rem<<32) + (dig[i]&mask);
final long q = (hq&rem>>63) + ((rem&hbit-1) + (hrem&rem>>63))/d;
rem = rem - q*d;
dig[i] = (int)q;
}
if(dig[len-1]==0 && len>1) --len;
if(len==1 && dig[0]==0) sign = 1;
return (int)rem;
}
/**
* Modulos this number with an unsigned int.
* I.e. sets this number to this % mod.
*
* @param mod The amount to modulo with (treated as unsigned).
* @complexity O(n)
*/
public void urem(final int mod)
{
if(mod<0) safeUrem(mod);
else unsafeUrem(mod);
}
// Assumes mod > 0.
private void unsafeUrem(final int mod)
{
long rem = 0, d = mod&mask;
for(int i = len-1; i>=0; i--)
{
rem <<= 32;
rem = (rem + (dig[i]&mask))%d;
}
len = 1;
dig[0] = (int)rem;
if(dig[0]==0) sign = 1;
}
// Assumes mod < 0.
private void safeUrem(final int mod)
{
final long d = mod&mask, hbit = Long.MIN_VALUE;
// Precompute hrem = (1<<63) % d
// I.e. the remainder caused by the highest bit.
long hrem = (hbit-1)%d;
if(++hrem==d) hrem = 0;
long rem = 0;
for(int i = len-1; i>=0; i--)
{
rem = (rem<<32) + (dig[i]&mask);
// Calculate rem %= d.
// Do this by calculating the lower 63 bits and highest bit separately.
// The highest bit remainder only gets added if it's set.
rem = ((rem&hbit-1) + (hrem&rem>>63))%d;
// The addition is safe and cannot overflow.
// Because hrem < 2^32 and there's at least one zero bit in [62,32] if bit 63 is set.
}
len = 1;
dig[0] = (int)rem;
if(dig[0]==0) sign = 1;
}
/*** </Unsigned Int Num> ***/
/*** <Unsigned Long Num> ***/
/**
* Increases the magnitude of this number.
*
* @param a The amount of the increase (treated as unsigned).
* @complexity O(n)
* @amortized O(1)
*/
private void uaddMag(final long a)
{
if(dig.length<=2){ realloc(3); len = 2; }
final long ah = a>>>32, al = a&mask;
long carry = (dig[0]&mask) + al;
dig[0] = (int)carry;
carry >>>= 32;
carry = (dig[1]&mask) + ah + carry;
dig[1] = (int)carry;
if(len==1 && dig[1]!=0) len=2; // KL(m) change (new line)
if((carry>>32)!=0)
{
int i = 2;
for(; i<len && ++dig[i]==0; i++);
if(i==len)
{
if(len==dig.length) realloc();
dig[len++] = 1;
}
}
else if(len==2 && dig[1]==0) --len;
}
/**
* Decreases the magnitude of this number.
* If s > this behaviour is undefined.
*
* @param s The amount of the decrease (treated as unsigned).
* @complexity O(n)
* @amortized O(1)
*/
private void usubMag(final long s)
{
final long sh = s>>>32, sl = s&mask;
long dif = (dig[0]&mask) - sl;
dig[0] = (int)dif;
dif >>= 32;
dif = (dig[1]&mask) - sh + dif;
dig[1] = (int)dif;
if((dif>>32)!=0)
{
int i = 2;
for(; dig[i]==0; i++) --dig[i];
if(--dig[i]==0 && i+1==len) --len;
}
if(len==2 && dig[1]==0) --len;
}
/**
* Adds an unsigned long to this number.
*
* @param a The amount to add (treated as unsigned).
* @complexity O(n)
* @amortized O(1)
*/
public void uadd(final long a) //Refactor? Similar to usub.
{
if(sign<0)
{
final long ah = a>>>32, al = a&mask;
if(len>2 || len==2&&((dig[1]&mask)>ah || (dig[1]&mask)==ah&&(dig[0]&mask)>=al) || ah==0&&(dig[0]&mask)>=al)
{
usubMag(a); return;
}
if(dig.length==1) realloc(2);
if(len==1) dig[len++] = 0;
long dif = al - (dig[0]&mask);
dig[0] = (int)dif;
dif >>= 32;
dif = ah - (dig[1]&mask) + dif;
dig[1] = (int)dif;
//dif>>32 != 0 should be impossible
if(dif==0) --len;
sign = 1;
}
else uaddMag(a);
}
/**
* Subtracts an unsigned long from this number.
*
* @param a The amount to subtract (treated as unsigned).
* @complexity O(n)
* @amortized O(1)
*/
public void usub(final long a) //Fix parameter name
{
if(sign>0)
{
final long ah = a>>>32, al = a&mask;
if(len>2 || len==2&&((dig[1]&mask)>ah || (dig[1]&mask)==ah&&(dig[0]&mask)>=al) || ah==0&&(dig[0]&mask)>=al)
{
usubMag(a); return;
}
if(dig.length==1) realloc(2);
if(len==1) dig[len++] = 0;
long dif = al - (dig[0]&mask);
dig[0] = (int)dif;
dif >>= 32;
dif = ah - (dig[1]&mask) + dif;
dig[1] = (int)dif;
//dif>>32 != 0 should be impossible
if(dif==0) --len;
sign = -1;
}
else uaddMag(a);
}
/**
* Multiplies this number with an unsigned long.
*
* @param mul The amount to multiply (treated as unsigned).
* @complexity O(n)
*/
public void umul(final long mul)
{
if(mul==0){ setToZero(); return; }
if(len+2>=dig.length) realloc(2*len+1);
final long mh = mul>>>32, ml = mul&mask;
long carry = 0, next = 0, tmp;
for(int i = 0; i<len; i++)
{
carry = carry + next; //Could this overflow?
tmp = (dig[i]&mask)*ml;
next = (dig[i]&mask)*mh;
dig[i] = (int)(tmp + carry);
carry = (tmp>>>32)+(carry>>>32) + ((tmp&mask)+(carry&mask)>>>32);
}
carry = carry+next;
dig[len++] = (int)carry;
dig[len++] = (int)(carry>>>32);
while(len>1 && dig[len-1]==0) --len;
}
/**
* Divides this number with an unsigned long and returns the remainder.
*
* @param div The amount to divide with (treated as unsigned).
* @return The absolute value of the remainder as an unsigned long.
* @complexity O(n)
*/
public long udiv(final long div) //Adaption of general div to long.
{
if(div==(div&mask)) return udiv((int)div)&mask;
if(len==1)
{
final long tmp = dig[0]&mask;
setToZero();
return tmp;
}
final int s = Integer.numberOfLeadingZeros((int)(div>>>32));
final long dh = div>>>32-s, dl = (div<<s)&mask, hbit = Long.MIN_VALUE;
long u2 = 0, u1 = dig[len-1]>>>32-s, u0 = (dig[len-1]<<s | dig[len-2]>>>32-s)&mask;
if(s==0){ u1 = 0; u0 = dig[len-1]&mask; }
for(int j = len-2; j>=0; j--)
{
u2 = u1; u1 = u0; u0 = s>0&&j>0 ? (dig[j]<<s | dig[j-1]>>>32-s)&mask : (dig[j]<<s)&mask;
long k = (u2<<32) + u1; //Unsigned division is a pain in the ass! ='(
long qhat = (k >>> 1)/dh << 1;
long t = k - qhat*dh;
if(t + hbit >= dh + hbit) qhat++; // qhat = (u[j+n]*b + u[j+n-1])/v[n-1];
long rhat = k - qhat*dh;
while(qhat+hbit >= (1L<<32)+hbit || qhat*dl+hbit > (rhat<<32)+u0+hbit) //Unsigned comparison.
{
--qhat;
rhat = rhat + dh;
if(rhat+hbit >= (1L<<32)+hbit) break;
}
// Multiply and subtract. Unfolded loop.
long p = qhat*dl;
t = u0 - (p&mask);
u0 = t&mask;
k = (p>>>32) - (t>>32);
p = qhat*dh;
t = u1 - k - (p&mask);
u1 = t&mask;
k = (p>>>32) - (t>>32);
t = u2 - k;
u2 = t&mask;
dig[j] = (int)qhat; // Store quotient digit. If we subtracted too much, add back.
if(t<0)
{
--dig[j]; //Unfolded loop.
t = u0 + dl;
u0 = t&mask;
t >>>= 32;
t = u1 + dh + t;
u1 = t&mask;
t >>>= 32;
u2 += t&mask;