-
Notifications
You must be signed in to change notification settings - Fork 33
/
siqs_factorization.pl
executable file
·2706 lines (1991 loc) · 70.5 KB
/
siqs_factorization.pl
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
#!/usr/bin/perl
=begin
This script factorizes a natural number given as a command line
parameter into its prime factors. It first attempts to use trial
division to find very small factors, then uses other special-purpose
factorization methods to find slightly larger factors. If any large
factors remain, it uses the Self-Initializing Quadratic Sieve (SIQS) [2]
to factorize those.
[2] Contini, Scott Patrick. 'Factoring integers with the self-
initializing quadratic sieve.' (1997).
=cut
use 5.020;
use strict;
use warnings;
use Math::GMPz;
use POSIX qw(ULONG_MAX);
use experimental qw(signatures);
use ntheory qw(
urandomm valuation sqrtmod invmod random_prime factor_exp vecmin
is_square divisors todigits primes prime_iterator
);
use Math::Prime::Util::GMP qw(
is_power powmod vecprod sqrtint rootint logint is_prime
gcd sieve_primes consecutive_integer_lcm lucas_sequence
);
my $ZERO = Math::GMPz->new(0);
my $ONE = Math::GMPz->new(1);
local $| = 1;
# Tuning parameters
use constant {
MASK_LIMIT => 200, # show Cn if n > MASK_LIMIT, where n ~ log_10(N)
LOOK_FOR_SMALL_FACTORS => 1,
TRIAL_DIVISION_LIMIT => 1_000_000,
PHI_FINDER_ITERATIONS => 100_000,
FERMAT_ITERATIONS => 100_000,
NEAR_POWER_ITERATIONS => 1_000,
PELL_ITERATIONS => 50_000,
FLT_ITERATIONS => 200_000,
HOLF_ITERATIONS => 100_000,
MBE_ITERATIONS => 100,
MILLER_RABIN_ITERATIONS => 100,
LUCAS_MILLER_ITERATIONS => 50,
SIQS_TRIAL_DIVISION_EPS => 25,
SIQS_MIN_PRIME_POLYNOMIAL => 400,
SIQS_MAX_PRIME_POLYNOMIAL => 4000,
};
my @small_primes = sieve_primes(2, TRIAL_DIVISION_LIMIT);
package Polynomial {
sub new ($class, $coeff, $A = undef, $B = undef) {
bless {
a => $A,
b => $B,
coeff => $coeff,
}, $class;
}
sub eval ($self, $x) {
my $res = $ZERO;
foreach my $k (@{$self->{coeff}}) {
$res *= $x;
$res += $k;
}
return $res;
}
}
package FactorBasePrime {
sub new ($class, $p, $t, $lp) {
bless {
p => $p,
soln1 => undef,
soln2 => undef,
t => $t,
lp => $lp,
ainv => undef,
}, $class;
}
}
sub siqs_factor_base_primes ($n, $nf) {
my @factor_base;
foreach my $p (@small_primes) {
my $t = sqrtmod($n, $p) // next;
my $lp = sprintf('%0.f', log($p) / log(2));
push @factor_base, FactorBasePrime->new($p, $t, $lp);
if (scalar(@factor_base) >= $nf) {
last;
}
}
return \@factor_base;
}
sub siqs_create_poly ($A, $B, $n, $factor_base, $first) {
my $B_orig = $B;
if (($B << 1) > $A) {
$B = $A - $B;
}
# 0 < $B or die 'error';
# 2 * $B <= $A or die 'error';
# ($B * $B - $n) % $A == 0 or die 'error';
my $g = Polynomial->new([$A * $A, ($A * $B) << 1, $B * $B - $n], $A, $B_orig);
my $h = Polynomial->new([$A, $B]);
foreach my $fb (@$factor_base) {
next if Math::GMPz::Rmpz_divisible_ui_p($A, $fb->{p});
#<<<
$fb->{ainv} = int(invmod($A, $fb->{p})) if $first;
$fb->{soln1} = int(($fb->{ainv} * ( $fb->{t} - $B)) % $fb->{p});
$fb->{soln2} = int(($fb->{ainv} * (-$fb->{t} - $B)) % $fb->{p});
#>>>
}
return ($g, $h);
}
sub siqs_find_first_poly ($n, $m, $factor_base) {
my $p_min_i;
my $p_max_i;
foreach my $i (0 .. $#{$factor_base}) {
my $fb = $factor_base->[$i];
if (not defined($p_min_i) and $fb->{p} >= SIQS_MIN_PRIME_POLYNOMIAL) {
$p_min_i = $i;
}
if (not defined($p_max_i) and $fb->{p} > SIQS_MAX_PRIME_POLYNOMIAL) {
$p_max_i = $i - 1;
last;
}
}
# The following may happen if the factor base is small
if (not defined($p_max_i)) {
$p_max_i = $#{$factor_base};
}
if (not defined($p_min_i)) {
$p_min_i = 5;
}
if ($p_max_i - $p_min_i < 20) {
$p_min_i = vecmin($p_min_i, 5);
}
my $target0 = (log("$n") + log(2)) / 2 - log("$m");
my $target1 = $target0 - log(($factor_base->[$p_min_i]{p} + $factor_base->[$p_max_i]{p}) / 2) / 2;
# find q such that the product of factor_base[q_i] is approximately
# sqrt(2 * n) / m; try a few different sets to find a good one
my ($best_q, $best_a, $best_ratio);
for (1 .. 30) {
my $A = $ONE;
my $log_A = 0;
my %Q;
while ($log_A < $target1) {
my $p_i = 0;
while ($p_i == 0 or exists $Q{$p_i}) {
$p_i = $p_min_i + urandomm($p_max_i - $p_min_i + 1);
}
my $fb = $factor_base->[$p_i];
$A *= $fb->{p};
$log_A += log($fb->{p});
$Q{$p_i} = $fb;
}
my $ratio = exp($log_A - $target0);
# ratio too small seems to be not good
if ( !defined($best_ratio)
or ($ratio >= 0.9 and $ratio < $best_ratio)
or ($best_ratio < 0.9 and $ratio > $best_ratio)) {
$best_q = \%Q;
$best_a = $A;
$best_ratio = $ratio;
}
}
my $A = $best_a;
my $B = $ZERO;
my @arr;
foreach my $fb (values %$best_q) {
my $p = $fb->{p};
#($A % $p == 0) or die 'error';
my $r = $A / $p;
#$fb->{t} // die 'error';
#gcd($r, $p) == 1 or die 'error';
my $gamma = ($fb->{t} * int(invmod($r, $p))) % $p;
if ($gamma > ($p >> 1)) {
$gamma = $p - $gamma;
}
my $t = $r * $gamma;
$B += $t;
push @arr, $t;
}
my ($g, $h) = siqs_create_poly($A, $B, $n, $factor_base, 1);
return ($g, $h, \@arr);
}
sub siqs_find_next_poly ($n, $factor_base, $i, $g, $arr) {
# Compute the (i+1)-th polynomials for the Self-Initializing
# Quadratic Sieve, given that g is the i-th polynomial.
my $v = valuation($i, 2);
my $z = ((($i >> ($v + 1)) & 1) == 0) ? -1 : 1;
my $A = $g->{a};
my $B = ($g->{b} + 2 * $z * $arr->[$v]) % $A;
return siqs_create_poly($A, $B, $n, $factor_base, 0);
}
sub siqs_sieve ($factor_base, $m) {
# Perform the sieving step of the SIQS. Return the sieve array.
my @sieve_array = (0) x (2 * $m + 1);
foreach my $fb (@$factor_base) {
$fb->{p} > 100 or next;
$fb->{soln1} // next;
my $p = $fb->{p};
my $lp = $fb->{lp};
my $end = 2 * $m;
my $i_start_1 = -int(($m + $fb->{soln1}) / $p);
my $a_start_1 = int($fb->{soln1} + $i_start_1 * $p);
for (my $i = $a_start_1 + $m ; $i <= $end ; $i += $p) {
$sieve_array[$i] += $lp;
}
my $i_start_2 = -int(($m + $fb->{soln2}) / $p);
my $a_start_2 = int($fb->{soln2} + $i_start_2 * $p);
for (my $i = $a_start_2 + $m ; $i <= $end ; $i += $p) {
$sieve_array[$i] += $lp;
}
}
return \@sieve_array;
}
sub siqs_trial_divide ($n, $factor_base_info) {
# Determine whether the given number can be fully factorized into
# primes from the factors base. If so, return the indices of the
# factors from the factor base. If not, return undef.
my $factor_prod = $factor_base_info->{prod};
state $g = Math::GMPz::Rmpz_init_nobless();
state $t = Math::GMPz::Rmpz_init_nobless();
Math::GMPz::Rmpz_set($t, $n);
Math::GMPz::Rmpz_gcd($g, $t, $factor_prod);
while (Math::GMPz::Rmpz_cmp_ui($g, 1) > 0) {
Math::GMPz::Rmpz_remove($t, $t, $g);
if (Math::GMPz::Rmpz_cmp_ui($t, 1) == 0) {
my $factor_index = $factor_base_info->{index};
return [map { [$factor_index->{$_->[0]}, $_->[1]] } factor_exp($n)];
}
Math::GMPz::Rmpz_gcd($g, $t, $g);
}
return undef;
}
sub siqs_trial_division ($n, $sieve_array, $factor_base_info, $smooth_relations, $g, $h, $m, $req_relations) {
# Perform the trial division step of the Self-Initializing Quadratic Sieve.
my $limit = (log("$m") + log("$n") / 2) / log(2) - SIQS_TRIAL_DIVISION_EPS;
foreach my $i (0 .. $#{$sieve_array}) {
next if ((my $sa = $sieve_array->[$i]) < $limit);
my $x = $i - $m;
my $gx = abs($g->eval($x));
my $divisors_idx = siqs_trial_divide($gx, $factor_base_info) // next;
my $u = $h->eval($x);
my $v = $gx;
#(($u * $u) % $n == ($v % $n)) or die 'error';
push @$smooth_relations, [$u, $v, $divisors_idx];
if (scalar(@$smooth_relations) >= $req_relations) {
return 1;
}
}
return 0;
}
sub siqs_build_matrix ($factor_base, $smooth_relations) {
# Build the matrix for the linear algebra step of the Quadratic Sieve.
my $fb = scalar(@$factor_base);
my @matrix;
foreach my $sr (@$smooth_relations) {
my @row = (0) x $fb;
foreach my $pair (@{$sr->[2]}) {
$row[$pair->[0]] = $pair->[1] % 2;
}
push @matrix, \@row;
}
return \@matrix;
}
sub siqs_build_matrix_opt ($M) {
# Convert the given matrix M of 0s and 1s into a list of numbers m
# that correspond to the columns of the matrix.
# The j-th number encodes the j-th column of matrix M in binary:
# The i-th bit of m[i] is equal to M[i][j].
my $m = scalar(@{$M->[0]});
my @cols_binary = ("") x $m;
foreach my $mi (@$M) {
foreach my $j (0 .. $#{$mi}) {
$cols_binary[$j] .= $mi->[$j];
}
}
#<<<
return ([map {
Math::GMPz::Rmpz_init_set_str(scalar reverse($_), 2)
} @cols_binary], scalar(@$M), $m);
#>>>
}
sub find_pivot_column_opt ($M, $j) {
# For a matrix produced by siqs_build_matrix_opt, return the row of
# the first non-zero entry in column j, or None if no such row exists.
my $v = $M->[$j];
if ($v == 0) {
return undef;
}
return valuation($v, 2);
}
sub siqs_solve_matrix_opt ($M, $n, $m) {
# Perform the linear algebra step of the SIQS. Perform fast
# Gaussian elimination to determine pairs of perfect squares mod n.
# Use the optimizations described in [1].
# [1] Koç, Çetin K., and Sarath N. Arachchige. 'A Fast Algorithm for
# Gaussian Elimination over GF (2) and its Implementation on the
# GAPP.' Journal of Parallel and Distributed Computing 13.1
# (1991): 118-122.
my @row_is_marked = (0) x $n;
my @pivots = (-1) x $m;
foreach my $j (0 .. $m - 1) {
my $i = find_pivot_column_opt($M, $j) // next;
$pivots[$j] = $i;
$row_is_marked[$i] = 1;
foreach my $k (0 .. $m - 1) {
if ($k != $j and Math::GMPz::Rmpz_tstbit($M->[$k], $i)) {
Math::GMPz::Rmpz_xor($M->[$k], $M->[$k], $M->[$j]);
}
}
}
my @perf_squares;
foreach my $i (0 .. $n - 1) {
if (not $row_is_marked[$i]) {
my @perfect_sq_indices = ($i);
foreach my $j (0 .. $m - 1) {
if (Math::GMPz::Rmpz_tstbit($M->[$j], $i)) {
push @perfect_sq_indices, $pivots[$j];
}
}
push @perf_squares, \@perfect_sq_indices;
}
}
return \@perf_squares;
}
sub siqs_calc_sqrts ($n, $square_indices, $smooth_relations) {
# Given on of the solutions returned by siqs_solve_matrix_opt and
# the corresponding smooth relations, calculate the pair [a, b], such
# that a^2 = b^2 (mod n).
my $r1 = $ONE;
my $r2 = $ONE;
foreach my $i (@$square_indices) {
($r1 *= $smooth_relations->[$i][0]) %= $n;
($r2 *= $smooth_relations->[$i][1]);
}
$r2 = Math::GMPz->new(sqrtint($r2));
return ($r1, $r2);
}
sub siqs_factor_from_square ($n, $square_indices, $smooth_relations) {
# Given one of the solutions returned by siqs_solve_matrix_opt,
# return the factor f determined by f = gcd(a - b, n), where
# a, b are calculated from the solution such that a*a = b*b (mod n).
# Return f, a factor of n (possibly a trivial one).
my ($sqrt1, $sqrt2) = siqs_calc_sqrts($n, $square_indices, $smooth_relations);
#(($sqrt1 * $sqrt1) % $n == ($sqrt2 * $sqrt2) % $n) or die 'error';
return Math::GMPz->new(gcd($sqrt1 - $sqrt2, $n));
}
sub siqs_find_more_factors_gcd (@numbers) {
my %res;
foreach my $i (0 .. $#numbers) {
my $n = $numbers[$i];
$res{$n} = $n;
foreach my $k ($i + 1 .. $#numbers) {
my $m = $numbers[$k];
my $fact = Math::GMPz->new(gcd($n, $m));
if ($fact != 1 and $fact != $n and $fact != $m) {
if (not exists($res{$fact})) {
say "SIQS: GCD found non-trivial factor: $fact";
$res{$fact} = $fact;
}
my $t1 = $n / $fact;
my $t2 = $m / $fact;
$res{$t1} = $t1;
$res{$t2} = $t2;
}
}
}
return (values %res);
}
sub siqs_find_factors ($n, $perfect_squares, $smooth_relations) {
# Perform the last step of the Self-Initializing Quadratic Field.
# Given the solutions returned by siqs_solve_matrix_opt, attempt to
# identify a number of (not necessarily prime) factors of n, and
# return them.
my @factors;
my $rem = $n;
my %non_prime_factors;
my %prime_factors;
foreach my $square_indices (@$perfect_squares) {
my $fact = siqs_factor_from_square($n, $square_indices, $smooth_relations);
if ($fact > 1 and $fact < $rem) {
if (is_prime($fact)) {
if (not exists $prime_factors{$fact}) {
say "SIQS: Prime factor found: $fact";
$prime_factors{$fact} = $fact;
}
$rem = check_factor($rem, $fact, \@factors);
if ($rem == 1) {
last;
}
if (is_prime($rem)) {
push @factors, $rem;
$rem = 1;
last;
}
if (defined(my $root = check_perfect_power($rem))) {
say "SIQS: Perfect power detected with root: $root";
push @factors, $root;
$rem = 1;
last;
}
}
else {
if (not exists $non_prime_factors{$fact}) {
say "SIQS: Composite factor found: $fact";
$non_prime_factors{$fact} = $fact;
}
}
}
}
if ($rem != 1 and keys(%non_prime_factors)) {
$non_prime_factors{$rem} = $rem;
my @primes;
my @composites;
foreach my $fact (siqs_find_more_factors_gcd(values %non_prime_factors)) {
if (is_prime($fact)) {
push @primes, $fact;
}
elsif ($fact > 1) {
push @composites, $fact;
}
}
foreach my $fact (@primes, @composites) {
if ($fact != $rem and $rem % $fact == 0) {
say "SIQS: Using non-trivial factor from GCD: $fact";
$rem = check_factor($rem, $fact, \@factors);
}
if ($rem == 1 or is_prime($rem)) {
last;
}
}
}
if ($rem != 1) {
push @factors, $rem;
}
return @factors;
}
sub siqs_choose_range ($n) {
# Choose m for sieving in [-m, m].
$n = "$n";
return sprintf('%.0f', exp(sqrt(log($n) * log(log($n))) / 2));
}
sub siqs_choose_nf ($n) {
# Choose parameters nf (sieve of factor base)
$n = "$n";
return sprintf('%.0f', exp(sqrt(log($n) * log(log($n))))**(sqrt(2) / 4));
}
sub siqs_choose_nf2 ($n) {
# Choose parameters nf (sieve of factor base)
$n = "$n";
return sprintf('%.0f', exp(sqrt(log($n) * log(log($n))) / 2));
}
sub siqs_factorize ($n, $nf) {
# Use the Self-Initializing Quadratic Sieve algorithm to identify
# one or more non-trivial factors of the given number n. Return the
# factors as a list.
my $m = siqs_choose_range($n);
my @factors;
my $factor_base = siqs_factor_base_primes($n, $nf);
my $factor_prod = Math::GMPz->new(vecprod(map { $_->{p} } @$factor_base));
my %factor_base_index;
@factor_base_index{map { $_->{p} } @{$factor_base}} = 0 .. $#{$factor_base};
my $factor_base_info = {
base => $factor_base,
prod => $factor_prod,
index => \%factor_base_index,
};
my $smooth_relations = [];
my $required_relations_ratio = 1;
my $success = 0;
my $prev_cnt = 0;
my $i_poly = 0;
my ($g, $h, $arr);
while (not $success) {
say "*** Step 1/2: Finding smooth relations ***";
say "SIQS sieving range: [-$m, $m]";
my $required_relations = sprintf('%.0f', (scalar(@$factor_base) + 1) * $required_relations_ratio);
say "Target: $required_relations relations.";
my $enough_relations = 0;
while (not $enough_relations) {
if ($i_poly == 0) {
($g, $h, $arr) = siqs_find_first_poly($n, $m, $factor_base);
}
else {
($g, $h) = siqs_find_next_poly($n, $factor_base, $i_poly, $g, $arr);
}
if (++$i_poly >= (1 << $#{$arr})) {
$i_poly = 0;
}
my $sieve_array = siqs_sieve($factor_base, $m);
$enough_relations = siqs_trial_division($n, $sieve_array, $factor_base_info, $smooth_relations, $g, $h, $m, $required_relations);
if ( scalar(@$smooth_relations) >= $required_relations
or scalar(@$smooth_relations) > $prev_cnt) {
printf("Progress: %d/%d relations.\r", scalar(@$smooth_relations), $required_relations);
$prev_cnt = scalar(@$smooth_relations);
}
}
say "\n\n*** Step 2/2: Linear Algebra ***";
say "Building matrix for linear algebra step...";
my $M = siqs_build_matrix($factor_base, $smooth_relations);
my ($M_opt, $M_n, $M_m) = siqs_build_matrix_opt($M);
say "Finding perfect squares using Gaussian elimination...";
my $perfect_squares = siqs_solve_matrix_opt($M_opt, $M_n, $M_m);
say "Finding factors from congruences of squares...\n";
@factors = siqs_find_factors($n, $perfect_squares, $smooth_relations);
if (scalar(@factors) > 1) {
$success = 1;
}
else {
say "Failed to find a solution. Finding more relations...";
$required_relations_ratio += 0.05;
}
}
return @factors;
}
sub check_factor ($n, $i, $factors) {
while ($n % $i == 0) {
$n /= $i;
push @$factors, $i;
if (is_prime($n)) {
push @$factors, $n;
return 1;
}
}
return $n;
}
sub trial_division_small_primes ($n) {
# Perform trial division on the given number n using all primes up
# to upper_bound. Initialize the global variable small_primes with a
# list of all primes <= upper_bound. Return (factors, rem), where
# factors is the list of identified prime factors of n, and rem is the
# remaining factor. If rem = 1, the function terminates early, without
# fully initializing small_primes.
say "[*] Trial division...";
my $factors = [];
my $rem = $n;
foreach my $p (@small_primes) {
if (Math::GMPz::Rmpz_divisible_ui_p($rem, $p)) {
$rem = check_factor($rem, $p, $factors);
last if ($rem == 1);
}
}
return ($factors, $rem);
}
sub fast_fibonacci_factor ($n, $upto) {
my $g = Math::GMPz::Rmpz_init();
my ($P, $Q) = (3, 1);
my $U0 = Math::GMPz::Rmpz_init_set_ui(0);
my $U1 = Math::GMPz::Rmpz_init_set_ui(1);
my $V0 = Math::GMPz::Rmpz_init_set_ui(2);
my $V1 = Math::GMPz::Rmpz_init_set_ui($P);
foreach my $k (2 .. $upto) {
# my ($U, $V) = Math::Prime::Util::GMP::lucas_sequence($n, $P, $Q, $k);
Math::GMPz::Rmpz_set($g, $U1);
Math::GMPz::Rmpz_mul_ui($U1, $U1, $P);
Math::GMPz::Rmpz_submul_ui($U1, $U0, $Q);
Math::GMPz::Rmpz_mod($U1, $U1, $n);
Math::GMPz::Rmpz_set($U0, $g);
Math::GMPz::Rmpz_set($g, $V1);
Math::GMPz::Rmpz_mul_ui($V1, $V1, $P);
Math::GMPz::Rmpz_submul_ui($V1, $V0, $Q);
Math::GMPz::Rmpz_mod($V1, $V1, $n);
Math::GMPz::Rmpz_set($V0, $g);
foreach my $param ([$U1, 0], [$V1, -$P, -2 * $Q, 0]) {
my ($t, @deltas) = @$param;
foreach my $delta (@deltas) {
($delta >= 0)
? Math::GMPz::Rmpz_add_ui($g, $t, $delta)
: Math::GMPz::Rmpz_sub_ui($g, $t, -$delta);
Math::GMPz::Rmpz_gcd($g, $g, $n);
if ( Math::GMPz::Rmpz_cmp_ui($g, 1) > 0
and Math::GMPz::Rmpz_cmp($g, $n) < 0) {
return $g;
}
}
}
}
return undef;
}
sub fast_power_check ($n, $upto) {
state $t = Math::GMPz::Rmpz_init_nobless();
state $g = Math::GMPz::Rmpz_init_nobless();
my $base_limit = vecmin(logint($n, 2), 150);
foreach my $base (2 .. $base_limit) {
Math::GMPz::Rmpz_set_ui($t, $base);
foreach my $exp (2 .. $upto) {
Math::GMPz::Rmpz_mul_ui($t, $t, $base);
foreach my $k ($base <= 10 ? (1 .. ($base_limit >> 1)) : 1) {
Math::GMPz::Rmpz_mul_ui($g, $t, $k);
Math::GMPz::Rmpz_sub_ui($g, $g, 1);
Math::GMPz::Rmpz_gcd($g, $g, $n);
if (Math::GMPz::Rmpz_cmp_ui($g, 1) > 0 and Math::GMPz::Rmpz_cmp($g, $n) < 0) {
return Math::GMPz::Rmpz_init_set($g);
}
Math::GMPz::Rmpz_mul_ui($g, $t, $k);
Math::GMPz::Rmpz_add_ui($g, $g, 1);
Math::GMPz::Rmpz_gcd($g, $g, $n);
if (Math::GMPz::Rmpz_cmp_ui($g, 1) > 0 and Math::GMPz::Rmpz_cmp($g, $n) < 0) {
return Math::GMPz::Rmpz_init_set($g);
}
}
}
}
return undef;
}
sub cyclotomic_polynomial ($n, $x, $m) {
$x = Math::GMPz::Rmpz_init_set_ui($x) if !ref($x);
# Generate the squarefree divisors of n, along
# with the number of prime factors of each divisor
my @sd;
foreach my $pe (factor_exp($n)) {
my ($p) = @$pe;
push @sd, map { [$_->[0] * $p, $_->[1] + 1] } @sd;
push @sd, [$p, 1];
}
push @sd, [Math::GMPz::Rmpz_init_set_ui(1), 0];
my $prod = Math::GMPz::Rmpz_init_set_ui(1);
foreach my $pair (@sd) {
my ($d, $c) = @$pair;
my $base = Math::GMPz::Rmpz_init();
my $exp = CORE::int($n / $d);
Math::GMPz::Rmpz_powm_ui($base, $x, $exp, $m); # x^(n/d) mod m
Math::GMPz::Rmpz_sub_ui($base, $base, 1);
if ($c % 2 == 1) {
Math::GMPz::Rmpz_invert($base, $base, $m) || return $base;
}
Math::GMPz::Rmpz_mul($prod, $prod, $base);
Math::GMPz::Rmpz_mod($prod, $prod, $m);
}
return $prod;
}
sub cyclotomic_factorization ($n) {
my $g = Math::GMPz::Rmpz_init();
my $base_limit = vecmin(1 + logint($n, 2), 1000);
for (my $base = $base_limit ; $base >= 2 ; $base -= 1) {
my $lim = 1 + logint($n, $base);
foreach my $k (1 .. $lim) {
my $c = cyclotomic_polynomial($k, $base, $n);
Math::GMPz::Rmpz_gcd($g, $n, $c);
if ( Math::GMPz::Rmpz_cmp_ui($g, 1) > 0
and Math::GMPz::Rmpz_cmp($g, $n) < 0) {
return $g;
}
}
}
return undef;
}
sub fast_lucasVmod ($P, $n, $m) { # assumes Q = 1
my ($V1, $V2) = (Math::GMPz::Rmpz_init_set_ui(2), Math::GMPz::Rmpz_init_set($P));
foreach my $bit (todigits($n, 2)) {
if ($bit) {
Math::GMPz::Rmpz_mul($V1, $V1, $V2);
Math::GMPz::Rmpz_powm_ui($V2, $V2, 2, $m);
Math::GMPz::Rmpz_sub($V1, $V1, $P);
Math::GMPz::Rmpz_sub_ui($V2, $V2, 2);
Math::GMPz::Rmpz_mod($V1, $V1, $m);
}
else {
Math::GMPz::Rmpz_mul($V2, $V2, $V1);
Math::GMPz::Rmpz_powm_ui($V1, $V1, 2, $m);
Math::GMPz::Rmpz_sub($V2, $V2, $P);
Math::GMPz::Rmpz_sub_ui($V1, $V1, 2);
Math::GMPz::Rmpz_mod($V2, $V2, $m);
}
}
return $V1;
}
sub chebyshev_factorization ($n, $B, $A = 127) {
# The Chebyshev factorization method, taking
# advantage of the smoothness of p-1 or p+1.
my $x = Math::GMPz::Rmpz_init_set_ui($A);
my $i = Math::GMPz::Rmpz_init_set_ui(2);
Math::GMPz::Rmpz_invert($i, $i, $n);
my $chebyshevTmod = sub ($A, $x) {
Math::GMPz::Rmpz_mul_2exp($x, $x, 1);
Math::GMPz::Rmpz_set($x, fast_lucasVmod($x, $A, $n));
Math::GMPz::Rmpz_mul($x, $x, $i);
Math::GMPz::Rmpz_mod($x, $x, $n);
};
my $g = Math::GMPz::Rmpz_init();
my $lnB = 2 * log($B);
my $s = sqrtint($B);
foreach my $p (@{primes(2, $s)}) {
for (1 .. int($lnB / log($p))) {
$chebyshevTmod->($p, $x); # T_k(x) (mod n)
}
}
my $it = prime_iterator($s + 1);
for (my $p = $it->() ; $p <= $B ; $p = $it->()) {
$chebyshevTmod->($p, $x); # T_k(x) (mod n)
Math::GMPz::Rmpz_sub_ui($g, $x, 1);
Math::GMPz::Rmpz_gcd($g, $g, $n);
if (Math::GMPz::Rmpz_cmp_ui($g, 1) > 0) {
return undef if (Math::GMPz::Rmpz_cmp($g, $n) == 0);
return $g;
}
}
return undef;
}
sub fibonacci_factorization ($n, $bound) {
# The Fibonacci factorization method, taking
# advantage of the smoothness of `p - legendre(p, 5)`.
my ($P, $Q) = (1, 0);
for (my $k = 2 ; ; ++$k) {
my $D = (-1)**$k * (2 * $k + 1);
if (Math::GMPz::Rmpz_si_kronecker($D, $n) == -1) {
$Q = (1 - $D) / 4;
last;
}
}
state %cache;
my $g = Math::GMPz::Rmpz_init();
for (; ;) {
return undef if $bound <= 1;
my $d = ($cache{$bound} //= consecutive_integer_lcm($bound));
my ($U, $V) = map { Math::GMPz::Rmpz_init_set_str($_, 10) } lucas_sequence($n, $P, $Q, $d);
foreach my $t ($U, $V - 2, $V, $V + 2) {
Math::GMPz::Rmpz_gcd($g, $t, $n);
if ( Math::GMPz::Rmpz_cmp_ui($g, 1) > 0
and Math::GMPz::Rmpz_cmp($g, $n) < 0) {
return $g;
}
}
if ($U == 0) {
say ":: p±1 seems to be $bound-smooth...";