mirrored from git://git.sv.gnu.org/coreutils.git
-
Notifications
You must be signed in to change notification settings - Fork 954
/
Copy pathfactor.c
2697 lines (2285 loc) · 76.6 KB
/
factor.c
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
/* factor -- print prime factors of n.
Copyright (C) 1986-2025 Free Software Foundation, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program 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 a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>. */
/* Originally written by Paul Rubin <phr@ocf.berkeley.edu>.
Adapted for GNU, fixed to factor UINT_MAX by Jim Meyering.
Arbitrary-precision code adapted by James Youngman from Torbjörn
Granlund's factorize.c, from GNU MP version 4.2.2.
In 2012, the core was rewritten by Torbjörn Granlund and Niels Möller.
Contains code from GNU MP. */
/* Efficiently factor numbers that fit in one or two words (word = uintmax_t),
or, with GMP, numbers of any size.
Code organization:
There are several variants of many functions, for handling one word, two
words, and GMP's mpz_t type. If the one-word variant is called foo, the
two-word variant will be foo2, and the one for mpz_t will be mp_foo. In
some cases, the plain function variants will handle both one-word and
two-word numbers, evidenced by function arguments.
The factoring code for two words will fall into the code for one word when
progress allows that.
Algorithm:
(1) Perform trial division using a small primes table, but without hardware
division since the primes table store inverses modulo the word base.
(The GMP variant of this code doesn't make use of the precomputed
inverses, but instead relies on GMP for fast divisibility testing.)
(2) Check the nature of any non-factored part using Miller-Rabin for
detecting composites, and Lucas for detecting primes.
(3) Factor any remaining composite part using the Pollard-Brent rho
algorithm or if USE_SQUFOF is defined to 1, try that first.
Status of found factors are checked again using Miller-Rabin and Lucas.
We prefer using Hensel norm in the divisions, not the more familiar
Euclidean norm, since the former leads to much faster code. In the
Pollard-Brent rho code and the prime testing code, we use Montgomery's
trick of multiplying all n-residues by the word base, allowing cheap Hensel
reductions mod n.
The GMP code uses an algorithm that can be considerably slower;
for example, on a circa-2017 Intel Xeon Silver 4116, factoring
2^{127}-3 takes about 50 ms with the two-word algorithm but would
take about 750 ms with the GMP code.
Improvements:
* Use modular inverses also for exact division in the Lucas code, and
elsewhere. A problem is to locate the inverses not from an index, but
from a prime. We might instead compute the inverse on-the-fly.
* Tune trial division table size (not forgetting that this is a standalone
program where the table will be read from secondary storage for
each invocation).
* Implement less naive powm, using k-ary exponentiation for k = 3 or
perhaps k = 4.
* Try to speed trial division code for single uintmax_t numbers, i.e., the
code using DIVBLOCK. It currently runs at 2 cycles per prime (Intel SBR,
IBR), 3 cycles per prime (AMD Stars) and 5 cycles per prime (AMD BD) when
using gcc 4.6 and 4.7. Some software pipelining should help; 1, 2, and 4
respectively cycles ought to be possible.
* The redcify function could be vastly improved by using (plain Euclidean)
pre-inversion (such as GMP's invert_limb) and udiv_qrnnd_preinv (from
GMP's gmp-impl.h). The redcify2 function could be vastly improved using
similar methods. These functions currently dominate run time when using
the -w option.
*/
/* Whether to recursively factor to prove primality,
or run faster probabilistic tests. */
#ifndef PROVE_PRIMALITY
# define PROVE_PRIMALITY 1
#endif
/* Faster for certain ranges but less general. */
#ifndef USE_SQUFOF
# define USE_SQUFOF 0
#endif
/* Output SQUFOF statistics. */
#ifndef STAT_SQUFOF
# define STAT_SQUFOF 0
#endif
#include <config.h>
#include <getopt.h>
#include <stdbit.h>
#include <stdio.h>
#include <gmp.h>
#include "system.h"
#include "assure.h"
#include "c-ctype.h"
#include "full-write.h"
#include "quote.h"
#include "readtokens.h"
#include "xstrtol.h"
/* The official name of this program (e.g., no 'g' prefix). */
#define PROGRAM_NAME "factor"
#define AUTHORS \
proper_name ("Paul Rubin"), \
proper_name_lite ("Torbjorn Granlund", "Torbj\303\266rn Granlund"), \
proper_name_lite ("Niels Moller", "Niels M\303\266ller")
/* Token delimiters when reading from a file. */
#define DELIM "\n\t "
#ifndef USE_LONGLONG_H
/* With the way we use longlong.h, it's only safe to use
when UWtype = UHWtype, as there were various cases
(as can be seen in the history for longlong.h) where
for example, _LP64 was required to enable W_TYPE_SIZE==64 code,
to avoid compile time or run time issues. */
# if LONG_MAX == INTMAX_MAX
# define USE_LONGLONG_H 1
# endif
#endif
#define W_TYPE_SIZE UINTMAX_WIDTH
#if USE_LONGLONG_H
/* Make definitions for longlong.h to make it do what it can do for us */
# define UWtype uintmax_t
# define UHWtype unsigned long int
# undef UDWtype
# if HAVE_ATTRIBUTE_MODE
typedef unsigned int UQItype __attribute__ ((mode (QI)));
typedef int SItype __attribute__ ((mode (SI)));
typedef unsigned int USItype __attribute__ ((mode (SI)));
typedef int DItype __attribute__ ((mode (DI)));
typedef unsigned int UDItype __attribute__ ((mode (DI)));
# else
typedef unsigned char UQItype;
typedef long SItype;
typedef unsigned long int USItype;
# if HAVE_LONG_LONG_INT
typedef long long int DItype;
typedef unsigned long long int UDItype;
# else /* Assume `long' gives us a wide enough type. Needed for hppa2.0w. */
typedef long int DItype;
typedef unsigned long int UDItype;
# endif
# endif
# define LONGLONG_STANDALONE /* Don't require GMP's longlong.h mdep files */
# define ASSERT(x) /* FIXME make longlong.h really standalone */
# define __GMP_DECLSPEC /* FIXME make longlong.h really standalone */
# ifndef __GMP_GNUC_PREREQ
# define __GMP_GNUC_PREREQ(a,b) 1
# endif
/* longlong.h uses these macros only in certain system compiler combinations.
Ensure usage to pacify -Wunused-macros. */
# if (defined ASSERT || defined UHWtype \
|| defined __GMP_DECLSPEC || defined __GMP_GNUC_PREREQ)
# endif
# if _ARCH_PPC
# define HAVE_HOST_CPU_FAMILY_powerpc 1
# endif
# include "longlong.h"
#else /* not USE_LONGLONG_H */
# define __ll_B ((uintmax_t) 1 << (W_TYPE_SIZE / 2))
# define __ll_lowpart(t) ((uintmax_t) (t) & (__ll_B - 1))
# define __ll_highpart(t) ((uintmax_t) (t) >> (W_TYPE_SIZE / 2))
#endif
/* 2*3*5*7*11...*101 is 128 bits, and has 26 prime factors */
#define MAX_NFACTS 26
enum
{
DEV_DEBUG_OPTION = CHAR_MAX + 1
};
static struct option const long_options[] =
{
{"exponents", no_argument, nullptr, 'h'},
{"-debug", no_argument, nullptr, DEV_DEBUG_OPTION},
{GETOPT_HELP_OPTION_DECL},
{GETOPT_VERSION_OPTION_DECL},
{nullptr, 0, nullptr, 0}
};
/* If true, use p^e output format. */
static bool print_exponents;
/* This represents an unsigned integer twice as wide as uintmax_t. */
typedef struct { uintmax_t uu[2]; } uuint;
/* Accessors and constructors for the type. Pprograms should not
access the type's internals directly, in case some future version
replaces the type with unsigned __int128 or whatever. */
static uintmax_t lo (uuint u) { return u.uu[0]; }
static uintmax_t hi (uuint u) { return u.uu[1]; }
static void hiset (uuint *u, uintmax_t hi) { u->uu[1] = hi; }
static void
uuset (uintmax_t *phi, uintmax_t *plo, uuint uu)
{
*phi = hi (uu);
*plo = lo (uu);
}
static uuint
make_uuint (uintmax_t hi, uintmax_t lo)
{
return (uuint) {{lo, hi}};
}
/* BIG_POWER_OF_10 is a positive power of 10 that does not exceed UINTMAX_MAX.
The larger it is, the more efficient the code will likely be.
LOG_BIG_POWER_OF_10 = log (BIG_POWER_OF_10). */
#if UINTMAX_WIDTH < 64
# error "platform does not support 64-bit integers"
#elif UINTMAX_WIDTH < 128 || !defined UINTMAX_C
/* Mainstream platforms as of 2024, with at-least-64-bit uintmax_t. */
static uintmax_t const BIG_POWER_OF_10 = 10000000000000000000llu;
enum { LOG_BIG_POWER_OF_10 = 19 };
#else
/* For so-far-only-theoretical platforms with at-least-128-bit uintmax_t.
This is for performance; the 64-bit mainstream code will still work. */
static uintmax_t const BIG_POWER_OF_10 =
UINTMAX_C (100000000000000000000000000000000000000);
enum { LOG_BIG_POWER_OF_10 = 38 };
#endif
struct factors
{
uuint plarge; /* Can have a single large factor */
uintmax_t p[MAX_NFACTS];
unsigned char e[MAX_NFACTS];
unsigned char nfactors;
};
struct mp_factors
{
mpz_t *p;
unsigned long int *e;
idx_t nfactors;
idx_t nalloc;
};
static void factor (uintmax_t, uintmax_t, struct factors *);
#ifndef umul_ppmm
# define umul_ppmm(w1, w0, u, v) \
do { \
uintmax_t __x0, __x1, __x2, __x3; \
unsigned long int __ul, __vl, __uh, __vh; \
uintmax_t __u = (u), __v = (v); \
\
__ul = __ll_lowpart (__u); \
__uh = __ll_highpart (__u); \
__vl = __ll_lowpart (__v); \
__vh = __ll_highpart (__v); \
\
__x0 = (uintmax_t) __ul * __vl; \
__x1 = (uintmax_t) __ul * __vh; \
__x2 = (uintmax_t) __uh * __vl; \
__x3 = (uintmax_t) __uh * __vh; \
\
__x1 += __ll_highpart (__x0);/* This can't give carry. */ \
__x1 += __x2; /* But this indeed can. */ \
if (__x1 < __x2) /* Did we get it? */ \
__x3 += __ll_B; /* Yes, add it in the proper pos. */ \
\
(w1) = __x3 + __ll_highpart (__x1); \
(w0) = (__x1 << W_TYPE_SIZE / 2) + __ll_lowpart (__x0); \
} while (0)
#endif
#if !defined udiv_qrnnd || defined UDIV_NEEDS_NORMALIZATION
/* Define our own, not needing normalization. This function is
currently not performance critical, so keep it simple. Similar to
the mod macro below. */
# undef udiv_qrnnd
# define udiv_qrnnd(q, r, n1, n0, d) \
do { \
uintmax_t __d1, __d0, __q, __r1, __r0; \
\
__d1 = (d); __d0 = 0; \
__r1 = (n1); __r0 = (n0); \
affirm (__r1 < __d1); \
__q = 0; \
for (int __i = W_TYPE_SIZE; __i > 0; __i--) \
{ \
rsh2 (__d1, __d0, __d1, __d0, 1); \
__q <<= 1; \
if (ge2 (__r1, __r0, __d1, __d0)) \
{ \
__q++; \
sub_ddmmss (__r1, __r0, __r1, __r0, __d1, __d0); \
} \
} \
(r) = __r0; \
(q) = __q; \
} while (0)
#endif
#if !defined add_ssaaaa
# define add_ssaaaa(sh, sl, ah, al, bh, bl) \
do { \
uintmax_t _add_x; \
_add_x = (al) + (bl); \
(sh) = (ah) + (bh) + (_add_x < (al)); \
(sl) = _add_x; \
} while (0)
#endif
/* Set (rh,rl) = (ah,al) >> cnt, where 0 < cnt < W_TYPE_SIZE. */
#define rsh2(rh, rl, ah, al, cnt) \
do { \
(rl) = ((ah) << (W_TYPE_SIZE - (cnt))) | ((al) >> (cnt)); \
(rh) = (ah) >> (cnt); \
} while (0)
/* Set (rh,rl) = (ah,al) << cnt, where 0 < cnt < W_TYPE_SIZE. */
#define lsh2(rh, rl, ah, al, cnt) \
do { \
(rh) = ((ah) << cnt) | ((al) >> (W_TYPE_SIZE - (cnt))); \
(rl) = (al) << (cnt); \
} while (0)
#define ge2(ah, al, bh, bl) \
((ah) > (bh) || ((ah) == (bh) && (al) >= (bl)))
#define gt2(ah, al, bh, bl) \
((ah) > (bh) || ((ah) == (bh) && (al) > (bl)))
#ifndef sub_ddmmss
# define sub_ddmmss(rh, rl, ah, al, bh, bl) \
do { \
uintmax_t _cy; \
_cy = (al) < (bl); \
(rl) = (al) - (bl); \
(rh) = (ah) - (bh) - _cy; \
} while (0)
#endif
/* Requires that a < n and b <= n */
#define submod(r,a,b,n) \
do { \
uintmax_t _t = - (uintmax_t) (a < b); \
(r) = ((n) & _t) + (a) - (b); \
} while (0)
#define addmod(r,a,b,n) \
submod ((r), (a), ((n) - (b)), (n))
/* Modular two-word addition and subtraction. For performance reasons, the
most significant bit of n1 must be clear. The destination variables must be
distinct from the mod operand. */
#define addmod2(r1, r0, a1, a0, b1, b0, n1, n0) \
do { \
add_ssaaaa ((r1), (r0), (a1), (a0), (b1), (b0)); \
if (ge2 ((r1), (r0), (n1), (n0))) \
sub_ddmmss ((r1), (r0), (r1), (r0), (n1), (n0)); \
} while (0)
#define submod2(r1, r0, a1, a0, b1, b0, n1, n0) \
do { \
sub_ddmmss ((r1), (r0), (a1), (a0), (b1), (b0)); \
if ((intmax_t) (r1) < 0) \
add_ssaaaa ((r1), (r0), (r1), (r0), (n1), (n0)); \
} while (0)
#define HIGHBIT_TO_MASK(x) \
(((intmax_t)-1 >> 1) < 0 \
? (uintmax_t)((intmax_t)(x) >> (W_TYPE_SIZE - 1)) \
: ((x) & ((uintmax_t) 1 << (W_TYPE_SIZE - 1)) \
? UINTMAX_MAX : (uintmax_t) 0))
/* Return r = a mod d, where a = <a1,a0>, d = <d1,d0>.
Requires that d1 != 0. */
ATTRIBUTE_PURE static uuint
mod2 (uintmax_t a1, uintmax_t a0, uintmax_t d1, uintmax_t d0)
{
affirm (d1 != 0);
if (a1)
{
int cntd = stdc_leading_zeros (d1);
int cnta = stdc_leading_zeros (a1);
int cnt = cntd - cnta;
if (0 < cnt)
{
lsh2 (d1, d0, d1, d0, cnt);
for (int i = 0; i < cnt; i++)
{
if (ge2 (a1, a0, d1, d0))
sub_ddmmss (a1, a0, a1, a0, d1, d0);
rsh2 (d1, d0, d1, d0, 1);
}
}
}
return make_uuint (a1, a0);
}
ATTRIBUTE_CONST
static uintmax_t
gcd_odd (uintmax_t a, uintmax_t b)
{
if ((b & 1) == 0)
{
uintmax_t t = b;
b = a;
a = t;
}
if (a == 0)
return b;
/* Take out least significant one bit, to make room for sign */
b >>= 1;
for (;;)
{
uintmax_t t;
uintmax_t bgta;
assume (a);
a >>= stdc_trailing_zeros (a);
a >>= 1;
t = a - b;
if (t == 0)
return (a << 1) + 1;
bgta = HIGHBIT_TO_MASK (t);
/* b <-- min (a, b) */
b += (bgta & t);
/* a <-- |a - b| */
a = (t ^ bgta) - bgta;
}
}
ATTRIBUTE_PURE static uuint
gcd2_odd (uintmax_t a1, uintmax_t a0, uintmax_t b1, uintmax_t b0)
{
affirm (b0 & 1);
if ((a0 | a1) == 0)
return make_uuint (b1, b0);
if (!a0)
a0 = a1, a1 = 0;
assume (a0);
int ctz = stdc_trailing_zeros (a0);
if (ctz)
rsh2 (a1, a0, a1, a0, ctz);
for (;;)
{
if ((b1 | a1) == 0)
return make_uuint (0, gcd_odd (b0, a0));
if (gt2 (a1, a0, b1, b0))
{
sub_ddmmss (a1, a0, a1, a0, b1, b0);
if (!a0)
a0 = a1, a1 = 0;
assume (a0);
ctz = stdc_trailing_zeros (a0);
if (ctz)
rsh2 (a1, a0, a1, a0, ctz);
}
else if (gt2 (b1, b0, a1, a0))
{
sub_ddmmss (b1, b0, b1, b0, a1, a0);
if (!b0)
b0 = b1, b1 = 0;
assume (b0);
ctz = stdc_trailing_zeros (b0);
if (ctz)
rsh2 (b1, b0, b1, b0, ctz);
}
else
break;
}
return make_uuint (a1, a0);
}
static void
factor_insert_multiplicity (struct factors *factors,
uintmax_t prime, int m)
{
int nfactors = factors->nfactors;
uintmax_t *p = factors->p;
unsigned char *e = factors->e;
/* Locate position for insert new or increment e. */
int i;
for (i = nfactors - 1; i >= 0; i--)
{
if (p[i] <= prime)
break;
}
if (i < 0 || p[i] != prime)
{
for (int j = nfactors - 1; j > i; j--)
{
p[j + 1] = p[j];
e[j + 1] = e[j];
}
p[i + 1] = prime;
e[i + 1] = m;
factors->nfactors = nfactors + 1;
}
else
{
e[i] += m;
}
}
#define factor_insert(f, p) factor_insert_multiplicity (f, p, 1)
static void
factor_insert_large (struct factors *factors,
uintmax_t p1, uintmax_t p0)
{
if (p1 > 0)
{
affirm (hi (factors->plarge) == 0);
factors->plarge = make_uuint (p1, p0);
}
else
factor_insert (factors, p0);
}
#ifndef mpz_inits
# include <stdarg.h>
# define mpz_inits(...) mpz_va_init (mpz_init, __VA_ARGS__)
# define mpz_clears(...) mpz_va_init (mpz_clear, __VA_ARGS__)
static void
mpz_va_init (void (*mpz_single_init)(mpz_t), ...)
{
va_list ap;
va_start (ap, mpz_single_init);
mpz_t *mpz;
while ((mpz = va_arg (ap, mpz_t *)))
mpz_single_init (*mpz);
va_end (ap);
}
#endif
static void mp_factor (mpz_t, struct mp_factors *);
static void
mp_factor_init (struct mp_factors *factors)
{
factors->p = nullptr;
factors->e = nullptr;
factors->nfactors = 0;
factors->nalloc = 0;
}
static void
mp_factor_clear (struct mp_factors *factors)
{
for (idx_t i = 0; i < factors->nfactors; i++)
mpz_clear (factors->p[i]);
free (factors->p);
free (factors->e);
}
static void
mp_factor_insert (struct mp_factors *factors, mpz_t prime)
{
idx_t nfactors = factors->nfactors;
mpz_t *p = factors->p;
unsigned long int *e = factors->e;
ptrdiff_t i;
/* Locate position for insert new or increment e. */
for (i = nfactors - 1; i >= 0; i--)
{
if (mpz_cmp (p[i], prime) <= 0)
break;
}
if (i < 0 || mpz_cmp (p[i], prime) != 0)
{
if (factors->nfactors == factors->nalloc)
{
p = xpalloc (p, &factors->nalloc, 1, -1, sizeof *p);
e = xireallocarray (e, factors->nalloc, sizeof *e);
}
mpz_init (p[nfactors]);
for (ptrdiff_t j = nfactors - 1; j > i; j--)
{
mpz_set (p[j + 1], p[j]);
e[j + 1] = e[j];
}
mpz_set (p[i + 1], prime);
e[i + 1] = 1;
factors->p = p;
factors->e = e;
factors->nfactors = nfactors + 1;
}
else
{
e[i] += 1;
}
}
static void
mp_factor_insert_ui (struct mp_factors *factors, unsigned long int prime)
{
mpz_t pz;
mpz_init_set_ui (pz, prime);
mp_factor_insert (factors, pz);
mpz_clear (pz);
}
#define P(a,b,c,d) a,
static const unsigned char primes_diff[] = {
#include "primes.h"
0,0,0,0,0,0,0 /* 7 sentinels for 8-way loop */
};
#undef P
#define PRIMES_PTAB_ENTRIES (ARRAY_CARDINALITY (primes_diff) - 8 + 1)
#define P(a,b,c,d) b,
static const unsigned char primes_diff8[] = {
#include "primes.h"
0,0,0,0,0,0,0 /* 7 sentinels for 8-way loop */
};
#undef P
struct primes_dtab
{
uintmax_t binv, lim;
};
#define P(a,b,c,d) {c,d},
static const struct primes_dtab primes_dtab[] = {
#include "primes.h"
{1,0},{1,0},{1,0},{1,0},{1,0},{1,0},{1,0} /* 7 sentinels for 8-way loop */
};
#undef P
/* Verify that uintmax_t is not wider than
the integers used to generate primes.h. */
static_assert (UINTMAX_WIDTH <= WIDE_UINT_BITS);
/* debugging for developers. Enables devmsg().
This flag is used only in the GMP code. */
static bool dev_debug = false;
/* Prove primality or run probabilistic tests. */
static bool flag_prove_primality = PROVE_PRIMALITY;
/* Number of Miller-Rabin tests to run when not proving primality. */
#define MR_REPS 25
static void
factor_insert_refind (struct factors *factors, uintmax_t p, int i, int off)
{
for (int j = 0; j < off; j++)
p += primes_diff[i + j];
factor_insert (factors, p);
}
/* Trial division with odd primes uses the following trick.
Let p be an odd prime, and B = 2^{W_TYPE_SIZE}. For simplicity,
consider the case t < B (this is the second loop below).
From our tables we get
binv = p^{-1} (mod B)
lim = floor ((B-1) / p).
First assume that t is a multiple of p, t = q * p. Then 0 <= q <= lim
(and all quotients in this range occur for some t).
Then t = q * p is true also (mod B), and p is invertible we get
q = t * binv (mod B).
Next, assume that t is *not* divisible by p. Since multiplication
by binv (mod B) is a one-to-one mapping,
t * binv (mod B) > lim,
because all the smaller values are already taken.
This can be summed up by saying that the function
q(t) = binv * t (mod B)
is a permutation of the range 0 <= t < B, with the curious property
that it maps the multiples of p onto the range 0 <= q <= lim, in
order, and the non-multiples of p onto the range lim < q < B.
*/
static uuint
factor_using_division (uintmax_t t1, uintmax_t t0,
struct factors *factors)
{
if (t0 % 2 == 0)
{
int cnt;
if (t0 == 0)
{
assume (t1);
cnt = stdc_trailing_zeros (t1);
t0 = t1 >> cnt;
t1 = 0;
cnt += W_TYPE_SIZE;
}
else
{
cnt = stdc_trailing_zeros (t0);
rsh2 (t1, t0, t1, t0, cnt);
}
factor_insert_multiplicity (factors, 2, cnt);
}
uintmax_t p = 3;
idx_t i;
for (i = 0; t1 > 0 && i < PRIMES_PTAB_ENTRIES; i++)
{
for (;;)
{
uintmax_t q1, q0, hi;
MAYBE_UNUSED uintmax_t lo;
q0 = t0 * primes_dtab[i].binv;
umul_ppmm (hi, lo, q0, p);
if (hi > t1)
break;
hi = t1 - hi;
q1 = hi * primes_dtab[i].binv;
if (LIKELY (q1 > primes_dtab[i].lim))
break;
t1 = q1; t0 = q0;
factor_insert (factors, p);
}
p += primes_diff[i + 1];
}
#define DIVBLOCK(I) \
do { \
for (;;) \
{ \
q = t0 * pd[I].binv; \
if (LIKELY (q > pd[I].lim)) \
break; \
t0 = q; \
factor_insert_refind (factors, p, i + 1, I); \
} \
} while (0)
for (; i < PRIMES_PTAB_ENTRIES; i += 8)
{
uintmax_t q;
const struct primes_dtab *pd = &primes_dtab[i];
DIVBLOCK (0);
DIVBLOCK (1);
DIVBLOCK (2);
DIVBLOCK (3);
DIVBLOCK (4);
DIVBLOCK (5);
DIVBLOCK (6);
DIVBLOCK (7);
p += primes_diff8[i];
if (p * p > t0)
break;
}
return make_uuint (t1, t0);
}
static void
mp_factor_using_division (mpz_t t, struct mp_factors *factors)
{
mpz_t q;
mp_bitcnt_t p;
devmsg ("[trial division] ");
mpz_init (q);
p = mpz_scan1 (t, 0);
mpz_fdiv_q_2exp (t, t, p);
while (p)
{
mp_factor_insert_ui (factors, 2);
--p;
}
unsigned long int d = 3;
for (idx_t i = 1; i <= PRIMES_PTAB_ENTRIES;)
{
if (! mpz_divisible_ui_p (t, d))
{
d += primes_diff[i++];
if (mpz_cmp_ui (t, d * d) < 0)
break;
}
else
{
mpz_tdiv_q_ui (t, t, d);
mp_factor_insert_ui (factors, d);
}
}
mpz_clear (q);
}
/* Entry i contains (2i+1)^(-1) mod 2^8. */
static const unsigned char binvert_table[128] =
{
0x01, 0xAB, 0xCD, 0xB7, 0x39, 0xA3, 0xC5, 0xEF,
0xF1, 0x1B, 0x3D, 0xA7, 0x29, 0x13, 0x35, 0xDF,
0xE1, 0x8B, 0xAD, 0x97, 0x19, 0x83, 0xA5, 0xCF,
0xD1, 0xFB, 0x1D, 0x87, 0x09, 0xF3, 0x15, 0xBF,
0xC1, 0x6B, 0x8D, 0x77, 0xF9, 0x63, 0x85, 0xAF,
0xB1, 0xDB, 0xFD, 0x67, 0xE9, 0xD3, 0xF5, 0x9F,
0xA1, 0x4B, 0x6D, 0x57, 0xD9, 0x43, 0x65, 0x8F,
0x91, 0xBB, 0xDD, 0x47, 0xC9, 0xB3, 0xD5, 0x7F,
0x81, 0x2B, 0x4D, 0x37, 0xB9, 0x23, 0x45, 0x6F,
0x71, 0x9B, 0xBD, 0x27, 0xA9, 0x93, 0xB5, 0x5F,
0x61, 0x0B, 0x2D, 0x17, 0x99, 0x03, 0x25, 0x4F,
0x51, 0x7B, 0x9D, 0x07, 0x89, 0x73, 0x95, 0x3F,
0x41, 0xEB, 0x0D, 0xF7, 0x79, 0xE3, 0x05, 0x2F,
0x31, 0x5B, 0x7D, 0xE7, 0x69, 0x53, 0x75, 0x1F,
0x21, 0xCB, 0xED, 0xD7, 0x59, 0xC3, 0xE5, 0x0F,
0x11, 0x3B, 0x5D, 0xC7, 0x49, 0x33, 0x55, 0xFF
};
/* Compute n^(-1) mod B, using a Newton iteration. */
#define binv(inv,n) \
do { \
uintmax_t __n = (n); \
uintmax_t __inv; \
\
__inv = binvert_table[(__n / 2) & 0x7F]; /* 8 */ \
if (W_TYPE_SIZE > 8) __inv = 2 * __inv - __inv * __inv * __n; \
if (W_TYPE_SIZE > 16) __inv = 2 * __inv - __inv * __inv * __n; \
if (W_TYPE_SIZE > 32) __inv = 2 * __inv - __inv * __inv * __n; \
\
if (W_TYPE_SIZE > 64) \
{ \
int __invbits = 64; \
do { \
__inv = 2 * __inv - __inv * __inv * __n; \
__invbits *= 2; \
} while (__invbits < W_TYPE_SIZE); \
} \
\
(inv) = __inv; \
} while (0)
/* q = u / d, assuming d|u. */
#define divexact_21(q1, q0, u1, u0, d) \
do { \
uintmax_t _di, _q0; \
binv (_di, (d)); \
_q0 = (u0) * _di; \
if ((u1) >= (d)) \
{ \
uintmax_t _p1; \
MAYBE_UNUSED intmax_t _p0; \
umul_ppmm (_p1, _p0, _q0, d); \
(q1) = ((u1) - _p1) * _di; \
(q0) = _q0; \
} \
else \
{ \
(q0) = _q0; \
(q1) = 0; \
} \
} while (0)
/* x B (mod n). */
#define redcify(r_prim, r, n) \
do { \
MAYBE_UNUSED uintmax_t _redcify_q; \
udiv_qrnnd (_redcify_q, r_prim, r, 0, n); \
} while (0)
/* x B^2 (mod n). Requires x > 0, n1 < B/2. */
#define redcify2(r1, r0, x, n1, n0) \
do { \
uintmax_t _r1, _r0, _i; \
if ((x) < (n1)) \
{ \
_r1 = (x); _r0 = 0; \
_i = W_TYPE_SIZE; \
} \
else \
{ \
_r1 = 0; _r0 = (x); \
_i = 2 * W_TYPE_SIZE; \
} \
while (_i-- > 0) \
{ \
lsh2 (_r1, _r0, _r1, _r0, 1); \
if (ge2 (_r1, _r0, (n1), (n0))) \
sub_ddmmss (_r1, _r0, _r1, _r0, (n1), (n0)); \
} \
(r1) = _r1; \
(r0) = _r0; \
} while (0)
/* Modular two-word multiplication, r = a * b mod m, with mi = m^(-1) mod B.
Both a and b must be in redc form, the result will be in redc form too. */
static inline uintmax_t
mulredc (uintmax_t a, uintmax_t b, uintmax_t m, uintmax_t mi)
{
uintmax_t rh, rl, q, th, xh;
MAYBE_UNUSED uintmax_t tl;
umul_ppmm (rh, rl, a, b);
q = rl * mi;
umul_ppmm (th, tl, q, m);
xh = rh - th;
if (rh < th)
xh += m;
return xh;
}
/* Modular two-word multiplication, r = a * b mod m, with mi = m^(-1) mod B.
Both a and b must be in redc form, the result will be in redc form too.
For performance reasons, the most significant bit of m must be clear. */
static uintmax_t
mulredc2 (uintmax_t *r1p,
uintmax_t a1, uintmax_t a0, uintmax_t b1, uintmax_t b0,
uintmax_t m1, uintmax_t m0, uintmax_t mi)
{
uintmax_t r1, r0, q, p1, t1, t0, s1, s0;
MAYBE_UNUSED uintmax_t p0;
mi = -mi;
affirm ((a1 >> (W_TYPE_SIZE - 1)) == 0);
affirm ((b1 >> (W_TYPE_SIZE - 1)) == 0);
affirm ((m1 >> (W_TYPE_SIZE - 1)) == 0);
/* First compute a0 * <b1, b0> B^{-1}
+-----+
|a0 b0|
+--+--+--+
|a0 b1|
+--+--+--+
|q0 m0|
+--+--+--+
|q0 m1|
-+--+--+--+
|r1|r0| 0|
+--+--+--+
*/
umul_ppmm (t1, t0, a0, b0);
umul_ppmm (r1, r0, a0, b1);
q = mi * t0;
umul_ppmm (p1, p0, q, m0);
umul_ppmm (s1, s0, q, m1);
r0 += (t0 != 0); /* Carry */