forked from hvds/divrep
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcoul.c
More file actions
3731 lines (3500 loc) · 114 KB
/
coul.c
File metadata and controls
3731 lines (3500 loc) · 114 KB
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
/* needed on FreeBSD for getline() to be exported from stdio.h */
#define _WITH_GETLINE
#define ANSI_COLOR_RED "\x1b[31m"
#define ANSI_COLOR_RESET "\x1b[0m"
#define ANSI_COLOR_GREEN "\x1b[32m"
#define ANSI_COLOR_YELLOW "\x1b[33m"
#define ANSI_COLOR_BLUE "\x1b[34m"
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <stdarg.h>
#include <string.h>
#include <errno.h>
#include <assert.h>
#ifdef HAVE_SETPROCTITLE
# include <sys/types.h>
#endif
#include <signal.h>
#ifdef __CYGWIN__
/* noop */
#else
#include <time.h>
#endif
#include <sys/time.h>
#include <sys/resource.h>
#include "coul.h"
#include "coulfact.h"
#include "diag.h"
#include "rootmod.h"
#include "coultau.h"
#include "pell.h"
/* from MPUG */
#include "factor.h"
#include "gmp_main.h"
#include "utility.h"
#include "primality.h"
/* primary parameters - we are searching for D(n, k), the least d such
* that tau(d + i) = n for all 0 <= i < k.
*/
uint n, k;
/* mpz_t passed as function parameter decays to pointer in a way that
* allows it to be used as mpz_t, but cannot be converted to a pointer
* in a typesafe manner. Given a function called as foo(z), use this as
* mpz_t *zp = PARAM_TO_PTR(z);
*/
static inline mpz_t *PARAM_TO_PTR(__mpz_struct *z) {
return (mpz_t *)z;
}
/* stash of mpz_t, initialized once at start */
typedef enum {
zero, zone, /* constants */
temp,
sqm_t, sqm_q, sqm_b, sqm_z, sqm_x, /* sqrtmod_t */
uc_minusvi, uc_px, /* update_chinese */
ur_a, ur_m, ur_ipg, /* update_residues */
asq_o, asq_qq, asq_m, /* alloc_square */
wv_ati, wv_end, wv_cand, /* walk_v */
wv_startr, wv_endr, wv_qqr, wv_r, wv_rx, wv_temp,
wv_x, wv_y, wv_x2, wv_y2,
w1_v, w1_j, w1_r, /* walk_1 */
lp_x, lp_mint, /* limit_p */
r_walk, /* recurse */
sdm_p, sdm_r, /* small_divmod (TODO) */
dm_r, /* divmod */
np_p, /* next_prime */
s_exp, uls_temp, /* ston, ulston */
MAX_ZSTASH
} t_zstash;
mpz_t *zstash;
static inline mpz_t *ZP(t_zstash e) { return &zstash[e]; }
#define Z(e) *ZP(e)
/* additional arrays of mpz_t initialized once at start */
mpz_t *wv_o = NULL, *wv_qq = NULL; /* wv_o[k], wv_qq[k] */
/* used to store disallowed inverses in walk_v() */
typedef struct s_mod {
ulong v;
ulong m;
} t_mod;
t_divisors *divisors = NULL;
/* For prime p < k, we "force" allocation of powers in a batch to ensure
* that multiple allocations of the same prime are coherent. Whereas normal
* allocation considers only p^{x-1} where x is divisible by the highest
* prime dividing t_i, forced primes may allocate any p^{x-1} with x | t_i.
*
* For cases where two or more v_i are divisible by p, we always force
* every possible case. For cases where only one v_i is divisible by p,
* we force them only if n == 2 (mod 4) (heuristically, since allocations
* are always either at least as powerful as normal allocations _or_ they
* have x=2, leaving v_i.t odd) or if requested by the -f option (force_all).
*
* Each batch describes the location and magnitude of the highest power of p
* that divides any v_i (using the lower i if there are more than one).
*/
typedef struct s_forcebatch {
uint vi; /* allocate p^{x-1} at v_{vi} */
uint x;
} t_forcebatch;
typedef struct s_forcep {
uint p;
uint count;
t_forcebatch *batch;
} t_forcep;
t_forcep *forcep = NULL;
uint forcedp;
uint force_all = 0;
uint unforce_all = 0;
/* When allocation forces the residue of some v_i to be square, we want
* to calculate the roots mod every allocation (before and after this one),
* first to check if a solution is possible, and second to avoid duplicate
* work when we actually use the roots in walk_v().
* The set of roots lives in resarray(level), but here we track what power
* root they are: the allocation at value[sq0].alloc[i] leaves gcddm sqg[i].
*/
uint sq0 = 0;
uint *sqg = NULL; /* size maxfact */
t_level *levels = NULL; /* one level per allocated prime */
uint level = 0; /* current recursion level */
uint final_level = 0; /* level at which to terminate */
t_value *value = NULL; /* v_0 .. v_{k-1} */
static inline void level_setp(t_level *lp, ulong p) {
lp->p = p;
prime_iterator_setprime(&lp->piter, p);
}
/* reset allocations at this level to those at previous level */
static inline void reset_vlevel(t_level *cur_level) {
assert(cur_level->level > 0);
t_level *prev_level = &levels[cur_level->level - 1];
memcpy(cur_level->vlevel, prev_level->vlevel, k * sizeof(uint));
}
/* list of some small primes, at least enough for one per allocation */
uint *sprimes = NULL;
uint nsprimes;
/* set to utime at start of run, minus last timestamp of recovery file */
double t0 = 0;
struct rusage rusage_buf;
static inline double utime(void) {
#ifdef __CYGWIN__
return clock() / 1000;
#else
getrusage(RUSAGE_SELF, &rusage_buf);
return (double)rusage_buf.ru_utime.tv_sec + (double)rusage_buf.ru_utime.tv_usec / 1000000;
#endif
}
timer_t diag_timerid, log_timerid;
volatile bool need_work, need_diag, need_log;
bool clock_is_realtime = 0;
mpz_t min, max; /* limits to check for v_0 */
mpz_t best; /* best solution seen */
bool improve_max = 1; /* reduce max when solution found */
uint seen_best = 0; /* number of times we've improved max */
ulong gain = 0; /* used to fine-tune balance of recursion vs. walk */
ulong antigain = 0;
/* maxp[e] is the greatest prime we should attempt to allocate as power p^e;
* minp[e] is the threshold that at least one allocated p^e should exceed
* (else we can skip the walk); midp[e] is the additional threshold up to
* which we should pre-walk.
* sminp, smaxp, smidp are the strings that express the requests.
*/
ulong *minp = NULL, *maxp = NULL, *midp = NULL;
char *sminp = NULL, *smaxp = NULL, *smidp = NULL;
char *sminpx = NULL, *smaxpx = NULL, *smidpx = NULL;
bool midp_only = 0, in_midp = 0, need_maxp = 0, need_midp = 0;
/* where to walk for -W (midp) */
typedef struct s_midpp {
uint vi;
uint x;
ulong maxp;
ulong minp;
} t_midpp;
uint midppc;
t_midpp *midpp = NULL;
struct {
uint valid;
ulong p;
uint x;
uint vi;
} midp_recover;
uint rough = 0; /* test roughness if tau >= rough */
bool opt_print = 0; /* print candidates instead of fully testing them */
/* If opt_alloc is true and opt_batch < 0, just show the forced-prime
* allocation; if opt_alloc is true and opt_batch >= 0, just process
* the specified batch_alloc.
*/
bool opt_alloc = 0;
int opt_batch_min = -1, opt_batch_max;
int batch_alloc = 0; /* index of forced-prime allocations */
int last_batch_seen = -1;
uint cur_batch_level = 0; /* for disp_batch */
uint strategy; /* best_v() strategy */
uint strategy_set = 0; /* strategy was user-selected */
bool debugw = 0; /* diag and keep every case seen (excluding walk) */
bool debugW = 0; /* diag and keep every case seen (including walk) */
bool debugx = 0; /* show p^x constraints */
bool debugb = 0; /* show batch id, if changed */
bool debugB = 0; /* show every batch id */
ulong randseed = 1; /* for ECM, etc */
bool vt100 = 0; /* update window title with VT100 escape sequences */
char *rpath = NULL; /* path to log file */
FILE *rfp = NULL; /* file handle to log file */
bool start_seen = 0; /* true if log file has been written to before */
bool skip_recover = 0; /* true if we should not attempt recovery */
t_fact *rstack = NULL; /* point reached in recovery log file */
bool have_rwalk = 0; /* true if recovery is mid-walk */
mpz_t rwalk_from;
mpz_t rwalk_to;
t_fact nf; /* factors of n */
uint tn; /* tau(n) */
uint maxfact; /* count of prime factors dividing n, with multiplicity */
uint maxodd; /* as above for odd prime factors */
uint *maxforce = NULL; /* max prime to force at v_i */
mpz_t px; /* p^x */
#define DIAG 1
#define LOG 600
double diag_delay = DIAG, log_delay = LOG, diagt, logt;
ulong countr, countw, countwi;
#define MAX_DEC_ULONG 20
#define MAX_DEC_POWER 5
#define DIAG_BUFSIZE (6 + MAX_DEC_ULONG + k * maxfact * (MAX_DEC_ULONG + 1 + MAX_DEC_POWER + 1) + 1)
char *diag_buf = NULL;
uint aux_buf_size = 0;
char *aux_buf = NULL;
/* Initial pattern set with -I */
char *init_pattern = NULL;
/* Mod constraints set with -m */
typedef struct s_modfix {
mpz_t mod;
mpz_t val;
} t_modfix;
t_modfix *modfix = NULL;
uint modfix_count = 0;
#if defined(TYPE_o)
static inline uint TYPE_OFFSET(uint i) {
return i;
}
#elif defined(TYPE_a)
static inline uint TYPE_OFFSET(uint i) {
return i * n;
}
#else
# error "No type defined"
#endif
void update_window(t_level *cur_level) {
if (vt100) {
/* update window title and icon with <ESC> ] 0 ; "string" <BEL> */
uint this_batch = (opt_batch_min < 0) ? batch_alloc : batch_alloc - 1;
printf("\x1b]0;b%d:", this_batch);
uint pc = 0;
for (uint i = 1; i <= cur_level->level && pc < 3; ++i) {
if (levels[i].is_forced)
continue;
printf(" %lu", levels[i].p);
++pc;
}
printf("\a");
}
fflush(stdout);
}
void prep_show_v(t_level *cur_level) {
uint offset = 0;
uint mid_vi;
if (in_midp)
mid_vi = cur_level->vi;
offset += sprintf(&diag_buf[offset], "b%u: ", batch_alloc - 1);
for (uint vi = 0; vi < k; ++vi) {
uint vlevel = cur_level->vlevel[vi]
- ((in_midp && vi == mid_vi) ? 1 : 0);
if (vi)
diag_buf[offset++] = ' ';
if (vlevel == 0)
diag_buf[offset++] = '.';
else {
t_value *vp = &value[vi];
for (uint ai = 0; ai < vlevel; ++ai) {
t_allocation *ap = &vp->alloc[ai];
if (ai)
diag_buf[offset++] = '.';
offset += sprintf(&diag_buf[offset], "%lu", ap->p);
if (ap->x > 2)
offset += sprintf(&diag_buf[offset], "^%u", ap->x - 1);
}
}
}
if (in_midp) {
ulong p = cur_level->p;
uint x = cur_level->x;
offset += sprintf(&diag_buf[offset], " W(%lu,%u,%u)", p, x, mid_vi);
}
diag_buf[offset] = 0;
}
void report(char *format, ...) {
keep_diag();
va_list ap;
va_start(ap, format);
gmp_vfprintf(stdout, format, ap);
va_end(ap);
if (rfp) {
va_start(ap, format);
gmp_vfprintf(rfp, format, ap);
va_end(ap);
fflush(rfp);
t0 = utime();
}
}
double seconds(double t1) {
return (t1 - t0);
}
/* gmp_sprintf into aux_buf, resizing as needed */
void aux_sprintf(char *fmt, ...) {
va_list ap;
va_start(ap, fmt);
uint size = gmp_vsnprintf(aux_buf, aux_buf_size, fmt, ap);
va_end(ap);
if (size >= aux_buf_size) {
size += 32;
aux_buf = realloc(aux_buf, size);
aux_buf_size = size;
va_start(ap, fmt);
gmp_vsprintf(aux_buf, fmt, ap);
va_end(ap);
}
}
void disp_batch(void) {
assert(level >= cur_batch_level);
t_level *lp = &levels[cur_batch_level];
prep_show_v(lp); /* into diag_buf */
if (lp->have_square) {
uint l = strlen(diag_buf);
sprintf(&diag_buf[l], " [sq=%u]", lp->have_square);
}
report("203 %s\n", diag_buf);
}
void diag_any(t_level *cur_level, bool need_disp) {
double t1 = utime();
update_window(cur_level);
if ((debugb && !debugB)
&& batch_alloc != last_batch_seen
&& ((need_diag && need_disp) || (rfp && need_log))
) {
last_batch_seen = batch_alloc;
disp_batch();
}
prep_show_v(cur_level); /* into diag_buf */
if (need_diag) {
if (need_disp)
diag("%s%s", diag_buf, aux_buf);
if (debugw)
keep_diag();
else
need_diag = 0;
}
if (rfp && need_log) {
fprintf(rfp, "305 %s%s (%.2fs)\n", diag_buf, aux_buf, seconds(t1));
logt = t1 + log_delay;
need_log = 0;
}
if (!debugw)
need_work = 0;
}
void diag_plain(t_level *cur_level) {
aux_sprintf("");
diag_any(cur_level, 1);
}
void diag_walk_v(t_level *cur_level, ulong ati, ulong end) {
aux_sprintf(": %lu / %lu", ati, end);
diag_any(cur_level, !(debugw && !debugW && ati));
}
void diag_walk_zv(t_level *cur_level, mpz_t ati, mpz_t end) {
aux_sprintf(": %Zu / %Zu", ati, end);
diag_any(cur_level, !(debugw && !debugW && mpz_sgn(ati)));
}
void diag_walk_pell(t_level *cur_level, uint pc) {
aux_sprintf(": P%u", pc);
diag_any(cur_level, !(debugw && pc));
}
void candidate(mpz_t c) {
keep_diag();
double t1 = utime();
report("202 Candidate %Zu (%.2fs)\n", c, seconds(t1));
if (!seen_best || mpz_cmp(c, best) <= 0) {
mpz_set(best, c);
++seen_best;
}
if (improve_max && mpz_cmp(c, max) <= 0)
mpz_set(max, c);
}
void free_levels(void) {
for (uint i = 0; i < k * maxfact + 1; ++i) {
t_level *l = &levels[i];
free(l->vlevel);
mpz_clear(l->aq);
mpz_clear(l->rq);
prime_iterator_destroy(&l->piter);
}
free(levels);
}
void init_levels(void) {
/* CHECKME: can this be maxodd * k + forcedp? */
levels = (t_level *)calloc(k * maxfact + nf.count + 1, sizeof(t_level));
for (uint i = 0; i < k * maxfact + 1; ++i) {
t_level *l = &levels[i];
l->level = i;
l->vlevel = calloc(k, sizeof(uint));
mpz_init(l->aq);
mpz_init(l->rq);
#if 0
/* not needed, prime_iterator_setprime() later will initialize */
prime_iterator_init(&l->piter);
#endif
}
mpz_set_ui(levels[0].aq, 1);
mpz_set_ui(levels[0].rq, 0);
levels[0].have_square = 0;
levels[0].have_min = (sminp || sminpx) ? 0 : 1;
levels[0].nextpi = 0;
levels[0].maxp = 0;
level = 1;
}
void free_value(void) {
for (int i = 0; i < k; ++i) {
t_value *v = &value[i];
for (int j = 0; j < maxfact; ++j)
mpz_clear(v->alloc[j].q);
free(v->alloc);
}
free(value);
}
void init_value(void) {
value = (t_value *)malloc(k * sizeof(t_value));
for (int i = 0; i < k; ++i) {
t_value *v = &value[i];
v->alloc = (t_allocation *)malloc(maxfact * sizeof(t_allocation));
for (uint j = 0; j < maxfact; ++j)
mpz_init(v->alloc[j].q);
}
}
void done(void) {
/* update window title on completion */
if (vt100)
printf("\x1b]2;b%d: done\a",
opt_batch_min < 0 ? batch_alloc : opt_batch_max);
free(diag_buf);
free(aux_buf);
if (wv_qq)
for (uint i = 0; i < k; ++i)
mpz_clear(wv_qq[i]);
free(wv_qq);
if (wv_o)
for (uint i = 0; i < k; ++i)
mpz_clear(wv_o[i]);
free(wv_o);
free(modfix);
free(minp);
free(maxp);
free(midp);
free(midpp);
free(sqg);
free_value();
free_levels();
free(sprimes);
if (forcep)
for (int i = 0; i < forcedp; ++i)
free(forcep[i].batch);
free(forcep);
free(maxforce);
if (divisors)
for (int i = 0; i <= n; ++i)
free(divisors[i].div);
free(divisors);
if (have_rwalk) {
mpz_clear(rwalk_from);
mpz_clear(rwalk_to);
}
if (rstack)
for (int i = 0; i < k; ++i)
free_fact(&rstack[i]);
free(rstack);
if (rfp)
fclose(rfp);
free(rpath);
for (t_zstash i = 0; i < MAX_ZSTASH; ++i)
mpz_clear(Z(i));
free(zstash);
mpz_clear(px);
free_fact(&nf);
mpz_clear(max);
mpz_clear(min);
done_pell();
done_rootmod();
done_tau();
_GMP_destroy();
}
void fail(char *format, ...) {
va_list ap;
va_start(ap, format);
vfprintf(stderr, format, ap);
fprintf(stderr, "\n");
va_end(ap);
/* we accept leaks on fatal error, but should close the log file */
if (rfp)
fclose(rfp);
exit(1);
}
void handle_sig(int sig) {
need_work = 1;
if (sig == SIGUSR1)
need_diag = 1;
else
need_log = 1;
}
void init_modfix(void) {
for (uint mfi = 0; mfi < modfix_count; ++mfi) {
t_modfix *mfp = &modfix[mfi];
mpz_t zarray[4];
/* TODO: write a custom chinese() */
memcpy(&zarray[0], levels[0].rq, sizeof(mpz_t));
memcpy(&zarray[1], mfp->val, sizeof(mpz_t));
memcpy(&zarray[2], levels[0].aq, sizeof(mpz_t));
memcpy(&zarray[3], mfp->mod, sizeof(mpz_t));
if (!chinese(levels[0].rq, levels[0].aq, &zarray[0], &zarray[2], 2))
fail("failed to apply v_0 == %Zu (mod %Zu)", mfp->val, mfp->mod);
mpz_clear(mfp->mod);
mpz_clear(mfp->val);
}
}
void init_time(void) {
struct sigaction sa;
struct sigevent sev;
struct itimerspec diag_timer, log_timer;
sa.sa_handler = &handle_sig;
sa.sa_flags = SA_RESTART;
sigemptyset(&sa.sa_mask);
if (diag_delay) {
if (sigaction(SIGUSR1, &sa, NULL))
fail("Could not set USR1 handler: %s\n", strerror(errno));
sev.sigev_notify = SIGEV_SIGNAL;
sev.sigev_signo = SIGUSR1;
sev.sigev_value.sival_ptr = &diag_timerid;
if (timer_create(CLOCK_PROCESS_CPUTIME_ID, &sev, &diag_timerid)) {
/* guess that the CPUTIME clock is not supported */
if (timer_create(CLOCK_REALTIME, &sev, &diag_timerid))
fail("Could not create diag timer: %s\n", strerror(errno));
clock_is_realtime = 1;
}
diag_timer.it_value.tv_sec = diag_delay;
diag_timer.it_value.tv_nsec = 0;
diag_timer.it_interval.tv_sec = diag_delay;
diag_timer.it_interval.tv_nsec = 0;
if (timer_settime(diag_timerid, 0, &diag_timer, NULL))
fail("Could not set diag timer: %s\n", strerror(errno));
}
if (log_delay) {
if (sigaction(SIGUSR2, &sa, NULL))
fail("Could not set USR2 handler: %s\n", strerror(errno));
sev.sigev_notify = SIGEV_SIGNAL;
sev.sigev_signo = SIGUSR2;
sev.sigev_value.sival_ptr = &log_timerid;
if (timer_create(CLOCK_PROCESS_CPUTIME_ID, &sev, &log_timerid)) {
/* guess that the CPUTIME clock is not supported */
if (timer_create(CLOCK_REALTIME, &sev, &log_timerid))
fail("Could not create log timer: %s\n", strerror(errno));
clock_is_realtime = 1;
}
log_timer.it_value.tv_sec = log_delay;
log_timer.it_value.tv_nsec = 0;
log_timer.it_interval.tv_sec = log_delay;
log_timer.it_interval.tv_nsec = 0;
if (timer_settime(log_timerid, 0, &log_timer, NULL))
fail("Could not set log timer: %s\n", strerror(errno));
}
}
void init_pre(void) {
_GMP_init();
/* reseed immediately to retain reproducibility */
clear_randstate();
init_randstate(1);
/* we may do this again after options handled, to select real seed */
init_pell();
t0 = utime();
mpz_init_set_ui(min, 0);
mpz_init_set_ui(max, 0);
init_fact(&nf);
mpz_init(px);
zstash = (mpz_t *)malloc(MAX_ZSTASH * sizeof(mpz_t));
for (t_zstash i = 0; i < MAX_ZSTASH; ++i)
mpz_init(Z(i));
mpz_set_ui(Z(zero), 0);
mpz_set_ui(Z(zone), 1);
mpz_init(best);
midp_recover.valid = 0;
}
/* Parse a "305" log line for initialization.
* Input string should point after the initial "305 ".
*/
void parse_305(char *s) {
double dtime;
t_ppow pp;
bool is_W = 0;
rstack = (t_fact *)malloc(k * sizeof(t_fact));
for (int i = 0; i < k; ++i)
init_fact(&rstack[i]);
if (s[0] == 'b') {
int off = 0;
if (EOF == sscanf(s, "b%u: %n", &batch_alloc, &off))
fail("error parsing 305 line '%s'", s);
s += off;
++batch_alloc; /* we always point to the next batch */
}
for (int i = 0; i < k; ++i) {
if (i) {
assert(s[0] == ' ');
++s;
}
if (s[0] == '.') {
++s;
continue;
}
while (1) {
pp.p = strtoul(s, &s, 10);
pp.e = (s[0] == '^') ? strtoul(&s[1], &s, 10) : 1;
add_fact(&rstack[i], pp);
if (s[0] != '.')
break;
++s;
}
/* reverse them, so we can pop as we allocate */
reverse_fact(&rstack[i]);
}
if (strncmp(s, " W(", 3) == 0) {
s += 3;
is_W = 1;
midp_recover.p = strtoul(s, &s, 10);
assert(s[0] == ',');
++s;
midp_recover.x = strtoul(s, &s, 10);
if (s[0] == ')') {
#if 1
/* new version uses different order, cannot reliably recover */
fail("cannot recover from old-style 'W(...)' entry");
#else
/* old version had x fixed to 3 */
midp_recover.vi = midp_recover.x;
midp_recover.x = 3;
#endif
} else {
assert(s[0] == ',');
++s;
midp_recover.vi = strtoul(s, &s, 10);
}
assert(s[0] == ')');
++s;
midp_recover.valid = 1;
}
if (s[0] == ':') {
assert(s[1] == ' ');
s += 2;
if (strncmp("t=1", s, 3) == 0)
s += 3; /* ignore */
else {
int from_start, from_end, to_start, to_end;
have_rwalk = 1;
if (EOF == sscanf(s, "%n%*[0-9]%n / %n%*[0-9]%n ",
&from_start, &from_end, &to_start, &to_end))
fail("could not parse 305 from/to: '%s'", s);
s[from_end] = 0;
mpz_init_set_str(rwalk_from, &s[from_start], 10);
s[to_end] = 0;
mpz_init_set_str(rwalk_to, &s[to_start], 10);
have_rwalk = 1;
s[to_end] = ' ';
s = &s[to_end];
}
}
if (s[0] == 0 || s[0] == '\n')
dtime = 0;
else if (EOF == sscanf(s, " (%lfs)\n", &dtime))
fail("could not parse 305 time: '%s'", s);
if (is_W && !need_midp)
fail("recovery expected -W option");
t0 -= dtime;
}
void recover(FILE *fp) {
char *last305 = NULL;
char *curbuf = NULL;
size_t len = 120, len305 = 0, len202 = 0;
fseek(fp, 0L, SEEK_SET);
while (1) {
ssize_t nread = getline(&curbuf, &len, fp);
if (nread <= 0) {
if (errno == 0)
break;
fail("error reading %s: %s", rpath, strerror(errno));
}
if (curbuf[nread - 1] != '\n'
|| memchr(curbuf, 0, nread) != NULL) {
/* corrupt line, file should be truncated */
off_t offset = ftello(fp);
if (offset == -1)
fail("could not ask offset: %s", strerror(errno));
/* not ftruncate(), we are open only for reading */
if (truncate(rpath, offset - nread) != 0)
fail("could not truncate %s to %lu: %s", rpath, offset - nread,
strerror(errno));
break;
}
if (strncmp("305 ", curbuf, 4) == 0) {
char *t = last305;
last305 = curbuf;
curbuf = t;
size_t lt = len305;
len305 = len;
len = lt;
} else if (strncmp("202 ", curbuf, 4) == 0) {
int start, end;
mpz_t cand;
if (EOF == sscanf(curbuf, "202 Candidate %n%*[0-9]%n (%*[0-9.]s)\n",
&start, &end))
fail("error parsing 202 line '%s'", curbuf);
curbuf[end] = 0;
mpz_init_set_str(cand, &curbuf[start], 10);
if (!seen_best || mpz_cmp(best, cand) >= 0)
mpz_set(best, cand);
seen_best = 1;
mpz_clear(cand);
} else if (strncmp("001 ", curbuf, 4) == 0) {
/* TODO: parse and check for consistent options */
start_seen = 1;
} else if (strncmp("000 ", curbuf, 4) == 0)
; /* comment */
else if (strncmp("203 ", curbuf, 4) == 0)
; /* batch number */
else
fail("unexpected log line %.3s in %s", curbuf, rpath);
}
fseek(fp, 0L, SEEK_END);
if (improve_max && seen_best && mpz_cmp(best, max) < 0)
mpz_set(max, best);
if (last305)
parse_305(last305 + 4);
fseek(fp, 0L, SEEK_SET);
free(curbuf);
free(last305);
}
int cmp_high(const void *va, const void *vb) {
uint a = *(uint *)va, b = *(uint *)vb;
return (int)divisors[b].high - (int)divisors[a].high;
}
/* Note this is used only for prep_primes(), not at runtime */
ulong next_prime(ulong cur) {
mpz_set_ui(Z(np_p), cur);
_GMP_next_prime(Z(np_p));
if (mpz_fits_ulong_p(Z(np_p)))
return mpz_get_ui(Z(np_p));
fail("next_prime overflow\n");
}
/* recurse() wants the list of powers to try: each divisor of t_i (which
* itself divides n) that is divisible by the highest odd prime factor
* dividing t_i, in increasing order.
* prep_forcep() wants the full list of divisors, but in similar order.
* For each power, recurse() also wants to know which powers to skip
* if the previous power was a given value, but that's simply:
* skip x' if x' < x and high(x') == high(x).
* mintau() wants sumpm, sum{p_j - 1} of the primes dividing t_i with
* multiplicity.
* When a square is fixed, walk_v() wants gcddm, the gcd{d_j-1} of all
* divisors d_j of t_i.
*/
void prep_fact(void) {
t_fact f;
divisors = (t_divisors *)calloc(n + 1, sizeof(t_divisors));
init_fact(&f);
for (uint i = 1; i <= n; ++i) {
if (n % i)
continue;
t_divisors *dp = &divisors[i];
f.count = 0;
simple_fact(i, &f);
uint td = simple_tau(&f);
dp->high = (f.count) ? f.ppow[f.count - 1].p : 1;
dp->sumpm = dp->high - 1;
dp->sumpm += divisors[i / dp->high].sumpm;
uint nd = 0;
dp->div = (uint *)malloc(td * sizeof(uint));
for (uint j = 1; j <= i; ++j) {
if (i % j)
continue;
dp->div[dp->alldiv++] = j;
if ((j % dp->high) == 0)
++dp->highdiv;
}
qsort(dp->div, dp->alldiv, sizeof(uint), &cmp_high);
uint g = dp->div[0] - 1;
for (uint di = 1; di < dp->alldiv; ++di)
g = tiny_gcd(g, dp->div[di] - 1);
dp->gcddm = g;
}
free_fact(&f);
}
void prep_mintau(void) {
return;
}
void prep_maxforce(void) {
maxforce = (uint *)malloc(k * sizeof(uint));
#if defined(TYPE_o)
if ((n & 3) != 0) {
for (int i = 0; i < k; ++i)
maxforce[i] = k;
} else
#endif
for (int i = 0; i < k; ++i) {
int mf = k - i - 1;
if (i > mf)
mf = i;
if (force_all > mf)
mf = force_all;
maxforce[i] = mf;
}
}
void prep_primes(void) {
/* We can certainly not allocate more than (each of the forced primes)
* plus (one per odd prime factor for each v_i); in practice it will
* usually be less.
* In mintau() we may need maxfact primes beyond what may have been
* allocated in k-1 places. */
nsprimes = maxodd * k + forcedp + (maxfact - maxodd);
sprimes = (uint *)malloc(nsprimes * sizeof(uint));
uint p = 1;
for (uint i = 0; i < nsprimes; ++i) {
p = next_prime(p);
sprimes[i] = p;
}
}
typedef enum {
TFP_BAD = 0,
TFP_SINGLE,
TFP_GOOD
} e_tfp;
e_tfp test_forcep(uint p, uint vi, uint x) {
bool seen_any = 0;
bool seen_odd = 0;
if (x == 0) {
/* p^0 is valid iff the differences are a multiple of p */
if (TYPE_OFFSET(1) % p)
return TFP_BAD;
return TFP_GOOD;
}
if (x & (x - 1))
seen_odd = 1;
uint ei = x - 1;
for (uint j = 1; j <= vi; ++j) {
uint vj = vi - j;
uint off = TYPE_OFFSET(j);
uint ej = simple_valuation(off, p);
if (ej == 0)
continue;
if (n % (ej + 1))
return TFP_BAD;
seen_any = 1;
if (ej & (ej + 1))
seen_odd = 1;
if (ej < ei)
continue;
/* Earlier element cannot have same or higher power of p */
return TFP_BAD;
}
if (p > 8 * sizeof(ulong))
fail("TODO: cope with p > %u", 8 * sizeof(ulong));
/* set bits for moduli 1 .. p - 1 */
ulong seen_same = (1 << p) - 2;
for (uint j = 1; j + vi < k; ++j) {
uint vj = vi + j;
uint off = TYPE_OFFSET(j);
uint ej = simple_valuation(off, p);
if (ej == 0)
continue;
seen_any = 1;
if (ej & (ej + 1))
seen_odd = 1;
if (ej > ei)
continue; /* p^e_i + p^e_j will have valuation e_i */
if (n % (ej + 1))
return TFP_BAD;
if (ej < ei)
continue;
/* p^e_i + p^e_i can have valuation e_i as long as we don't
* exceed the (p-1) possible values mod p */
for (uint i = 0; i < ei; ++i)
off /= p;
seen_same &= ~(1 << (off % p));
}
if (seen_same == 0)
/* all moduli seen, so one must have a higher power of p */
return TFP_BAD;
if (unforce_all && p >= unforce_all && !seen_odd)
return TFP_SINGLE;
if (seen_any)
return TFP_GOOD;
return TFP_SINGLE;
}
void prep_forcep(void) {
mpz_t pz;
uint p;
uint pi[k];
forcedp = 0;
mpz_init_set_ui(pz, 1);
#if defined(TYPE_o)
while (1) {
_GMP_next_prime(pz);
p = mpz_get_ui(pz);
if (p > k)
break;
pi[forcedp++] = p;
}
#elif defined(TYPE_a)
/* divisors of n must be force_all, so must come before other primes */
for (uint i = 0; i < nf.count; ++i) {
p = (uint)nf.ppow[i].p;
pi[forcedp++] = p;
}
while (1) {