-
Notifications
You must be signed in to change notification settings - Fork 106
/
Copy pathbigint_nonjs.mbt
1877 lines (1807 loc) · 50.9 KB
/
bigint_nonjs.mbt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2025 International Digital Economy Academy
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
///|
/// A big integer represented as an array of Int.
//
// Design explained:
// - Why use an FixedArray of Int with a len field instead of a Array[Int]?
// - It follows the principle of least dependency in MoonBit's core.
// - In our case, we always do one-off array allocation for each BigInt.
// - Why keep a separate len field instead of using limbs.length()?
// - Since we always do only once array allocation for each BigInt, we
// often need to estimate the number of limbs needed before allocating.
// Using len allows us to accommodate leading zeros.
//
// Invariants:
// - len > 0
// - forall 0 <= i < len. 0 <= limbs[i] < radix
// - (exists 0 <= i < len. limbs[i] > 0) => limbs[len-1] > 0
// - (forall 0 <= i < len. limbs[i] == 0) => limbs[0] == 0 and len == 1
// - forall len <= i < limbs.length(). limbs[i] == 0
struct BigInt {
limbs : FixedArray[UInt] // Note: do not use limbs.length(), use len instead because of leading zeros
sign : Sign // true for positive, false for negative
len : Int
}
///|
priv enum Sign {
Positive
Negative
} derive(Show, Eq)
// Hyper Params
///|
/// Invariants:
/// - ((radix - 1) ^ 2) must fit in an Int64
/// - radix can only be a power of 2
/// - radix_bit_len is multiple of 4
/// - radix_bit_len <= 32
let radix_bit_len = 32
///|
/// The base of the number system.
let radix : UInt64 = 1UL << radix_bit_len // TODO: This can be generalized once we have const generics
///|
/// The mask to extract the lower `radix_bit_len` bits.
let radix_mask : UInt64 = radix - 1
///|
/// The ratio of the number of decimal digits to the number of radix digits.
let decimal_ratio = 0.302 // log10(2)
///|
/// When to switch to Karatsuba multiplication
let karatsuba_threshold = 50
// Useful bigints
///|
let zero : BigInt = 0N
///|
let one : BigInt = 1N
// Conversion Functions
///|
/// Converts a 32-bit signed integer to a BigInt.
///
/// Parameters:
///
/// * `value` : The 32-bit signed integer (`Int`) to be converted.
///
/// Returns a `BigInt` equivalent to the input integer.
///
/// Example:
///
/// ```moonbit
/// test "BigInt::from_int" {
/// let big = BigInt::from_int(42)
/// inspect!(big, content="42")
/// let neg = BigInt::from_int(-42)
/// inspect!(neg, content="-42")
/// }
/// ```
pub fn BigInt::from_int(n : Int) -> BigInt {
BigInt::from_int64(n.to_int64())
}
///|
/// Converts an unsigned 32-bit integer to a `BigInt`.
///
/// Parameters:
///
/// * `value` : The unsigned 32-bit integer to be converted.
///
/// Returns a `BigInt` representing the same numerical value as the input.
///
/// Example:
///
/// ```moonbit
/// test "BigInt::from_uint" {
/// let n = 42U
/// inspect!(BigInt::from_uint(n), content="42")
/// }
/// ```
pub fn BigInt::from_uint(n : UInt) -> BigInt {
BigInt::from_uint64(n.to_uint64())
}
///|
/// Converts a signed 64-bit integer to a `BigInt`.
///
/// Parameters:
///
/// * `number` : A 64-bit signed integer (`Int64`) to be converted.
///
/// Returns a `BigInt` value that represents the same numerical value as the
/// input.
///
/// Example:
///
/// ```moonbit
/// test "BigInt::from_int64" {
/// let big = BigInt::from_int64(9223372036854775807L) // max value of Int64
/// inspect!(big, content="9223372036854775807")
/// let neg = BigInt::from_int64(-9223372036854775808L) // min value of Int64
/// inspect!(neg, content="-9223372036854775808")
/// }
/// ```
pub fn BigInt::from_int64(n : Int64) -> BigInt {
if n < 0L {
-BigInt::from_uint64((-n).reinterpret_as_uint64())
} else {
BigInt::from_uint64(n.reinterpret_as_uint64())
}
}
///|
/// Converts an unsigned 64-bit integer to a `BigInt`.
///
/// Parameters:
///
/// * `value` : The unsigned 64-bit integer (`UInt64`) to be converted.
///
/// Returns a new `BigInt` with the same value as the input. The resulting
/// `BigInt` will always have a positive sign since the input is an unsigned
/// integer.
///
/// Example:
///
/// ```moonbit
/// test "BigInt::from_uint64" {
/// let n = BigInt::from_uint64(12345678901234567890UL)
/// inspect!(n, content="12345678901234567890")
/// let zero = BigInt::from_uint64(0UL)
/// inspect!(zero, content="0")
/// }
/// ```
pub fn BigInt::from_uint64(n : UInt64) -> BigInt {
if n == 0UL {
return { limbs: FixedArray::make(1, 0), sign: Positive, len: 1 }
}
let limbs = FixedArray::make(64 / radix_bit_len, 0U)
let mut m = n
let mut i = 0
while m > 0 {
limbs[i] = (m % radix).to_uint()
m /= radix
i += 1
}
{ limbs, sign: Positive, len: i }
}
// Arithmetic Operations
///|
/// Negates a big integer, returning a new big integer with the opposite sign. If
/// the input is zero, returns zero.
///
/// Parameters:
///
/// * `self` : The big integer to negate.
///
/// Returns a new big integer with the opposite sign of the input, or zero if the
/// input is zero.
///
/// Example:
///
/// ```moonbit
/// test "BigInt::op_neg" {
/// inspect!(-42N, content="-42")
/// inspect!(-(-42N), content="42")
/// inspect!(-0N, content="0")
/// }
/// ```
pub impl Neg for BigInt with op_neg(self : BigInt) -> BigInt {
if self.is_zero() {
return zero
}
{ ..self, sign: if self.sign == Positive { Negative } else { Positive } }
}
///|
/// Adds two arbitrary-precision integers. Handles positive and negative numbers
/// correctly by converting subtraction of negative numbers into addition of
/// positive numbers.
///
/// Parameters:
///
/// * `self` : The first big integer to add.
/// * `other` : The second big integer to add.
///
/// Returns a new `BigInt` that represents the sum of the two input numbers.
///
/// Example:
///
/// ```moonbit
/// test "BigInt::op_add" {
/// let a = 9223372036854775807N // Max value of Int64
/// let b = 1N
/// inspect!(a + b, content="9223372036854775808") // Beyond Int64 range
/// inspect!(-a + -b, content="-9223372036854775808")
/// }
/// ```
pub impl Add for BigInt with op_add(self : BigInt, other : BigInt) -> BigInt {
if self.sign == Negative {
if other.sign == Negative {
return -(-other + -self)
} else {
return other - -self
}
} else if other.sign == Negative {
return self - -other
}
let self_len = self.len
let other_len = other.len
let limbs = FixedArray::make(1 + max(self_len, other_len), 0U)
let mut carry = 0UL
let mut i = 0
while i < self_len || i < other_len || carry != 0 {
let a = if i < self_len { self.limbs[i].to_uint64() } else { 0 }
let b = if i < other_len { other.limbs[i].to_uint64() } else { 0 }
let sum = a + b + carry
limbs[i] = (sum % radix).to_uint()
carry = sum / radix
i += 1
}
{ limbs, sign: Positive, len: i }
}
///|
/// Subtracts one arbitrary-precision integer from another. Handles positive and
/// negative numbers appropriately.
///
/// Parameters:
///
/// * `self` : The minuend (the number to subtract from).
/// * `other` : The subtrahend (the number to be subtracted).
///
/// Returns a new `BigInt` representing the difference between `self` and
/// `other`.
///
/// Example:
///
/// ```moonbit
/// test "BigInt::op_sub" {
/// let a = 12345678901234567890N
/// let b = 9876543210987654321N
/// inspect!(a - b, content="2469135690246913569")
/// inspect!(-a - b, content="-22222222112222222211")
/// }
/// ```
pub impl Sub for BigInt with op_sub(self : BigInt, other : BigInt) -> BigInt {
// first make sure self and other > 0
if self.sign == Negative {
if other.sign == Negative {
return -other - -self
} else {
return -(other + -self)
}
} else if other.sign == Negative {
return self + -other
}
// then make sure self >= other
if self < other {
return -(other - self)
}
let self_len = self.len
let other_len = other.len
let limbs = FixedArray::make(max(self_len, other_len), 0U)
let mut borrow = 0L
let mut i = 0
while i < self_len || i < other_len || borrow != 0L {
let a = if i < self_len {
self.limbs[i].to_uint64().reinterpret_as_int64()
} else {
0
}
let b = if i < other_len {
other.limbs[i].to_uint64().reinterpret_as_int64()
} else {
0
}
let diff = a - b - borrow // 0 <= a < radix, 0 <= b < radix, 0 <= borrow <= 1 => -radix <= diff < radix
if diff < 0L {
limbs[i] = (diff + radix.reinterpret_as_int64())
.reinterpret_as_uint64()
.to_uint() // -radix <= diff < 0, so we don't need to mod by radix
borrow = 1L
} else {
limbs[i] = diff.reinterpret_as_uint64().to_uint() // 0 <= diff < radix, so we don't need to mod by radix
borrow = 0L
}
i += 1
}
// Ensure the result has at least one limb with a value of zero if the result is zero
while i > 1 && limbs[i - 1] == 0 {
i -= 1
}
{ limbs, sign: Positive, len: i }
}
///|
/// Multiplies two arbitrary-precision integers. Uses the most efficient
/// multiplication algorithm based on the size of the operands:
///
/// * Grade school multiplication for small numbers
/// * Karatsuba multiplication for large numbers
///
/// Parameters:
///
/// * `self` : The first arbitrary-precision integer to multiply.
/// * `other` : The second arbitrary-precision integer to multiply.
///
/// Returns the product of the two numbers. The sign of the result follows the
/// standard multiplication rules: positive if both operands have the same sign,
/// negative otherwise.
///
/// Example:
///
/// ```moonbit
/// test "BigInt::op_mul" {
/// let a = 12345678901234567890N
/// let b = -98765432109876543210N
/// inspect!(a * b, content="-1219326311370217952237463801111263526900")
/// inspect!(a * 0N, content="0")
/// }
/// ```
pub impl Mul for BigInt with op_mul(self : BigInt, other : BigInt) -> BigInt {
if self.is_zero() || other.is_zero() {
return zero
}
let ret = if self.len < karatsuba_threshold || other.len < karatsuba_threshold {
self.grade_school_mul(other)
} else {
self.karatsuba_mul(other)
}
{ ..ret, sign: if self.sign == other.sign { Positive } else { Negative } }
}
///|
// Simplest way to multiply two BigInts.
fn BigInt::grade_school_mul(self : BigInt, other : BigInt) -> BigInt {
let self_len = self.len
let other_len = other.len
let mut len = self_len + other_len
let limbs = FixedArray::make(len, 0U)
for i in 0..<self_len {
let mut carry = 0UL
for j = 0; j < other_len || carry != 0; j = j + 1 {
let product = limbs[i + j].to_uint64() +
self.limbs[i].to_uint64() *
(if j < other_len { other.limbs[j].to_uint64() } else { 0 }) +
carry
limbs[i + j] = (product % radix).to_uint()
carry = product / radix
}
}
if limbs[self_len + other_len - 1] == 0 {
len -= 1
}
{ limbs, sign: Positive, len }
}
///|
// Karatsuba multiplication
fn BigInt::karatsuba_mul(self : BigInt, other : BigInt) -> BigInt {
let half = (max(self.len, other.len) + 1) / 2
let (xl, xh) = self.split(half)
let (yl, yh) = other.split(half)
let p1 = xh * yh
let p2 = xl * yl
let p3 = (xh + xl) * (yh + yl)
(p1 << (radix_bit_len * 2 * half)) +
((p3 - p1 - p2) << (radix_bit_len * half)) +
p2
}
///|
// Get the lower half of the number.
fn BigInt::split(self : BigInt, half : Int) -> (BigInt, BigInt) {
if self.len <= half {
return ({ ..self, sign: Positive }, zero)
}
let lower = FixedArray::make(half, 0U)
lower.unsafe_blit(0, self.limbs, 0, half)
let upper = FixedArray::make(self.len - half, 0U)
upper.unsafe_blit(0, self.limbs, half, self.len - half)
(
{ limbs: lower, sign: Positive, len: half },
{ limbs: upper, sign: Positive, len: self.len - half },
)
}
///|
/// Performs division between two arbitrary-precision integers, following
/// standard arithmetic rules for signed division.
///
/// Parameters:
///
/// * `self` : The dividend big integer.
/// * `other` : The divisor big integer.
///
/// Returns the quotient of the division.
///
/// Throws a panic if the divisor is zero.
///
/// Example:
///
/// ```moonbit
/// test "BigInt::op_div" {
/// let a = BigInt::from_string("100")
/// let b = BigInt::from_string("20")
/// inspect!(a / b, content="5")
/// inspect!(-a / b, content="-5")
/// inspect!(a / -b, content="-5")
/// inspect!(-a / -b, content="5")
/// }
///
/// test "panic BigInt::op_div/division_by_zero" {
/// let a = BigInt::from_string("100")
/// let b = BigInt::from_string("0")
/// ignore(a / b) // Division by zero
/// }
/// ```
pub impl Div for BigInt with op_div(self : BigInt, other : BigInt) -> BigInt {
// TODO:
// guard (other != zero, "division by zero")
if other == zero {
abort("division by zero")
}
// Handle negative numbers
if self.sign == Negative {
if other.sign == Negative {
BigInt::grade_school_div(-self, -other).0
} else {
-BigInt::grade_school_div(-self, other).0
}
} else if other.sign == Negative {
-BigInt::grade_school_div(self, -other).0
} else {
return BigInt::grade_school_div(self, other).0
}
}
///|
/// Calculates the modulo (remainder) of dividing one big integer by another.
///
/// Parameters:
///
/// * `self` : The dividend big integer.
/// * `other` : The divisor big integer.
///
/// Returns the remainder of the division operation.
///
/// Throws an error if `other` is zero.
///
/// Example:
///
/// ```moonbit
/// test "BigInt::op_mod" {
/// let a = 42N
/// let b = 5N
/// inspect!(a % b, content="2")
/// let c = -42N
/// let d = -5N
/// inspect!(c % d, content="-2")
/// }
///
/// test "panic BigInt::op_mod/divide_by_zero" {
/// let a = 42N
/// ignore(a % 0N) // Division by zero
/// }
/// ```
pub impl Mod for BigInt with op_mod(self : BigInt, other : BigInt) -> BigInt {
if other == zero {
abort("division by zero")
}
// Handle negative numbers
if self.sign == Negative {
if other.sign == Negative {
-BigInt::grade_school_div(-self, -other).1
} else {
-BigInt::grade_school_div(-self, other).1
}
} else if other.sign == Negative {
BigInt::grade_school_div(self, -other).1
} else {
BigInt::grade_school_div(self, other).1
}
}
///|
// Simplest way to divide two BigInts.
// Assumption: other != zero.
fn BigInt::grade_school_div(self : BigInt, other : BigInt) -> (BigInt, BigInt) {
// Handle edge cases
if self < other {
return (zero, self)
} else if self == other {
return (one, zero)
}
if other.len == 1 {
let number = other.limbs[0]
let ret = self.copy()
if number == 1 {
return (ret, zero)
}
let a = ret.limbs
let x = number.to_uint64()
let mut y = 0UL
for i = self.len - 1; i >= 0; i = i - 1 {
y = y << radix_bit_len
y += a[i].to_uint64()
a[i] = ((y / x) & radix_mask).to_uint()
y %= x
}
if ret.limbs[ret.len - 1] == 0 {
return (
{ ..ret, len: ret.len - 1 },
{ limbs: FixedArray::make(1, y.to_uint()), sign: Positive, len: 1 },
)
}
return (
ret,
{ limbs: FixedArray::make(1, y.to_uint()), sign: Positive, len: 1 },
)
}
// Cite: TAOCP Vol. 2, 4.3.1
let dividend = self
let divisor = other
// D1. normalize
// m = dividend.len - divisor.len
// left shift dividend & divisor such that
// - b[b.length() - 1] >= radix / 2
// - a.length() == self.len + 1
// where a and b represent the limbs of the adjusted dividend and divisor
let lshift = max(
0,
radix_bit_len -
(
64 -
divisor.limbs[divisor.len - 1].to_uint64().reinterpret_as_int64().clz()
),
)
let a_len = dividend.len
let dividend = dividend << lshift
let divisor = divisor << lshift
let b_len = divisor.len
let b = FixedArray::make(b_len, 0UL)
for i in 0..<b_len {
b[i] = divisor.limbs[i].to_uint64()
}
let a = FixedArray::make(a_len + 1, 0UL)
for i in 0..<a_len {
a[i] = dividend.limbs[i].to_uint64()
} else {
if dividend.limbs.length() > i {
a[i] = dividend.limbs[i].to_uint64()
}
}
// invariant : divisor.limbs.last() >= radix / 2
// if b[b_len - 1] < radix / 2 {
// panic()
// }
let a_len = a_len + 1
// a is the adjusted dividend and b is the adjusted divisor
let v1 = b[b_len - 1]
let v2 = b[b_len - 2]
let q = FixedArray::make(a_len - b_len, 0U)
// D2 - D7 loop through m to 0
for i = q.length() - 1; i >= 0; i = i - 1 {
let u0 = a[i + b_len]
let u1 = a[i + b_len - 1]
let u2 = a[i + b_len - 2]
// D3 compute qh
let mut qh = (u0 * radix + u1) / v1
if qh * v2 > radix * (u0 * radix + u1 - qh * v1) + u2 {
qh -= 1
}
// D4 divident = divident - qh * divisor
let mut borrow = 0L
let mut carry = 0UL
for j in 0..<b_len {
carry += qh * b[j]
borrow += a[i + j].reinterpret_as_int64()
borrow -= (carry & radix_mask).reinterpret_as_int64()
a[i + j] = (borrow & radix_mask.reinterpret_as_int64()).reinterpret_as_uint64()
borrow = borrow >> radix_bit_len
carry = carry >> radix_bit_len
}
borrow = borrow + a[i + b_len].reinterpret_as_int64()
borrow -= carry.reinterpret_as_int64()
a[i + b_len] = (borrow & radix_mask.reinterpret_as_int64()).reinterpret_as_uint64()
borrow = borrow >> radix_bit_len
if borrow < 0L {
carry = 0UL
for j in 0..<b_len {
carry += a[i + j]
carry += b[j]
a[i + j] = carry & radix_mask
carry = carry >> radix_bit_len
}
carry += a[i + b_len]
a[i + b_len] = carry & radix_mask
carry = carry >> radix_bit_len
borrow += carry.reinterpret_as_int64()
qh -= 1
}
q[i] = qh.to_uint()
}
let len = if q[q.length() - 1] == 0 { q.length() - 1 } else { q.length() }
// strip leading zeros
let mut i = a.length() - 1
while i >= 0 && a[i] == 0 {
i -= 1
}
if i < 0 {
i = 1
} else {
i += 1
}
let modulo = FixedArray::make(i, 0U)
for j in 0..<i {
modulo[j] = a[j].to_uint()
}
let modulo = { limbs: modulo, sign: Positive, len: i }
({ limbs: q, sign: Positive, len }, modulo >> lshift)
}
// Bitwise Operations
///|
/// Performs a left shift operation on a `BigInt` value. Preserves the sign of
/// the original number while shifting only its absolute value.
///
/// Parameters:
///
/// * `self` : The `BigInt` value to be shifted.
/// * `n` : The number of positions to shift left. Must be non-negative.
///
/// Returns a new `BigInt` value that is the result of shifting the absolute
/// value of the input left by `n` positions, maintaining the original sign.
///
/// Throws a panic if the shift count is negative.
///
/// Example:
///
/// ```moonbit
/// test "BigInt::op_shl" {
/// let x = 5N
/// inspect!(x << 2, content="20")
/// let y = -5N
/// inspect!(y << 2, content="-20")
/// }
///
/// test "panic BigInt::op_shl/negative_shift" {
/// let x = 5N
/// ignore(x << -1) // Panics with "negative shift count"
/// }
/// ```
pub impl Shl for BigInt with op_shl(self : BigInt, n : Int) -> BigInt {
if n < 0 {
abort("negative shift count")
}
if not(self.is_zero()) {
let new_limbs = FixedArray::make(
self.len + (n + radix_bit_len - 1) / radix_bit_len, // ceiling(n / radix_bit_len)
0U,
)
let a = self.limbs
let r = n % radix_bit_len
let lz = n / radix_bit_len // number of leading zeros
let mut len = self.len + lz
if r != 0 {
let mut carry = 0UL
for i in 0..<self.len {
carry = carry | (a[i].to_uint64() << r)
new_limbs[i + lz] = (carry % radix).to_uint()
carry = carry >> radix_bit_len
}
if carry != 0 {
new_limbs[self.len + lz] = carry.to_uint()
len += 1
}
} else {
new_limbs.unsafe_blit(lz, self.limbs, 0, self.len)
}
{ limbs: new_limbs, sign: self.sign, len }
} else {
zero
}
}
///|
/// Performs arithmetic right shift operation on a big integer value. The shift
/// operation preserves the sign of the number while shifting the absolute value
/// right by `n` bits. For negative numbers, the result is rounded towards
/// negative infinity.
///
/// Parameters:
///
/// * `self` : The big integer value to be shifted.
/// * `n` : The number of bits to shift right. Must be non-negative.
///
/// Returns a new `BigInt` value that represents the result of shifting `self`
/// right by `n` bits.
///
/// Throws a panic if `n` is negative.
///
/// Example:
///
/// ```moonbit
/// test "BigInt::op_shr" {
/// let n = BigInt::from_string("1024")
/// inspect!(n >> 3, content="128")
/// let neg = BigInt::from_string("-1024")
/// inspect!(neg >> 3, content="-128")
/// }
///
/// test "panic BigInt::op_shr/negative_shift" {
/// let n = BigInt::from_string("1024")
/// ignore(n >> -1) // Panics with "negative shift count"
/// }
/// ```
pub impl Shr for BigInt with op_shr(self : BigInt, n : Int) -> BigInt {
if n < 0 {
abort("negative shift count")
}
let r = n % radix_bit_len
let lz = n / radix_bit_len
if lz >= self.len {
match self.sign {
Positive => return zero
Negative =>
return { limbs: FixedArray::make(1, 1), sign: Negative, len: 1 }
}
}
let mut new_len = self.len - lz
if r == 0 {
let new_limbs = FixedArray::make(new_len, 0U)
new_limbs.unsafe_blit(0, self.limbs, lz, new_len)
{ limbs: new_limbs, sign: self.sign, len: new_len }
} else {
let new_limbs = FixedArray::make(new_len, 0U)
let a = self.limbs
let mut carry = 0UL
for i = self.len - 1; i >= lz; i = i - 1 {
let x = a[i].to_uint64()
new_limbs[i - lz] = ((x >> r) | carry).to_uint()
carry = (x << (radix_bit_len - r)) % radix
}
if new_len > 1 && new_limbs[new_len - 1] == 0 {
new_len -= 1
}
if self.sign == Negative && (carry & (1UL << r)) != carry {
{ limbs: new_limbs, sign: self.sign, len: new_len } - 1
} else {
{ limbs: new_limbs, sign: self.sign, len: new_len }
}
}
}
// Comparison Operations
///|
/// Checks whether a `BigInt` value is equal to zero.
///
/// Parameters:
///
/// * `self` : The `BigInt` value to be checked.
///
/// Returns `true` if the `BigInt` is zero, `false` otherwise.
///
/// Example:
///
/// ```moonbit
/// test "BigInt::is_zero" {
/// inspect!(0N.is_zero(), content="true")
/// inspect!(42N.is_zero(), content="false")
/// inspect!((-1N).is_zero(), content="false")
/// }
/// ```
pub fn BigInt::is_zero(self : BigInt) -> Bool {
self.len == 1 && self.limbs[0] == 0
}
///|
/// Compares two arbitrary-precision integers and returns their relative order.
///
/// Parameters:
///
/// * `self` : The first arbitrary-precision integer to compare.
/// * `other` : The second arbitrary-precision integer to compare.
///
/// Returns an integer indicating the relative order:
///
/// * A negative value if `self` is less than `other`
/// * Zero if `self` equals `other`
/// * A positive value if `self` is greater than `other`
///
/// Example:
///
/// ```moonbit
/// test "BigInt::compare" {
/// let a = BigInt::from_string("42")
/// let b = BigInt::from_string("24")
/// let c = BigInt::from_string("-42")
/// inspect!(a.compare(b), content="1") // 42 > 24
/// inspect!(b.compare(a), content="-1") // 24 < 42
/// inspect!(c.compare(a), content="-1") // -42 < 42
/// inspect!(a.compare(a), content="0") // 42 = 42
/// }
/// ```
pub impl Compare for BigInt with compare(self, other) {
if self.sign != other.sign {
return if self.sign == Positive { 1 } else { -1 }
}
let self_len = self.len
let other_len = other.len
if self_len != other_len {
return if self.sign == Positive {
self_len - other_len
} else {
other_len - self_len
}
}
for i = self_len - 1; i >= 0; i = i - 1 {
if self.limbs[i] != other.limbs[i] {
return if self.sign == Positive {
self.limbs[i].compare(other.limbs[i])
} else {
other.limbs[i].compare(self.limbs[i])
}
}
}
0
}
///|
/// Compares two `BigInt` values for equality. Returns true if both numbers have
/// the same sign and magnitude.
///
/// Parameters:
///
/// * `self` : The first `BigInt` value to compare.
/// * `other` : The second `BigInt` value to compare.
///
/// Returns `true` if the two `BigInt` values are equal, `false` otherwise.
///
/// Example:
///
/// ```moonbit
/// test "BigInt::op_equal" {
/// let a = 123456789N
/// let b = 123456789N
/// let c = -123456789N
/// inspect!(a == b, content="true")
/// inspect!(a == c, content="false")
/// }
/// ```
pub impl Eq for BigInt with op_equal(self, other) {
if self.sign != other.sign || self.len != other.len {
return false
}
for i in 0..<self.len {
if self.limbs[i] != other.limbs[i] {
return false
}
}
true
}
///|
/// Converts a `BigInt` value to its decimal string representation.
///
/// Parameters:
///
/// * `self` : The `BigInt` value to convert to a string.
///
/// Returns a string containing the decimal representation of the number, with a
/// leading minus sign for negative numbers.
///
/// Example:
///
/// ```moonbit
/// test "BigInt::to_string" {
/// let n = 12345678901234567890N
/// inspect!(n.to_string(), content="12345678901234567890")
/// let neg = -42N
/// inspect!(neg.to_string(), content="-42")
/// let zero = 0N
/// inspect!(zero.to_string(), content="0")
/// }
/// ```
pub fn BigInt::to_string(self : BigInt) -> String {
// This function first converts the BigInt to a decimal representation, with a radix of 2^(`decimal_radix_bit_len`).
// Then it converts the decimal representation to a string slot by slot.
if self.is_zero() {
return "0"
}
let decimal_radix_bit_len = 19 - 1 - (1 + radix_bit_len) / 3 // < len(9,223,372,036,854,775,807) - len(2^radix_bit_len). len means the number of digits in decimal.
let decimal_mask = 10_000_000L // 10^(decimal_radix_bit_len). TODO: compute it when we have power function.
// The following value should fit well into an Int without precision loss.
// This is an approximation of the number of slots needed to represent the decimal value.
let decimal_len = ((self.len * radix_bit_len).to_double() *
decimal_ratio /
decimal_radix_bit_len.to_double()).to_unchecked_int() +
1
let s = if self.sign == Negative { "-" } else { "" }
let v = Array::make(decimal_len, 0L)
let mut v_idx = 0
for i = self.len - 1; i >= 0; i = i - 1 {
let mut x = self.limbs[i].to_uint64().reinterpret_as_int64()
for j in 0..<v_idx {
let y = (v[j] << radix_bit_len) | x
x = y / decimal_mask
v[j] = y % decimal_mask
}
while x > 0L {
v[v_idx] = x % decimal_mask
v_idx += 1
x /= decimal_mask
}
}
let mut ret = ""
for i in 0..<(v_idx - 1) {
for j in 0..<decimal_radix_bit_len {
let x = v[i] % 10L
v[i] /= 10L
ret = x.to_string() + ret
}
}
let mut x = v[v_idx - 1] // v_idx is at least 1, we check is_zero() at the beginning.
while x > 0L {
let y = x % 10L
x /= 10L
ret = y.to_string() + ret
}
s + ret
}
///|
/// Formats and writes a `BigInt` value to a logger by converting it to a string
/// representation.
///
/// Implements the `Show` trait for `BigInt` type, allowing `BigInt` values to be
/// converted to strings and used in string interpolation.
///
/// Parameters:
///
/// * `self` : The `BigInt` value to be formatted.
/// * `logger` : A logger that implements the `Logger` trait, which will receive
/// the formatted string output.
///
/// Example:
///
/// ```moonbit
/// test "BigInt::output" {
/// let n = 12345678901234567890N
/// inspect!(n, content="12345678901234567890")
/// let neg = -42N