-
Notifications
You must be signed in to change notification settings - Fork 4
/
bigint.nelua
5837 lines (4905 loc) · 136 KB
/
bigint.nelua
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
--[[
Arbitrary-precision arithmetic integer module based on GMP.
This module works in standalone by default and bundles the Mini GMP library.
However you can set BIGINT_USE_GMP to true before requiring this to use
your system's GMP library, which is a more sophisticated implementation and is
much faster.
]]
require 'string'
require 'math'
--------------------------------------------------------------------------------
-- GMP imports
##[[
if BIGINT_USE_GMP then
cinclude 'gmp.h'
linklib 'gmp'
else -- use bundled mini gmp
cinclude '@mini-gmp.h'
cinclude '@mini-gmp.c'
cflags '-Wno-sign-compare'
end
]]
-- Import only APIs available in 'mini-gmp.h'
local mp_limb_t: type <cimport,nodecl> = @culong
local mp_size_t: type <cimport,nodecl> = @clong
local mp_bitcnt_t: type <cimport,nodecl> = @culong
local __mpz_struct: type <cimport,nodecl> = @record{
_mp_alloc: cint,
_mp_size: cint,
_mp_d: *mp_limb_t
}
local function mpz_init(a1: *__mpz_struct): void <cimport,nodecl> end
local function mpz_init2(a1: *__mpz_struct, a2: mp_bitcnt_t): void <cimport,nodecl> end
local function mpz_clear(a1: *__mpz_struct): void <cimport,nodecl> end
local function mpz_sgn(a1: *__mpz_struct): cint <cimport,nodecl> end
local function mpz_cmp_si(a1: *__mpz_struct, a2: clong): cint <cimport,nodecl> end
local function mpz_cmp_ui(a1: *__mpz_struct, a2: culong): cint <cimport,nodecl> end
local function mpz_cmp(a1: *__mpz_struct, a2: *__mpz_struct): cint <cimport,nodecl> end
local function mpz_cmpabs_ui(a1: *__mpz_struct, a2: culong): cint <cimport,nodecl> end
local function mpz_cmpabs(a1: *__mpz_struct, a2: *__mpz_struct): cint <cimport,nodecl> end
local function mpz_cmp_d(a1: *__mpz_struct, a2: float64): cint <cimport,nodecl> end
local function mpz_cmpabs_d(a1: *__mpz_struct, a2: float64): cint <cimport,nodecl> end
local function mpz_abs(a1: *__mpz_struct, a2: *__mpz_struct): void <cimport,nodecl> end
local function mpz_neg(a1: *__mpz_struct, a2: *__mpz_struct): void <cimport,nodecl> end
local function mpz_swap(a1: *__mpz_struct, a2: *__mpz_struct): void <cimport,nodecl> end
local function mpz_add_ui(a1: *__mpz_struct, a2: *__mpz_struct, a3: culong): void <cimport,nodecl> end
local function mpz_add(a1: *__mpz_struct, a2: *__mpz_struct, a3: *__mpz_struct): void <cimport,nodecl> end
local function mpz_sub_ui(a1: *__mpz_struct, a2: *__mpz_struct, a3: culong): void <cimport,nodecl> end
local function mpz_ui_sub(a1: *__mpz_struct, a2: culong, a3: *__mpz_struct): void <cimport,nodecl> end
local function mpz_sub(a1: *__mpz_struct, a2: *__mpz_struct, a3: *__mpz_struct): void <cimport,nodecl> end
local function mpz_mul_si(a1: *__mpz_struct, a2: *__mpz_struct, a3: clong): void <cimport,nodecl> end
local function mpz_mul_ui(a1: *__mpz_struct, a2: *__mpz_struct, a3: culong): void <cimport,nodecl> end
local function mpz_mul(a1: *__mpz_struct, a2: *__mpz_struct, a3: *__mpz_struct): void <cimport,nodecl> end
local function mpz_mul_2exp(a1: *__mpz_struct, a2: *__mpz_struct, a3: mp_bitcnt_t): void <cimport,nodecl> end
local function mpz_addmul_ui(a1: *__mpz_struct, a2: *__mpz_struct, a3: culong): void <cimport,nodecl> end
local function mpz_addmul(a1: *__mpz_struct, a2: *__mpz_struct, a3: *__mpz_struct): void <cimport,nodecl> end
local function mpz_submul_ui(a1: *__mpz_struct, a2: *__mpz_struct, a3: culong): void <cimport,nodecl> end
local function mpz_submul(a1: *__mpz_struct, a2: *__mpz_struct, a3: *__mpz_struct): void <cimport,nodecl> end
local function mpz_cdiv_qr(a1: *__mpz_struct, a2: *__mpz_struct, a3: *__mpz_struct, a4: *__mpz_struct): void <cimport,nodecl> end
local function mpz_fdiv_qr(a1: *__mpz_struct, a2: *__mpz_struct, a3: *__mpz_struct, a4: *__mpz_struct): void <cimport,nodecl> end
local function mpz_tdiv_qr(a1: *__mpz_struct, a2: *__mpz_struct, a3: *__mpz_struct, a4: *__mpz_struct): void <cimport,nodecl> end
local function mpz_cdiv_q(a1: *__mpz_struct, a2: *__mpz_struct, a3: *__mpz_struct): void <cimport,nodecl> end
local function mpz_fdiv_q(a1: *__mpz_struct, a2: *__mpz_struct, a3: *__mpz_struct): void <cimport,nodecl> end
local function mpz_tdiv_q(a1: *__mpz_struct, a2: *__mpz_struct, a3: *__mpz_struct): void <cimport,nodecl> end
local function mpz_cdiv_r(a1: *__mpz_struct, a2: *__mpz_struct, a3: *__mpz_struct): void <cimport,nodecl> end
local function mpz_fdiv_r(a1: *__mpz_struct, a2: *__mpz_struct, a3: *__mpz_struct): void <cimport,nodecl> end
local function mpz_tdiv_r(a1: *__mpz_struct, a2: *__mpz_struct, a3: *__mpz_struct): void <cimport,nodecl> end
local function mpz_cdiv_q_2exp(a1: *__mpz_struct, a2: *__mpz_struct, a3: mp_bitcnt_t): void <cimport,nodecl> end
local function mpz_fdiv_q_2exp(a1: *__mpz_struct, a2: *__mpz_struct, a3: mp_bitcnt_t): void <cimport,nodecl> end
local function mpz_tdiv_q_2exp(a1: *__mpz_struct, a2: *__mpz_struct, a3: mp_bitcnt_t): void <cimport,nodecl> end
local function mpz_cdiv_r_2exp(a1: *__mpz_struct, a2: *__mpz_struct, a3: mp_bitcnt_t): void <cimport,nodecl> end
local function mpz_fdiv_r_2exp(a1: *__mpz_struct, a2: *__mpz_struct, a3: mp_bitcnt_t): void <cimport,nodecl> end
local function mpz_tdiv_r_2exp(a1: *__mpz_struct, a2: *__mpz_struct, a3: mp_bitcnt_t): void <cimport,nodecl> end
local function mpz_mod(a1: *__mpz_struct, a2: *__mpz_struct, a3: *__mpz_struct): void <cimport,nodecl> end
local function mpz_divexact(a1: *__mpz_struct, a2: *__mpz_struct, a3: *__mpz_struct): void <cimport,nodecl> end
local function mpz_divisible_p(a1: *__mpz_struct, a2: *__mpz_struct): cint <cimport,nodecl> end
local function mpz_congruent_p(a1: *__mpz_struct, a2: *__mpz_struct, a3: *__mpz_struct): cint <cimport,nodecl> end
local function mpz_cdiv_qr_ui(a1: *__mpz_struct, a2: *__mpz_struct, a3: *__mpz_struct, a4: culong): culong <cimport,nodecl> end
local function mpz_fdiv_qr_ui(a1: *__mpz_struct, a2: *__mpz_struct, a3: *__mpz_struct, a4: culong): culong <cimport,nodecl> end
local function mpz_tdiv_qr_ui(a1: *__mpz_struct, a2: *__mpz_struct, a3: *__mpz_struct, a4: culong): culong <cimport,nodecl> end
local function mpz_cdiv_q_ui(a1: *__mpz_struct, a2: *__mpz_struct, a3: culong): culong <cimport,nodecl> end
local function mpz_fdiv_q_ui(a1: *__mpz_struct, a2: *__mpz_struct, a3: culong): culong <cimport,nodecl> end
local function mpz_tdiv_q_ui(a1: *__mpz_struct, a2: *__mpz_struct, a3: culong): culong <cimport,nodecl> end
local function mpz_cdiv_r_ui(a1: *__mpz_struct, a2: *__mpz_struct, a3: culong): culong <cimport,nodecl> end
local function mpz_fdiv_r_ui(a1: *__mpz_struct, a2: *__mpz_struct, a3: culong): culong <cimport,nodecl> end
local function mpz_tdiv_r_ui(a1: *__mpz_struct, a2: *__mpz_struct, a3: culong): culong <cimport,nodecl> end
local function mpz_cdiv_ui(a1: *__mpz_struct, a2: culong): culong <cimport,nodecl> end
local function mpz_fdiv_ui(a1: *__mpz_struct, a2: culong): culong <cimport,nodecl> end
local function mpz_tdiv_ui(a1: *__mpz_struct, a2: culong): culong <cimport,nodecl> end
local function mpz_mod_ui(a1: *__mpz_struct, a2: *__mpz_struct, a3: culong): culong <cimport,nodecl> end
local function mpz_divexact_ui(a1: *__mpz_struct, a2: *__mpz_struct, a3: culong): void <cimport,nodecl> end
local function mpz_divisible_ui_p(a1: *__mpz_struct, a2: culong): cint <cimport,nodecl> end
local function mpz_gcd_ui(a1: *__mpz_struct, a2: *__mpz_struct, a3: culong): culong <cimport,nodecl> end
local function mpz_gcd(a1: *__mpz_struct, a2: *__mpz_struct, a3: *__mpz_struct): void <cimport,nodecl> end
local function mpz_gcdext(a1: *__mpz_struct, a2: *__mpz_struct, a3: *__mpz_struct, a4: *__mpz_struct, a5: *__mpz_struct): void <cimport,nodecl> end
local function mpz_lcm_ui(a1: *__mpz_struct, a2: *__mpz_struct, a3: culong): void <cimport,nodecl> end
local function mpz_lcm(a1: *__mpz_struct, a2: *__mpz_struct, a3: *__mpz_struct): void <cimport,nodecl> end
local function mpz_invert(a1: *__mpz_struct, a2: *__mpz_struct, a3: *__mpz_struct): cint <cimport,nodecl> end
local function mpz_sqrtrem(a1: *__mpz_struct, a2: *__mpz_struct, a3: *__mpz_struct): void <cimport,nodecl> end
local function mpz_sqrt(a1: *__mpz_struct, a2: *__mpz_struct): void <cimport,nodecl> end
local function mpz_perfect_square_p(a1: *__mpz_struct): cint <cimport,nodecl> end
local function mpz_pow_ui(a1: *__mpz_struct, a2: *__mpz_struct, a3: culong): void <cimport,nodecl> end
local function mpz_ui_pow_ui(a1: *__mpz_struct, a2: culong, a3: culong): void <cimport,nodecl> end
local function mpz_powm(a1: *__mpz_struct, a2: *__mpz_struct, a3: *__mpz_struct, a4: *__mpz_struct): void <cimport,nodecl> end
local function mpz_powm_ui(a1: *__mpz_struct, a2: *__mpz_struct, a3: culong, a4: *__mpz_struct): void <cimport,nodecl> end
local function mpz_rootrem(a1: *__mpz_struct, a2: *__mpz_struct, a3: *__mpz_struct, a4: culong): void <cimport,nodecl> end
local function mpz_root(a1: *__mpz_struct, a2: *__mpz_struct, a3: culong): cint <cimport,nodecl> end
local function mpz_fac_ui(a1: *__mpz_struct, a2: culong): void <cimport,nodecl> end
local function mpz_2fac_ui(a1: *__mpz_struct, a2: culong): void <cimport,nodecl> end
local function mpz_mfac_uiui(a1: *__mpz_struct, a2: culong, a3: culong): void <cimport,nodecl> end
local function mpz_bin_uiui(a1: *__mpz_struct, a2: culong, a3: culong): void <cimport,nodecl> end
local function mpz_probab_prime_p(a1: *__mpz_struct, a2: cint): cint <cimport,nodecl> end
local function mpz_tstbit(a1: *__mpz_struct, a2: mp_bitcnt_t): cint <cimport,nodecl> end
local function mpz_setbit(a1: *__mpz_struct, a2: mp_bitcnt_t): void <cimport,nodecl> end
local function mpz_clrbit(a1: *__mpz_struct, a2: mp_bitcnt_t): void <cimport,nodecl> end
local function mpz_combit(a1: *__mpz_struct, a2: mp_bitcnt_t): void <cimport,nodecl> end
local function mpz_com(a1: *__mpz_struct, a2: *__mpz_struct): void <cimport,nodecl> end
local function mpz_and(a1: *__mpz_struct, a2: *__mpz_struct, a3: *__mpz_struct): void <cimport,nodecl> end
local function mpz_ior(a1: *__mpz_struct, a2: *__mpz_struct, a3: *__mpz_struct): void <cimport,nodecl> end
local function mpz_xor(a1: *__mpz_struct, a2: *__mpz_struct, a3: *__mpz_struct): void <cimport,nodecl> end
local function mpz_popcount(a1: *__mpz_struct): mp_bitcnt_t <cimport,nodecl> end
local function mpz_hamdist(a1: *__mpz_struct, a2: *__mpz_struct): mp_bitcnt_t <cimport,nodecl> end
local function mpz_scan0(a1: *__mpz_struct, a2: mp_bitcnt_t): mp_bitcnt_t <cimport,nodecl> end
local function mpz_scan1(a1: *__mpz_struct, a2: mp_bitcnt_t): mp_bitcnt_t <cimport,nodecl> end
local function mpz_fits_slong_p(a1: *__mpz_struct): cint <cimport,nodecl> end
local function mpz_fits_ulong_p(a1: *__mpz_struct): cint <cimport,nodecl> end
local function mpz_get_si(a1: *__mpz_struct): clong <cimport,nodecl> end
local function mpz_get_ui(a1: *__mpz_struct): culong <cimport,nodecl> end
local function mpz_get_d(a1: *__mpz_struct): float64 <cimport,nodecl> end
local function mpz_size(a1: *__mpz_struct): csize <cimport,nodecl> end
local function mpz_getlimbn(a1: *__mpz_struct, a2: mp_size_t): mp_limb_t <cimport,nodecl> end
local function mpz_realloc2(a1: *__mpz_struct, a2: mp_bitcnt_t): void <cimport,nodecl> end
local function mpz_limbs_read(a1: *__mpz_struct): *mp_limb_t <cimport,nodecl> end
local function mpz_limbs_modify(a1: *__mpz_struct, a2: mp_size_t): *mp_limb_t <cimport,nodecl> end
local function mpz_limbs_write(a1: *__mpz_struct, a2: mp_size_t): *mp_limb_t <cimport,nodecl> end
local function mpz_limbs_finish(a1: *__mpz_struct, a2: mp_size_t): void <cimport,nodecl> end
local function mpz_roinit_n(a1: *__mpz_struct, a2: *mp_limb_t, a3: mp_size_t): *__mpz_struct <cimport,nodecl> end
local function mpz_set_si(a1: *__mpz_struct, a2: clong): void <cimport,nodecl> end
local function mpz_set_ui(a1: *__mpz_struct, a2: culong): void <cimport,nodecl> end
local function mpz_set(a1: *__mpz_struct, a2: *__mpz_struct): void <cimport,nodecl> end
local function mpz_set_d(a1: *__mpz_struct, a2: float64): void <cimport,nodecl> end
local function mpz_init_set_si(a1: *__mpz_struct, a2: clong): void <cimport,nodecl> end
local function mpz_init_set_ui(a1: *__mpz_struct, a2: culong): void <cimport,nodecl> end
local function mpz_init_set(a1: *__mpz_struct, a2: *__mpz_struct): void <cimport,nodecl> end
local function mpz_init_set_d(a1: *__mpz_struct, a2: float64): void <cimport,nodecl> end
local function mpz_sizeinbase(a1: *__mpz_struct, a2: cint): csize <cimport,nodecl> end
local function mpz_get_str(a1: cstring, a2: cint, a3: *__mpz_struct): cstring <cimport,nodecl> end
local function mpz_set_str(a1: *__mpz_struct, a2: cstring, a3: cint): cint <cimport,nodecl> end
local function mpz_init_set_str(a1: *__mpz_struct, a2: cstring, a3: cint): cint <cimport,nodecl> end
local function mpz_import(a1: *__mpz_struct, a2: csize, a3: cint, a4: csize, a5: cint, a6: csize, a7: pointer): void <cimport,nodecl> end
local function mpz_export(a1: pointer, a2: *csize, a3: cint, a4: csize, a5: cint, a6: csize, a7: *__mpz_struct): pointer <cimport,nodecl> end
--------------------------------------------------------------------------------
-- Helpers
-- Cleanup big integer resources when the garbage collector is enabled.
function __mpz_struct:__gc(): void
mpz_clear(self)
end
-- Auxiliary macro to convert strings, integers to big integers.
##[[
local function ensure_bigints(...)
for i=1,select('#',...) do
local sym = select(i, ...)
if not sym.type.is_bigint then
]]
local #|sym.name|#: BigInt <close> = BigInt.from(#[sym]#)
assert(#|sym.name|#:isvalid(), "BIGINT - Big integer conversion failed, it's malformed")
## else
assert(#[sym]#:isvalid(), "BIGINT - Invalid big integer, it's not initialized")
##[[
end
end
end
]]
-- Concept that accept any value that is convertible to a big integer.
local BigInt_convertible: type = #[concept(function(x)
return x.type.is_integral or x.type.is_bigint or x.type.is_string
end)]#
--------------------------------------------------------------------------------
-- The Big Integer
-- The big integer record.
local BigInt: type = @record{
mpz: *__mpz_struct
}
## BigInt.value.is_bigint = true
-- Destroys the big integer, freeing its resources.
function BigInt:destroy(): void
if self.mpz then
## if pragmas.nogc then -- delete will already call `__mpz_struct:__gc`
mpz_clear(self.mpz)
## end
delete(self.mpz)
self.mpz = nilptr
end
end
-- Allow cleaning up resources with to-be-closed variables.
function BigInt:__close(): void
self:destroy()
end
-- Returns true if the big integer is properly allocated and initialized.
function BigInt.isvalid(x: BigInt): boolean
return x.mpz ~= nilptr and x.mpz._mp_d ~= nilptr
end
-- Returns the total storage size in bytes (`#` unary operator).
function BigInt.__len(x: BigInt): usize
if not x:isvalid() or mpz_sgn(x.mpz) == 0 then return 0 end
return (mpz_sizeinbase(x.mpz, 2) + 7) // 8
end
-- Returns the sign of the big integer, -1 if negative, 0 if zero, 1 if positive.
function BigInt.sign(x: BigInt_convertible): int32
if not x:isvalid() then return 0 end
local s: cint = mpz_sgn(x.mpz)
return s
end
-- Returns a new big integer with zero value stored.
function BigInt.new(): BigInt
local self: BigInt
self.mpz = new(@__mpz_struct)
mpz_init(self.mpz)
return self
end
-- Creates a new big integer with the same value of another big integer.
function BigInt.clone(x: BigInt): BigInt
## ensure_bigints(x)
local clone: BigInt = BigInt.new()
mpz_set(clone.mpz, x.mpz)
return clone
end
-- Copy the value of another big integer (in-place).
function BigInt:copy_(x: BigInt_convertible): BigInt
## ensure_bigints(x)
if not self.mpz then
self.mpz = new(@__mpz_struct)
elseif not self:isvalid() then
mpz_init(self.mpz)
end
mpz_set(self.mpz, x.mpz)
return $self
end
-- Return the total storage size in bits.
function BigInt.bitlen(x: BigInt): usize
if not x:isvalid() or mpz_sgn(x.mpz) == 0 then return 0 end
return mpz_sizeinbase(x.mpz, 2)
end
-- Returns bit at position `pos`.
function BigInt.getbit(x: BigInt_convertible, pos: usize): uint8
## ensure_bigints(x)
return mpz_tstbit(x.mpz, pos)
end
--------------------------------------------------------------------------------
-- Functions for unserializing big integers
-- Creates a new big integer from a buffer of bytes `data`.
function BigInt.frombytes(data: string, little_endian: facultative(boolean)): BigInt
## if little_endian.type.is_niltype then
local little_endian: boolean = false
## end
local res: BigInt = BigInt.new()
if data.size > 0 then
mpz_import(res.mpz, data.size, little_endian and -1 or 1, #@byte, 0, 0, data.data)
end
return res
end
--[[
Creates a new big integer from string `s` in base `base`.
In case the input string is malformed, then a big integer in invalid state is returned.
]]
function BigInt.fromstring(s: string, base: facultative(int32)): BigInt
local self: BigInt = BigInt.new()
## if base.type.is_niltype then
local base: int32
if #s >= 2 and s:subview(1,2) == '0x' then -- hexadecimal
base = 16
s = s:subview(3,-1)
elseif #s >= 2 and s:subview(1,2) == '0b' then -- binary
base = 2
s = s:subview(3,-1)
else -- should be decimal
base = 10
end
## end
-- TODO: ensure 's' is null terminated
if mpz_set_str(self.mpz, s, base) ~= 0 then
self:destroy()
end
return self
end
--[[
Creates a new big integer from a decimal string.
The returned big integer is multiplied by `10^decimal_places` so decimals are not lost.
Any decimals after `decimal_places` decimals are discarded.
In case the input string is malformed, then a big integer in invalid state is returned.
]]
function BigInt.fromdecimal(s: string, decimal_places: usize): BigInt
local found_decimal: boolean
local n_decimals: usize
local sb: stringbuilder <close>
-- filter string by removing '.'
for i: usize=0,<s.size do
local c: byte = s.data[i]
if c == '.'_b then
found_decimal = true
else
sb:writebyte(c)
if found_decimal then
n_decimals = n_decimals + 1
end
end
end
if decimal_places > n_decimals then
-- add zeros past decimal place
for i: usize=0,<decimal_places-n_decimals do
sb:writebyte('0'_b)
end
elseif decimal_places < n_decimals then
-- too much decimal places, discard extra ones
sb:rollback(n_decimals - decimal_places)
end
return BigInt.fromstring(sb:view())
end
--[[
Creates a new big integer from a decimal string.
This always succeeds.
]]
function BigInt.frominteger(x: integer): BigInt
local self: BigInt = BigInt.new()
mpz_set_si(self.mpz, x)
return self
end
--[[
Creates a new big integer from a number, string or another big integer.
In case the input string is malformed, then a big integer in invalid state is returned.
]]
function BigInt.from(v: BigInt_convertible): BigInt
## if v.type.is_integral then
return BigInt.frominteger(v)
## elseif v.type.is_string then
return BigInt.fromstring(v)
## elseif v.type.is_bigint then
return BigInt.clone(v)
## end
end
--------------------------------------------------------------------------------
-- Functions for serializing big integers
-- Returns the big integer bytes as string of bytes, that is, in binary form (not human readable).
function BigInt.tobytes(x: BigInt_convertible, little_endian: facultative(boolean), size: facultative(usize)): string
## ensure_bigints(x)
## if little_endian.type.is_niltype then
local little_endian: boolean = false
## end
## if size.type.is_niltype then
local size: usize = #x
## end
assert(size >= #x, 'BigInt.tobytes: desired buffer size is not not enough')
local data: string
if size > 0 then
data = string.create(size)
local data_ptr: *byte = &data.data[0]
if size > #x then
memory.spanzero(data:span())
if not little_endian then
data_ptr = &data.data[size - #x]
end
end
local len: csize
assert(mpz_export(data_ptr, &len, little_endian and -1 or 1, #@byte, 0, 0, x.mpz) == data_ptr, 'mpz_export failed')
end
return data
end
-- Returns the big integer as a human readable string in the desired base.
function BigInt.tostring(x: BigInt_convertible, base: facultative(int32), minlen: facultative(int32)): string
## ensure_bigints(x)
## if base.type.is_niltype then
local base: int32 = 10
## end
local sb: stringbuilder <close>
local buf: span(byte) = sb:prepare(mpz_sizeinbase(x.mpz, base) + 2)
local s: cstring = mpz_get_str(&buf[0], base, x.mpz)
assert(s ~= nilptr, 'mpz_get_str failed')
sb:commit(#s)
-- remove trailing zeros
local s: string = sb:view():lower()
## if not minlen.type.is_niltype then
if #s < minlen then
local zeros: string <close> = string.rep('0', minlen-#s)
local s2: string = zeros..s
s:destroy()
return s2
end
## end
return s
end
--[[
Returns the big integer as an integer.
Integer not in the `integer` type range, its values will wrap around.
]]
function BigInt.tointeger(x: BigInt_convertible): integer
## ensure_bigints(x)
return mpz_get_si(x.mpz)
end
-- Returns the big integer as a string in decimal base (to allow using `tostring` function).
function BigInt.__tostring(x: BigInt_convertible): string
## ensure_bigints(x)
return x:tostring(10)
end
--------------------------------------------------------------------------------
-- Functions for creation random integers
--[[
Returns a random big int with at most `size` bytes.
The generated random number doesn't satisfy any particular requirements of randomness.
It uses `math.random` to generate random,
thus the random seed can be changed by calling `math.seed` before this function.
]]
function BigInt.randombytes(size: usize): BigInt
local res: BigInt = BigInt.new()
if size > 0 then
local rands: span(integer) = new(@integer, (size + #@integer - 1) // #@integer)
defer delete(rands) end
for i: usize=0,<#rands do
rands[i] = math.random(0)
end
local data: span(byte) = rands:as(@byte)
mpz_import(res.mpz, size, 1, #@byte, 0, 0, data.data)
end
return res
end
--[[
Returns a random big int in the range [0,max).
See also `BigInt.randombytes` for random details.
]]
function BigInt.random(max: BigInt_convertible): BigInt
## ensure_bigints(max)
return BigInt.randombytes(#max):tmod_(max)
end
--------------------------------------------------------------------------------
-- Comparison methods
-- Less than comparison.
function BigInt.lt(a: BigInt_convertible, b: BigInt_convertible): boolean
## if b.type.is_integral then ensure_bigints(a)
return mpz_cmp_si(a.mpz, b) < 0
## elseif a.type.is_integral then ensure_bigints(b)
return mpz_cmp_si(b.mpz, a) > 0
## else ensure_bigints(a, b)
return mpz_cmp(a.mpz, b.mpz) < 0
## end
end
-- Less or equal than comparison.
function BigInt.le(a: BigInt_convertible, b: BigInt_convertible): boolean
## if b.type.is_integral then ensure_bigints(a)
return mpz_cmp_si(a.mpz, b) <= 0
## elseif a.type.is_integral then ensure_bigints(b)
return mpz_cmp_si(b.mpz, a) >= 0
## else ensure_bigints(a, b)
return mpz_cmp(a.mpz, b.mpz) <= 0
## end
end
-- Equals comparison.
function BigInt.eq(a: BigInt_convertible, b: BigInt_convertible): boolean
## ensure_bigints(a, b)
return mpz_cmp(a.mpz, b.mpz) == 0
end
--------------------------------------------------------------------------------
-- Arithmetic operations
-- Negation.
function BigInt.neg(a: BigInt_convertible): BigInt
## ensure_bigints(a)
local res: BigInt = BigInt.new()
mpz_neg(res.mpz, a.mpz)
return res
end
-- Negation (in-place).
function BigInt.neg_(a: BigInt): BigInt
## ensure_bigints(a)
mpz_neg(a.mpz, a.mpz)
return a
end
-- Absolute value.
function BigInt.abs(a: BigInt_convertible): BigInt
## ensure_bigints(a)
local res: BigInt = BigInt.new()
mpz_abs(res.mpz, a.mpz)
return res
end
-- Absolute value (in-place).
function BigInt.abs_(a: BigInt): BigInt
## ensure_bigints(a)
mpz_abs(a.mpz, a.mpz)
return a
end
-- Addition.
function BigInt.add(a: BigInt_convertible, b: BigInt_convertible): BigInt
## ensure_bigints(a, b)
local res: BigInt = BigInt.new()
mpz_add(res.mpz, a.mpz, b.mpz)
return res
end
-- Addition (in-place).
function BigInt.add_(a: BigInt, b: BigInt_convertible): BigInt
## ensure_bigints(a, b)
mpz_add(a.mpz, a.mpz, b.mpz)
return a
end
-- Subtraction.
function BigInt.sub(a: BigInt_convertible, b: BigInt_convertible): BigInt
## ensure_bigints(a, b)
local res: BigInt = BigInt.new()
mpz_sub(res.mpz, a.mpz, b.mpz)
return res
end
-- Subtraction (in-place).
function BigInt.sub_(a: BigInt, b: BigInt_convertible): BigInt
## ensure_bigints(a, b)
mpz_sub(a.mpz, a.mpz, b.mpz)
return a
end
-- Multiplication.
function BigInt.mul(a: BigInt_convertible, b: BigInt_convertible): BigInt
## ensure_bigints(a, b)
local res: BigInt = BigInt.new()
mpz_mul(res.mpz, a.mpz, b.mpz)
return res
end
-- Multiplication (in-place).
function BigInt.mul_(a: BigInt, b: BigInt_convertible): BigInt
## ensure_bigints(a, b)
mpz_mul(a.mpz, a.mpz, b.mpz)
return a
end
-- Integer truncate division (rounding towards 0).
function BigInt.tdiv(a: BigInt_convertible, b: BigInt_convertible): BigInt
## ensure_bigints(a, b)
local res: BigInt = BigInt.new()
mpz_tdiv_q(res.mpz, a.mpz, b.mpz)
return res
end
-- Integer truncate division (rounding towards 0) (in-place).
function BigInt.tdiv_(a: BigInt, b: BigInt_convertible): BigInt
## ensure_bigints(a, b)
mpz_tdiv_q(a.mpz, a.mpz, b.mpz)
return a
end
-- Integer floor division (rounding towards minus infinity).
function BigInt.fdiv(a: BigInt_convertible, b: BigInt_convertible): BigInt
## ensure_bigints(a, b)
local res: BigInt = BigInt.new()
mpz_fdiv_q(res.mpz, a.mpz, b.mpz)
return res
end
-- Integer floor division (rounding towards minus infinity) (in-place).
function BigInt.fdiv_(a: BigInt, b: BigInt_convertible): BigInt
## ensure_bigints(a, b)
mpz_fdiv_q(a.mpz, a.mpz, b.mpz)
return a
end
-- Integer ceil division (rounding towards infinity).
function BigInt.cdiv(a: BigInt_convertible, b: BigInt_convertible): BigInt
## ensure_bigints(a, b)
local res: BigInt = BigInt.new()
mpz_cdiv_q(res.mpz, a.mpz, b.mpz)
return res
end
-- Integer ceil division (rounding towards infinity) (in-place).
function BigInt.cdiv_(a: BigInt, b: BigInt_convertible): BigInt
## ensure_bigints(a, b)
mpz_cdiv_q(a.mpz, a.mpz, b.mpz)
return a
end
-- Integer round division (rounding towards nearest integer).
function BigInt.rdiv(a: BigInt_convertible, b: BigInt_convertible): BigInt
## ensure_bigints(a, b)
local res: BigInt = b:tdiv(2)
if ((a:sign() < 0 and 1 or 0) ~ (b:sign() < 0 and 1 or 0)) == 1 then
res:neg_()
end
return res:add_(a):tdiv_(b)
end
-- Integer round division (rounding towards nearest integer) (in-place).
function BigInt.rdiv_(a: BigInt, b: BigInt_convertible): BigInt
## ensure_bigints(a, b)
local res: BigInt <close> = BigInt.rdiv(a, b)
a:copy_(res)
return a
end
-- Integer exponentiation.
function BigInt.pow(base: BigInt_convertible, exp: usize): BigInt
## ensure_bigints(base)
local res: BigInt = BigInt.new()
mpz_pow_ui(res.mpz, base.mpz, exp)
return res
end
-- Integer exponentiation (in-place).
function BigInt.pow_(base: BigInt, exp: usize): BigInt
## ensure_bigints(base)
mpz_pow_ui(base.mpz, base.mpz, exp)
return base
end
-- Integer modulo operation (result always non-negative).
function BigInt.mod(a: BigInt_convertible, b: BigInt_convertible): BigInt
## ensure_bigints(a, b)
local res: BigInt = BigInt.new()
mpz_mod(res.mpz, a.mpz, b.mpz)
return res
end
-- Integer modulo operation (result always non-negative).
function BigInt.mod_(a: BigInt, b: BigInt_convertible): BigInt
## ensure_bigints(a, b)
mpz_mod(a.mpz, a.mpz, b.mpz)
return a
end
-- Integer truncate modulo operation (rounding towards 0).
function BigInt.tmod(a: BigInt_convertible, b: BigInt_convertible): BigInt
## ensure_bigints(a, b)
local res: BigInt = BigInt.new()
mpz_tdiv_r(res.mpz, a.mpz, b.mpz)
return res
end
-- Integer truncate modulo operation (rounding towards 0) (in-place).
function BigInt.tmod_(a: BigInt, b: BigInt_convertible): BigInt
## ensure_bigints(a, b)
mpz_tdiv_r(a.mpz, a.mpz, b.mpz)
return a
end
-- Integer floor modulo operation (rounding towards minus infinity).
function BigInt.fmod(a: BigInt_convertible, b: BigInt_convertible): BigInt
## ensure_bigints(a, b)
local res: BigInt = BigInt.new()
mpz_fdiv_r(res.mpz, a.mpz, b.mpz)
return res
end
-- Integer floor modulo operation (rounding towards minus infinity) (in-place).
function BigInt.fmod_(a: BigInt_convertible, b: BigInt_convertible): BigInt
## ensure_bigints(a, b)
mpz_fdiv_r(a.mpz, a.mpz, b.mpz)
return a
end
--------------------------------------------------------------------------------
-- Bitwise operations
-- Performs a bitwise NOT, that is, the one's complement.
function BigInt.bnot(a: BigInt_convertible): BigInt
## ensure_bigints(a)
local res: BigInt = BigInt.new()
mpz_com(res.mpz, a.mpz)
return res
end
-- Performs a bitwise NOT, that is, the one's complement (in-place).
function BigInt.bnot_(a: BigInt): BigInt
## ensure_bigints(a)
mpz_com(a.mpz, a.mpz)
return a
end
-- Performs a logical left shift.
function BigInt.shl(a: BigInt_convertible, count: usize): BigInt
## ensure_bigints(a)
local res: BigInt = BigInt.new()
mpz_mul_2exp(res.mpz, a.mpz, count)
return res
end
-- Performs a logical left shift (in-place).
function BigInt.shl_(a: BigInt, count: usize): BigInt
## ensure_bigints(a)
mpz_mul_2exp(a.mpz, a.mpz, count)
return a
end
--[[
Performs a right shift.
Beware, this is not really a logical right shift for negative values.
]]
function BigInt.shr(a: BigInt_convertible, count: usize): BigInt
## ensure_bigints(a)
local res: BigInt = BigInt.new()
mpz_tdiv_q_2exp(res.mpz, a.mpz, count)
return res
end
-- Performs a right shift (in-place).
function BigInt.shr_(a: BigInt, count: usize): BigInt
## ensure_bigints(a)
mpz_tdiv_q_2exp(a.mpz, a.mpz, count)
return a
end
-- Performs an arithmetic right shift.
function BigInt.asr(a: BigInt_convertible, count: usize): BigInt
## ensure_bigints(a)
local res: BigInt = BigInt.new()
mpz_fdiv_q_2exp(res.mpz, a.mpz, count)
return res
end
-- Performs an arithmetic right shift (in-place).
function BigInt.asr_(a: BigInt, count: usize): BigInt
## ensure_bigints(a)
mpz_fdiv_q_2exp(a.mpz, a.mpz, count)
return a
end
-- Performs a bitwise OR.
function BigInt.bor(a: BigInt_convertible, b: BigInt_convertible): BigInt
## ensure_bigints(a, b)
local res: BigInt = BigInt.new()
mpz_ior(res.mpz, a.mpz, b.mpz)
return res
end
-- Performs a bitwise OR (in-place).
function BigInt.bor_(a: BigInt, b: BigInt_convertible): BigInt
## ensure_bigints(a, b)
mpz_ior(a.mpz, a.mpz, b.mpz)
return a
end
-- Performs a bitwise AND.
function BigInt.band(a: BigInt_convertible, b: BigInt_convertible): BigInt
## ensure_bigints(a, b)
local res: BigInt = BigInt.new()
mpz_and(res.mpz, a.mpz, b.mpz)
return res
end
-- Performs a bitwise AND (in-place).
function BigInt.band_(a: BigInt, b: BigInt_convertible): BigInt
## ensure_bigints(a, b)
mpz_and(a.mpz, a.mpz, b.mpz)
return a
end
-- Performs a bitwise XOR.
function BigInt.bxor(a: BigInt_convertible, b: BigInt_convertible): BigInt
## ensure_bigints(a, b)
local res: BigInt = BigInt.new()
mpz_xor(res.mpz, a.mpz, b.mpz)
return res
end
-- Performs a bitwise XOR (in-place).
function BigInt.bxor_(a: BigInt, b: BigInt_convertible): BigInt
## ensure_bigints(a, b)
mpz_xor(a.mpz, a.mpz, b.mpz)
return a
end
--------------------------------------------------------------------------------
-- Extra operations
-- Computes the modular inverse.
function BigInt.invmod(a: BigInt_convertible, b: BigInt_convertible): BigInt
## ensure_bigints(a, b)
local res: BigInt = BigInt.new()
mpz_invert(res.mpz, a.mpz, b.mpz)
return res
end
-- Computes the modular inverse (in-place).
function BigInt.invmod_(a: BigInt, b: BigInt_convertible): BigInt
## ensure_bigints(a, b)
mpz_invert(a.mpz, a.mpz, b.mpz)
return a
end
-- Computes the modular exponentiation.
function BigInt.powmod(base: BigInt_convertible, exp: BigInt_convertible, mod: BigInt_convertible): BigInt
## ensure_bigints(base, exp, mod)
local res: BigInt = BigInt.new()
mpz_powm(res.mpz, base.mpz, exp.mpz, mod.mpz)
return res
end
-- Computes the modular exponentiation (in-place).
function BigInt.powmod_(base: BigInt_convertible, exp: BigInt_convertible, mod: BigInt_convertible): BigInt
## ensure_bigints(base, exp, mod)
mpz_powm(base.mpz, base.mpz, exp.mpz, mod.mpz)
return base
end
-- Computes the division and remainder operations together.
function BigInt.tdivrem(n: BigInt_convertible, d: BigInt_convertible): (BigInt, BigInt)
## ensure_bigints(n, d)
local q: BigInt, r: BigInt = BigInt.new(), BigInt.new()
mpz_tdiv_qr(q.mpz, r.mpz, n.mpz, d.mpz)
return q, r
end
-- Computes the greatest common divisor.
function BigInt.gcd(a: BigInt_convertible, b: BigInt_convertible): BigInt
## ensure_bigints(a, b)
local res: BigInt = BigInt.new()
mpz_gcd(res.mpz, a.mpz, b.mpz)
return res
end
-- Computes the least common multiple.
function BigInt.lcm(a: BigInt_convertible, b: BigInt_convertible): BigInt
## ensure_bigints(a, b)
local res: BigInt = BigInt.new()
mpz_lcm(res.mpz, a.mpz, b.mpz)
return res
end
--------------------------------------------------------------------------------
-- Metamethods
-- Alias for as `add` (to allow using binary '+' operator).
function BigInt.__add(a: BigInt_convertible, b: BigInt_convertible): BigInt
return BigInt.add(a, b)
end
-- Alias for as `sub` (to allow using binary '-' operator).
function BigInt.__sub(a: BigInt_convertible, b: BigInt_convertible): BigInt
return BigInt.sub(a, b)
end
-- Alias for as `mul` (to allow using binary '*' operator).
function BigInt.__mul(a: BigInt_convertible, b: BigInt_convertible): BigInt
return BigInt.mul(a, b)
end
-- Alias for as `fdiv` (to allow using binary '//' operator).
function BigInt.__idiv(a: BigInt_convertible, b: BigInt_convertible): BigInt
return BigInt.fdiv(a, b)
end
-- Alias for as `tdiv` (to allow using binary '///' operator).
function BigInt.__tdiv(a: BigInt_convertible, b: BigInt_convertible): BigInt
return BigInt.tdiv(a, b)
end
-- Alias for as `fmod` (to allow using binary '%' operator).
function BigInt.__mod(a: BigInt_convertible, b: BigInt_convertible): BigInt
return BigInt.fmod(a, b)
end
-- Alias for as `tmod` (to allow using binary '%%%' operator).
function BigInt.__tmod(a: BigInt_convertible, b: BigInt_convertible): BigInt
return BigInt.tmod(a, b)
end
-- Alias for as `pow` (to allow using binary '^' operator).
function BigInt.__pow(base: BigInt_convertible, exp: integer): BigInt
return BigInt.pow(base, exp)
end
-- Alias for as `band` (to allow using binary '&' operator).
function BigInt.__band(a: BigInt_convertible, b: BigInt_convertible): BigInt
return BigInt.band(a, b)
end
-- Alias for as `bor` (to allow using binary '|' operator).
function BigInt.__bor(a: BigInt_convertible, b: BigInt_convertible): BigInt
return BigInt.bor(a, b)
end
-- Alias for as `bxor` (to allow using binary '~' operator).
function BigInt.__bxor(a: BigInt_convertible, b: BigInt_convertible): BigInt
return BigInt.bxor(a, b)
end
-- Alias for as `neg` (to allow using unary '-' operator).
function BigInt.__unm(x: BigInt): BigInt
return BigInt.neg(x)
end
-- Alias for as `shl` (to allow using binary '<<' operator).
function BigInt.__shl(a: BigInt_convertible, count: usize): BigInt
return BigInt.shl(a, count)
end
-- Alias for as `shr` (to allow using binary '>>' operator).
function BigInt.__shr(a: BigInt_convertible, count: usize): BigInt
return BigInt.shr(a, count)
end
-- Alias for as `asr` (to allow using binary '>>>' operator).
function BigInt.__asr(a: BigInt_convertible, count: usize): BigInt
return BigInt.asr(a, count)
end
-- Alias for as `bnot` (to allow using unary '~' operator).
function BigInt.__bnot(a: BigInt): BigInt
return BigInt.bnot(a)
end
-- Alias for as `lt` (to allow using binary '<' operator).
function BigInt.__lt(a: BigInt_convertible, b: BigInt_convertible): boolean
return BigInt.lt(a, b)
end
-- Alias for as `le` (to allow using binary '<=' operator).
function BigInt.__le(a: BigInt_convertible, b: BigInt_convertible): boolean
return BigInt.le(a, b)
end
-- Alias for as `eq` (to allow using binary '==' operator).
function BigInt.__eq(a: BigInt_convertible, b: BigInt_convertible): boolean
return BigInt.eq(a, b)
end
-- Bundle mini GMP.
##[====[
local cdefs = require 'nelua.cdefs'
cdefs.include_hooks['@mini-gmp.h'] = [==[
/* mini-gmp, a minimalistic implementation of a GNU GMP subset.
Copyright 2011-2015, 2017, 2019-2020 Free Software Foundation, Inc.
This file is part of the GNU MP Library.
The GNU MP Library is free software; you can redistribute it and/or modify
it under the terms of either:
* the GNU Lesser General Public License as published by the Free
Software Foundation; either version 3 of the License, or (at your
option) any later version.
or
* the GNU General Public License as published by the Free Software
Foundation; either version 2 of the License, or (at your option) any
later version.
or both in parallel, as here.
The GNU MP Library is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received copies of the GNU General Public License and the
GNU Lesser General Public License along with the GNU MP Library. If not,
see https://www.gnu.org/licenses/. */