-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathcoul.c
4799 lines (4500 loc) · 147 KB
/
coul.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
/* needed on FreeBSD for getline() to be exported from stdio.h */
#define _WITH_GETLINE
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <stdarg.h>
#include <string.h>
#include <errno.h>
#include <assert.h>
/* used to set process title */
#include <sys/prctl.h>
#include <signal.h>
#include <time.h>
#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"
#include "coulvec.h"
#include "assume.h"
/* from MPUG */
#include "factor.h"
#include "gmp_main.h"
#include "utility.h"
#include "primality.h"
/* primary parameters - we are searching for f(n, k), the least d such
* that for all 0 <= i < k:
* (if compiled with TYPE_o): tau(d + i) = n
* (if compiled with TYPE_a): tau(d + in) = n
* (if compiled with TYPE_r): tau(d + i) = tau(n + i), d <> n
* (if compiled with TYPE_t): tau(n + di) = tau(n)
* (TYPE_t not yet supported.)
*/
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;
}
/* We assume x != 0 */
#ifdef __GNUC__
static inline bool ispow2(ulong x) {
return __builtin_popcountl(x) == 1;
}
#else
static inline bool ispow2(ulong x) {
return (x & (x - 1)) == 0;
}
#endif
/* stash of mpz_t, initialized once at start */
typedef enum {
zero, zone, /* constants */
temp,
tfp_v, /* test_forcep */
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_qqnext, 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 */
j4a, j4b, j4m, j4p, j4q, /* best_6x() */
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] */
/* for failure diagnostics */
mpz_t *g_q0;
uint g_ati;
/* used to store disallowed inverses in walk_v() */
typedef struct s_mod {
ulong v;
ulong m;
} t_mod;
/* warn if the divisor array will be bigger than this */
#define DIVISOR_WARN_LIMIT (100000)
t_divisors *divisors = NULL;
#if defined(TYPE_r)
uint *target_tau = NULL;
uint target_lcm;
static inline uint target_t(uint vi) { return target_tau[vi]; }
#else
# define target_lcm (n)
static inline uint target_t(uint vi) { return n; }
#endif
/* 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).
*
* The "primary" of a batch is the least index v_i at which the greatest
* power of p appears.
*/
typedef struct s_forcebatch {
uint primary; /* x[primary] is first max */
uint x[0]; /* allocate p^{x-1} at v_i for i: 0..k-1 */
} t_forcebatch;
static inline size_t size_forcebatch(void) {
return sizeof(t_forcebatch) + k * sizeof(uint);
}
typedef struct s_forcep {
uint p;
uint count;
t_forcebatch *batch; /* beware, struct is dynamically sized */
} 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 */
uint maxlevel; /* avvailable entries in levels[] */
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) {
getrusage(RUSAGE_SELF, &rusage_buf);
return (double)rusage_buf.ru_utime.tv_sec
+ (double)rusage_buf.ru_utime.tv_usec / 1000000;
}
timer_t diag_timerid, log_timerid;
volatile bool need_work, need_diag, need_log;
bool clock_is_realtime = 0;
mpz_t zmin, zmax; /* limits to check for v_0 */
mpz_t best; /* best solution seen */
bool improve_max = 1; /* reduce zmax when solution found */
uint seen_best = 0; /* number of times we've improved zmax */
ulong gain = 0; /* used to fine-tune balance of recursion vs. walk */
ulong antigain = 0;
ulong gain2 = 0; /* as gain/antigain for squares */
ulong antigain2 = 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 highpow = 0; /* allocate even p^{2^x-1} (based on roughness) */
ulong limp_cap = 0;
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 */
uint opt_flake = 0; /* test less before printing candidates */
/* 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 */
bool seen_valid = 0; /* if nothing seen, this case has no solutions */
/* by default, we call walk_v() as soon as we have 2 values fixed to
* be squares rather than waiting for a full batch allocation; however
* this can stop us noticing that there are no valid batches. Running
* with '-jp' tells us to wait until we have a full batch before doing
* a Pell walk.
*/
bool defer_pell = 0;
uint strategy; /* best_v() strategy */
uint strategy_set = 0; /* strategy was user-selected */
uint prev_strategy; /* for special-case strategy override */
/* best_6x() special-case strategy (TYPE_o only) */
#define STRATEGY_6X 5
uint check = 0; /* modulus to check up to */
uint check_prime = 0; /* skip moduli divisible by prime greater than this */
double check_ratio = 1.0; /* drop moduli that have too low rejection ratio */
uint check_chunk = 0; /* combine moduli into chunks of this size */
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 */
bool debugf = 0; /* show prepped sub-batches */
bool debugt = 0; /* show target_t() */
bool debugv = 0; /* show modular constraints */
bool debugV = 0; /* show more modular constraints */
bool log_full = 0; /* show prefinal result for harness */
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 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;
/* Default cvec context */
t_context *cx0 = NULL;
/* Mod constraints set with -m */
typedef struct s_modfix {
mpz_t mod;
mpz_t val;
bool negate;
} t_modfix;
t_modfix *modfix = NULL;
uint modfix_count = 0;
bool have_modfix = 0;
typedef struct s_sizedstr {
char *s;
size_t size;
} t_sizedstr;
uint tm_count = 0;
static inline void test_multi_reset(void) {
tm_count = 0;
}
/* Note: test_multi_append() steals the input mpz_t */
static inline bool test_multi_append(mpz_t n, uint vi, uint t, uint e) {
uint i = tm_count++;
t_tm *tm = &taum[i];
mpz_swap(tm->n, n);
tm->vi = vi;
tm->t = t;
tm->e = e;
return tau_multi_prep(i);
}
/* Note: test_prime_append() steals the input mpz_t */
static inline bool test_prime_append(mpz_t n, uint vi) {
uint i = tm_count++;
t_tm *tm = &taum[i];
mpz_swap(tm->n, n);
tm->vi = vi;
tm->t = 2;
tm->e = 1;
return tau_prime_prep(i);
}
static inline uint test_prime_run(void) {
return tau_prime_run(tm_count);
}
static inline uint test_multi_run(tau_failure_handler tfh) {
return tau_multi_run(tm_count, tfh);
}
#if defined(TYPE_o) || defined(TYPE_r)
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
static inline char typename(void) {
#if defined(TYPE_o)
return 'o';
#elif defined(TYPE_a)
return 'a';
#elif defined(TYPE_r)
return 'r';
#endif
}
uint know_target(uint vi) {
#if defined(TYPE_r)
t_fact f;
init_fact(&f);
simple_fact(n + vi, &f);
uint t = simple_tau(&f);
free_fact(&f);
return t;
#else
return n;
#endif
}
#ifdef TRACK_STATS
ulong* count_bad;
static inline void TRACK_GOOD(uint vk, uint vi) { }
static inline void TRACK_BAD(uint vk, uint vi) {
++count_bad[vk];
}
static inline void TRACK_MULTI(uint count, uint* need, t_tm *tm) {
++count_bad[k - count];
}
void init_stats(uint k) {
count_bad = calloc(k + 1, sizeof(ulong));
}
void done_stats(void) {
free(count_bad);
}
#else
static inline void TRACK_GOOD(uint vk, uint vi) { }
static inline void TRACK_BAD(uint vk, uint vi) { }
static inline void TRACK_MULTI(uint count, uint* need, t_tm *tm) { }
void init_stats(uint k) { }
void done_stats(void) { }
#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 == 1)
diag_buf[offset++] = '.';
else {
t_value *vp = &value[vi];
for (uint ai = 1; ai < vlevel; ++ai) {
t_allocation *ap = &vp->alloc[ai];
if (ai > 1)
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);
}
}
double seconds(double t1) {
return (t1 - t0);
}
double elapsed(void) {
return seconds(utime());
}
uint _sizeinbase(uint n, uint base) {
uint size = 1;
while (n >= base) {
++size;
n /= base;
}
return size;
}
uint write_fact(t_sizedstr *bufp, mpz_t v, uint target) {
factor_state fs;
uint t = 1;
if (mpz_cmp_ui(v, 1) == 0) {
bufp->s = realloc(bufp->s, 2);
bufp->size = sprintf(bufp->s, "1");
return t;
}
fs_init(&fs);
mpz_set(fs.n, v);
while (1) {
if (!factor_one(&fs))
break;
t *= fs.e + 1;
uint next = bufp->size ? 1 : 0;
uint size = bufp->size + next + 1;
size += mpz_sizeinbase(fs.f, 10);
if (fs.e > 1)
size += 1 + _sizeinbase(fs.e, 10);
bufp->s = realloc(bufp->s, size);
bufp->size += gmp_sprintf(&bufp->s[bufp->size], "%s%Zu",
(next ? "." : ""), fs.f);
if (fs.e > 1)
bufp->size += sprintf(&bufp->s[bufp->size], "^%u", fs.e);
}
fs_clear(&fs);
return t;
}
bool report_211(uint vi, t_sizedstr *bufp) {
/* 211 Sequence 0: 4 = tau(1248619267217398415 = 5.249723853443479683) */
mpz_add_ui(Z(temp), best, vi);
uint target = know_target(vi);
uint t = write_fact(bufp, Z(temp), target);
report("211 Sequence %d: %d = tau(%Zu = %s)\n",
vi, t, Z(temp), bufp->s);
bufp->size = 0;
return t == target;
}
void report_prefinal(double tz) {
if (!seen_best) {
/* 500 f(241, 9) > 56346707724292074686037507 (655.570s) */
report("500 f(%d, %d) > %Zd (%.3fs)\n",
n, k, zmax, seconds(tz));
return;
}
t_sizedstr buf = { NULL, 0 };
bool good = 1;
for (uint i = 0; i <= k || good; ++i)
if (!report_211(i, &buf))
good = 0;
free(buf.s);
}
/* 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) {
#ifdef TRACK_STATS
fprintf(rfp, "305 %s%s (%.2fs) [", diag_buf, aux_buf, seconds(t1));
for (uint i = 0; i < k; ++i) {
if (i)
fprintf(rfp, " ");
fprintf(rfp, "%lu", count_bad[i]);
}
fprintf(rfp, "]\n");
#else
fprintf(rfp, "305 %s%s (%.2fs)\n", diag_buf, aux_buf, seconds(t1));
#endif
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 && !debugW && pc));
}
/* Record a found candidate; returns FALSE if we should continue testing
* larger candidates with the current set of allocations.
*/
bool candidate(mpz_t c) {
#if defined(TYPE_r)
if (mpz_fits_ulong_p(c) && mpz_get_ui(c) == n)
return 0;
#endif
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, zmax) <= 0)
mpz_set(zmax, c);
return improve_max;
}
void free_levels(void) {
for (uint i = 0; i < maxlevel; ++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) {
levels = (t_level *)calloc(maxlevel + 1, sizeof(t_level));
for (uint i = 0; i < maxlevel; ++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].next_best = 0;
levels[0].nextpi = 0;
levels[0].maxp = 0;
for (uint j = 0; j < k; ++j)
levels[0].vlevel[j] = 1;
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);
mpz_clear(v->alloc[j].lim);
}
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 + 1) * sizeof(t_allocation));
for (uint j = 0; j <= maxfact; ++j) {
mpz_init(v->alloc[j].q);
mpz_init(v->alloc[j].lim);
}
t_allocation *ap = &v->alloc[0];
ap->p = 0;
ap->x = 0;
ap->t = target_t(i);
mpz_set_ui(ap->q, 1);
}
}
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);
if (check)
cvec_done(cx0);
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(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 <= target_lcm; ++i)
free(divisors[i].div);
free(divisors);
#if defined(TYPE_r)
free(target_tau);
#endif
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(zmax);
mpz_clear(zmin);
mpz_clear(best);
done_pell();
done_rootmod();
done_stats();
done_tau();
_GMP_destroy();
}
void fail_silent(void) {
/* we accept leaks on fatal error, but should close the log file */
if (rfp)
fclose(rfp);
exit(0);
}
void fail(char *format, ...) {
va_list ap;
va_start(ap, format);
gmp_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_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(zmin, 0);
mpz_init_set_ui(zmax, 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 {
int off = 0;
if (EOF == sscanf(s, " (%lfs)%n", &dtime, &off))
fail("could not parse 305 time: '%s'", s);
#ifdef TRACK_STATS
s += off;
if (EOF != sscanf(s, " [")) {
s += 2;
for (uint i = 0; i < k; ++i) {
if (i) {
if (s[0] == ' ')
++s;
else
fail("could not parse 305 time: '%s'", s);
}
if (EOF == sscanf(s, "%lu%n", &count_bad[i], &off))
fail("could not parse 305 time: '%s'", s);
s += off;
}
if (s[0] != ']')
fail("could not parse 305 time: '%s'", s);
++s;
}
#endif
}
if (is_W && !need_midp)
fail("recovery expected -W option");
t0 -= dtime;
}
void recover(FILE *fp) {
char *last305 = NULL;
char *curbuf = NULL;