-
Notifications
You must be signed in to change notification settings - Fork 1
/
combined_sieve.cpp
2445 lines (2008 loc) · 88.7 KB
/
combined_sieve.cpp
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
// Copyright 2020 Seth Troisi
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <algorithm>
#include <cassert>
#include <chrono>
#include <clocale>
#include <cmath>
#include <csignal>
#include <cstdio>
#include <functional>
#include <iostream>
#include <map>
#include <mutex>
#include <sstream>
#include <thread>
#include <type_traits>
#include <vector>
#include <gmp.h>
#include <omp.h>
#include <primesieve.hpp>
#include "gap_common.h"
#include "modulo_search.h"
using std::cout;
using std::endl;
using std::map;
using std::mutex;
using std::pair;
using std::vector;
using namespace std::chrono;
/**
* Two MACROS used to validate results
* GMP_VALIDATE_FACTORS (validates all factors)
* GMP_VALIDATE_LARGE_FACTORS (validate large factors)
*
* GMP_VALIDATE_LARGE_FACTORS only validates the rarer 60+ bit factors
*/
// Tweaking this doesn't seem to method1 much.
// method2 is more sensitive and set it's own.
#define SMALL_PRIME_LIMIT_METHOD1 400'000
// Compresses composite by 50-80%,
// Might make large prime faster but never makes sense because
// Of increased memory size (and time for count unknows)
#define METHOD2_WHEEL 1
// This probably should be optimized to fit in L2/L3
// Related to sizeof(int) * SIEVE_INTERVAL * WHEEL_MAX
// WHEEL should divide config.d
#define METHOD2_WHEEL_MAX (2*3*5*7)
void set_defaults(struct Config& config);
void prime_gap_search(const struct Config& config);
void prime_gap_parallel(struct Config& config);
int main(int argc, char* argv[]) {
// Display %'d with commas i.e. 12,345
setlocale(LC_NUMERIC, "");
Config config = Args::argparse(argc, argv, Args::Pr::SIEVE);
if (config.verbose >= 2) {
printf("\tCompiled with GMP %d.%d.%d\n\n",
__GNU_MP_VERSION, __GNU_MP_VERSION_MINOR, __GNU_MP_VERSION_PATCHLEVEL);
}
// More combined sieve specific validation
{
set_defaults(config);
// Both shouldn't be true from gap_common.
assert(!(config.save_unknowns && config.testing));
if (!config.save_unknowns && !config.testing) {
cout << "Must set --save-unknowns" << endl;
exit(1);
}
if (config.sieve_length < 6 * config.p || config.sieve_length > 22 * config.p) {
int sl_min = ((config.p * 8 - 1) / 500 + 1) * 500;
int sl_max = ((config.p * 20 - 1) / 500 + 1) * 500;
printf("--sieve_length(%d) should be between [%d, %d]\n",
config.sieve_length, sl_min, sl_max);
exit(1);
}
if (config.valid == 0) {
Args::show_usage(argv[0], Args::Pr::SIEVE);
exit(1);
}
if (config.max_prime > 500'000'000) {
float m_per = config.max_prime / ((float) config.minc * config.sieve_length);
if (m_per < .1 && config.p <= 8000) {
printf("\tmax_prime(%ldB) is probably too large\n",
config.max_prime / 1'000'000'000);
}
}
if (config.save_unknowns) {
std::string fn = Args::gen_unknown_fn(config, ".txt");
std::ifstream f(fn);
if (f.good()) {
printf("\nOutput file '%s' already exists\n", fn.c_str());
exit(1);
}
}
if (!config.compression && (config.minc * config.sieve_length) > 100'000'000'000L) {
printf("\tSetting --bitcompress to prevent very large output file\n");
config.compression = 2;
}
if (!config.compression && (config.minc * config.sieve_length) > 30'000'000'000L) {
printf("\tSetting --rle to prevent very large output file\n");
config.compression = 1;
}
}
// Status lines
if (config.verbose >= 0) {
printf("\n");
printf("Testing m * %u#/%u, m = %'ld + [0, %'ld)\n",
config.p, config.d, config.mstart, config.minc);
}
if (config.verbose >= 2 && config.threads > 1) {
printf("Running with %d threads\n", config.threads);
}
#ifdef GMP_VALIDATE_FACTORS
printf("\tValidating factors with GMP\n");
#endif
if (config.method1) {
prime_gap_search(config);
} else {
prime_gap_parallel(config);
}
}
void set_defaults(struct Config& config) {
if (config.valid == 0) {
// Don't do anything if argparse didn't work.
return;
}
if (config.d % 4 == 0) {
// AKA min-merit
config.sieve_length = config.p * config.min_merit;
// Start from 1
config.mstart = 1;
// Large prime near P to make D unique (chosen semi-randomly)
config.d /= 4;
vector<uint32_t> P_primes = get_sieve_primes(config.p);
uint32_t rand_prime = P_primes[P_primes.size() - 2 - (rand() % 10)];
uint32_t large_p = config.d > 1 ? config.d : rand_prime;
assert(is_prime_brute(large_p));
printf("d optimizer for P = %d# | large prime=%d | SL=%d (%.1f merit)\n",
config.p, large_p, config.sieve_length, config.min_merit);
/**
* Secret value to optimize d
* 1. Test small primorials to find optimal primorial
* 2. Multiple by large prime (to make unique)
* 3. test that ~same expected
*/
vector<uint32_t> primes = {1,2,3,5,7,11,13,17,19,23};
for (uint32_t lp : {1u, large_p}) {
config.d = lp;
for (uint32_t p : primes) {
// check if large_p already includes p
if (p != 1 && config.d % p == 0)
continue;
if (__builtin_umul_overflow(config.d, p, &config.d)) {
// overflow
break;
}
// Try searching all values of m (up to 20,000)
config.minc = std::min(config.d, 20'000U);
auto expected = count_K_d(config);
printf("Optimizing | d = %5d * %2d# | %d remaining, %5.0f avg gap | SL insufficient %.3f%% of time\n",
lp, p, std::get<1>(expected), std::get<0>(expected), 100 * std::get<2>(expected));
}
}
exit(0);
}
mpz_t K;
double K_log;
{
// Suppress log
int temp = config.verbose;
config.verbose = -1;
int K_digits;
K_stats(config, K, &K_digits, &K_log);
config.verbose = temp;
}
if (config.sieve_length == 0) {
// Change that a number near K is prime
// GIVEN no factor of K or D => no factor of P#
const double prob_prime_coprime_P = prob_prime_coprime(config);
// factors of K = P#/D
vector<uint32_t> K_primes = get_sieve_primes(config.p);
// Remove any factors of D
K_primes.erase(
std::remove_if(K_primes.begin(), K_primes.end(),
[&](uint32_t p){ return config.d % p == 0; }),
K_primes.end());
// K = #P/D
// only numbers K+i has no factor <= p
// => (K+i, i) == (K, i) == 1
// => only relatively prime i's
//
// factors of d are hard because they depend on m*K
// some of these m are worse than others so use worst m
assert( config.p >= 503 );
// Search till chance of shorter gap is small.
{
// Code below is quite slow with larger values of d.
assert( config.d <= 30030 );
uint32_t base = mpz_fdiv_ui(K, config.d);
// count of (m*K) % d over all m
vector<uint32_t> count_by_mod_d(config.d, 0);
{
for (uint64_t mi = 0; mi < config.minc; mi++) {
uint64_t m = config.mstart + mi;
if (gcd(m, config.d) == 1) {
uint32_t center = ((__int128) m * base) % config.d;
uint32_t center_down = (config.d - center) % config.d;
// distance heading up
count_by_mod_d[ center ] += 1;
// distance heading up
count_by_mod_d[ center_down ] += 1;
}
}
}
// Note: By averaging over counts prob_larger could be improve here.
map<uint32_t, uint32_t> coprime_by_mod_d;
for (size_t i = 0; i < config.d; i++) {
if (count_by_mod_d[i] > 0) {
coprime_by_mod_d[i] = 0;
}
}
// Keep increasing SL till prob_gap_shorter < 0.8%
for (size_t tSL = 1; ; tSL += 1) {
bool any_divisible = false;
for (int prime : K_primes) {
if ((tSL % prime) == 0) {
any_divisible = true;
break;
}
}
// Result will be the same as last.
if (any_divisible) continue;
// check if tSL is divisible for all center mods
for (auto& coprime_counts : coprime_by_mod_d) {
const auto center = coprime_counts.first;
// Some multiple of d will mark this off (for these centers) don't count it.
if (gcd(center + tSL, config.d) == 1) {
coprime_counts.second += 1;
}
}
// Find the smallest number of coprimes
uint32_t min_coprime = tSL;
for (auto& coprime_counts : coprime_by_mod_d) {
min_coprime = std::min(min_coprime, coprime_counts.second);
}
// Assume each coprime is independent
double prob_gap_shorter = pow(1 - prob_prime_coprime_P, min_coprime);
// This seems to balance PRP fallback and sieve_size
if (prob_gap_shorter <= 0.008) {
config.sieve_length = tSL;
printf("AUTO SET: sieve length: %ld (coprime: %d, prob_gap longer %.2f%%)\n",
tSL, min_coprime, 100 * prob_gap_shorter);
break;
}
}
}
assert( config.sieve_length > 100 ); // Something went wrong above.
}
if (config.max_prime == 0) {
// each additional numbers removes unknowns / prime
// and takes log2(prime / sieve_length) time
// Not worth improving given method2 CTRL+C handling.
if (K_log >= 1500) {
config.max_prime = 100'000'000'000;
} else {
config.max_prime = 10'000'000'000;
}
if (config.method1) {
printf("Can't use method1 and not set max_prime");
exit(1);
}
if (config.verbose >= 0) {
printf("AUTO SET: max_prime (log(K) = ~%.0f): %ld\n",
K_log, config.max_prime);
printf("WATCH for 'Estimated 2x faster (CTRL+C to stop sieving)' warning");
}
}
mpz_clear(K);
}
static void insert_range_db(
const struct Config& config,
long num_rows,
float time_sieve) {
DB db_helper(config.search_db.c_str());
sqlite3 *db = db_helper.get_db();
const uint64_t rid = db_helper.config_hash(config);
char sSQL[300];
sprintf(sSQL,
"INSERT INTO range(rid, P,D, m_start,m_inc,"
"sieve_length, max_prime,"
"min_merit,"
"num_m,"
"time_sieve)"
"VALUES(%ld, %d,%d, %ld,%ld,"
"%d,%ld, %.3f,"
"%ld, %.2f)"
"ON CONFLICT(rid) DO UPDATE SET time_sieve=%.2f",
rid, config.p, config.d, config.mstart, config.minc,
config.sieve_length, config.max_prime,
config.min_merit,
num_rows,
time_sieve, time_sieve);
char *zErrMsg = nullptr;
int rc = sqlite3_exec(db, sSQL, nullptr, nullptr, &zErrMsg);
if (rc != SQLITE_OK) {
printf("\nrange INSERT failed %d: %s\n",
rc, sqlite3_errmsg(db));
exit(1);
}
}
// Method1
void save_unknowns_method1(
std::ofstream &unknown_file,
const uint64_t m, int unknown_p, int unknown_n,
const unsigned int SL, const vector<char> composite[]) {
unknown_file << m << " : -" << unknown_p << " +" << unknown_n << " |";
for (int d = 0; d <= 1; d++) {
char prefix = "-+"[d];
for (size_t i = 1; i <= SL; i++) {
if (!composite[d][i]) {
unknown_file << " " << prefix << i;
}
}
if (d == 0) {
unknown_file << " |";
}
}
unknown_file << "\n";
}
void prime_gap_search(const struct Config& config) {
//const uint64_t P = config.p;
const uint64_t D = config.d;
const uint64_t M_start = config.mstart;
const uint64_t M_inc = config.minc;
const unsigned int SIEVE_LENGTH = config.sieve_length;
const unsigned int SL = SIEVE_LENGTH;
const uint64_t MAX_PRIME = config.max_prime;
mpz_t test;
mpz_init(test);
if (config.verbose >= 2) {
printf("\n");
printf("sieve_length: 2x %'d\n", config.sieve_length);
printf("max_prime: %'ld\n", MAX_PRIME);
printf("\n");
}
// ----- Generate primes under SMALL_PRIME_LIMIT_METHOD1
vector<uint32_t> small_primes;
primesieve::generate_primes(SMALL_PRIME_LIMIT_METHOD1, &small_primes);
// ----- Merit / Sieve stats
mpz_t K;
prob_prime_and_stats(config, K);
// ----- Sieve stats
const size_t SMALL_PRIME_PI = small_primes.size();
{
// deals with all primes that can mark off two items in SIEVE_LENGTH.
assert( SMALL_PRIME_LIMIT_METHOD1 > 2 * SIEVE_LENGTH );
if (config.verbose >= 1) {
printf("\tUsing %'ld primes for SMALL_PRIME_LIMIT(%'d)\n\n",
SMALL_PRIME_PI, SMALL_PRIME_LIMIT_METHOD1);
}
assert( small_primes[SMALL_PRIME_PI-1] < SMALL_PRIME_LIMIT_METHOD1);
assert( small_primes[SMALL_PRIME_PI-1] + 200 > SMALL_PRIME_LIMIT_METHOD1);
}
const auto s_setup_t = high_resolution_clock::now();
// ----- Allocate memory for a handful of utility functions.
// Remainders of (p#/d) mod prime
typedef pair<uint64_t,uint64_t> p_and_r;
vector<p_and_r> prime_and_remainder;
prime_and_remainder.reserve(SMALL_PRIME_PI);
// Big improvement over surround_prime is avoiding checking each large prime.
// vector<m, vector<pi>> for large primes that only rarely divide a sieve
int s_large_primes_rem = 0;
double expected_primes_per = 0;
// To save space, only save remainder for primes that divide ANY m in range.
// This helps with memory usage when MAX_PRIME >> SL * MINC;
auto *large_prime_queue = new vector<p_and_r>[M_inc];
{
size_t pr_pi = 0;
if (config.verbose >= 0) {
printf("\tCalculating first m each prime divides\n");
}
// large_prime_queue size can be approximated by
// https://en.wikipedia.org/wiki/Meissel–Mertens_constant
// Print "."s during, equal in length to 'Calculating ...'
size_t print_dots = 38;
const size_t expected_primes = primepi_estimate(MAX_PRIME);
long first_m_sum = 0;
if (config.verbose >= 0) {
cout << "\t";
}
size_t pi = 0;
primesieve::iterator it;
for (uint64_t prime = it.next_prime(); prime <= MAX_PRIME; prime = it.next_prime()) {
pi += 1;
if (config.verbose >= 0 && (pi * print_dots) % expected_primes < print_dots) {
cout << "." << std::flush;
}
// Big improvement over surround_prime is reusing this for each m.
const uint64_t base_r = mpz_fdiv_ui(K, prime);
if (prime <= SMALL_PRIME_LIMIT_METHOD1) {
prime_and_remainder.emplace_back(prime, base_r);
pr_pi += 1;
continue;
}
expected_primes_per += (2.0 * SL + 1) / prime;
// solve base_r * (M + mi) + (SL - 1)) % prime < 2 * SL
// 0 <= (base_r * M + SL - 1) + base_r * mi < 2 * SL mod prime
//
// let shift = (base_r * M + SL - 1) % prime
// 0 <= shift + base_r * mi < 2 * SL mod prime
// add (prime - shift) to all three
//
// (prime - shift) <= base_r * mi < (prime - shift) + 2 * SL mod prime
uint64_t mi = modulo_search_euclid_gcd(
M_start, D, M_inc, SL, prime, base_r);
// signals mi > M_inc
if (mi == M_inc) continue;
assert (mi < M_inc);
// (M_start + mi) * last_prime < int64 (checked in argparse)
uint64_t first = (base_r * (M_start + mi) + SL) % prime;
assert( first <= 2*SL );
//assert ( gcd(M + mi, D) == 1 );
large_prime_queue[mi].emplace_back(prime, base_r);
pr_pi += 1;
s_large_primes_rem += 1;
first_m_sum += mi;
}
if (config.verbose >= 0) {
cout << endl;
}
assert(prime_and_remainder.size() == small_primes.size());
if (config.verbose >= 1) {
printf("\tSum of m1: %ld\n", first_m_sum);
if (pi == expected_primes) {
printf("\tPrimePi(%ld) = %ld\n", MAX_PRIME, pi);
} else {
printf("\tPrimePi(%ld) = %ld guessed %ld\n", MAX_PRIME, pi, expected_primes);
}
printf("\t%ld primes not needed (%.1f%%)\n",
(pi - SMALL_PRIME_PI) - pr_pi,
100 - (100.0 * pr_pi / (pi - SMALL_PRIME_PI)));
double mertens3 = log(log(MAX_PRIME)) - log(log(SMALL_PRIME_LIMIT_METHOD1));
double theory_count = (2 * SL + 1) * mertens3;
printf("\texpected large primes/m: %.1f (theoretical: %.1f)\n",
expected_primes_per, theory_count);
}
}
if (config.verbose >= 0) {
auto s_stop_t = high_resolution_clock::now();
double secs = duration<double>(s_stop_t - s_setup_t).count();
printf("\n\tSetup took %.1f seconds\n", secs);
}
// ----- Open and Save to Output file
std::ofstream unknown_file;
if (config.save_unknowns) {
std::string fn = Args::gen_unknown_fn(config, ".txt");
printf("\nSaving to '%s'\n", fn.c_str());
unknown_file.open(fn, std::ios::out);
assert( unknown_file.is_open() ); // Can't open save_unknowns file
}
// ----- Main sieve loop.
vector<char> composite[2] = {
vector<char>(SIEVE_LENGTH+1, 0),
vector<char>(SIEVE_LENGTH+1, 0)
};
assert( composite[0].size() == SIEVE_LENGTH+1 );
assert( composite[1].size() == SIEVE_LENGTH+1 );
// Used for various stats
long s_tests = 0;
auto s_start_t = high_resolution_clock::now();
long s_total_unknown = 0;
long s_t_unk_prev = 0;
long s_t_unk_next = 0;
long s_large_primes_tested = 0;
uint64_t last_mi = M_inc - 1;
for (; last_mi > 0 && gcd(M_start + last_mi, D) > 1; last_mi -= 1);
assert(last_mi >= 0 && last_mi < M_inc);
assert(gcd(M_start + last_mi, D) == 1);
for (uint64_t mi = 0; mi < M_inc; mi++) {
const uint64_t m = M_start + mi;
if (gcd(m, D) > 1) {
assert( large_prime_queue[mi].empty() );
continue;
}
// Reset sieve array to unknown.
std::fill_n(composite[0].begin(), SIEVE_LENGTH+1, 0);
std::fill_n(composite[1].begin(), SIEVE_LENGTH+1, 0);
// center is always composite.
composite[0][0] = composite[1][0] = 1;
// For small primes that we don't do trick things with.
for (const auto& pr : prime_and_remainder) {
const uint64_t modulo = (pr.second * m) % pr.first;
// const auto& [prime, remainder] = prime_and_remainder[pi];
// const uint64_t modulo = (remainder * m) % prime;
for (size_t x = modulo; x <= SIEVE_LENGTH; x += pr.first) {
composite[0][x] = true;
}
// Not technically correct but fine to skip modulo == 0
int first_negative = pr.first - modulo;
assert(first_negative >= 0);
for (size_t x = first_negative; x <= SIEVE_LENGTH; x += pr.first) {
composite[1][x] = true;
}
}
// Maybe useful for some stats later.
// int unknown_small_l = std::count(composite[0].begin(), composite[0].end(), false);
// int unknown_small_u = std::count(composite[1].begin(), composite[1].end(), false);
for (const auto& pr : large_prime_queue[mi]) {
s_large_primes_tested += 1;
s_large_primes_rem -= 1;
const auto& prime = pr.first;
const auto& remainder = pr.second;
// Large prime should divide some number in SIEVE for this m
// When done find next mi where prime divides a number in SIEVE.
const uint64_t modulo = (remainder * m) % prime;
#ifdef GMP_VALIDATE_FACTORS
mpz_mul_ui(test, K, m);
assert(modulo == mpz_fdiv_ui(test, prime));
#endif // GMP_VALIDATE_FACTORS
if (modulo <= SIEVE_LENGTH) {
// Just past a multiple
composite[0][modulo] = true;
} else {
// Don't have to deal with 0 case anymore.
int64_t first_positive = prime - modulo;
assert(first_positive <= SIEVE_LENGTH); // Bad next m!
// Just before a multiple
composite[1][first_positive] = true;
}
// Find next mi where primes divides part of SIEVE
{
uint64_t start = mi + 1;
uint64_t next_mi = start + modulo_search_euclid_gcd(
M_start + start, D, M_inc - start, SL, prime, remainder);
if (next_mi == M_inc) continue;
// (M_start + mi) * prime < int64 (checked in argparse)
uint64_t mult = (remainder * (M_start + next_mi) + SL) % prime;
assert(mult < (2 * SL + 1));
//assert ( gcd(M_start + next_mi, D) == 1 );
large_prime_queue[next_mi].push_back(pr);
s_large_primes_rem += 1;
}
}
large_prime_queue[mi].clear();
large_prime_queue[mi].shrink_to_fit();
s_tests += 1;
int unknown_p = std::count(composite[0].begin(), composite[0].end(), false);
int unknown_n = std::count(composite[1].begin(), composite[1].end(), false);
s_total_unknown += unknown_p + unknown_n;
s_t_unk_prev += unknown_p;
s_t_unk_next += unknown_n;
// Save unknowns
if (config.save_unknowns) {
save_unknowns_method1(
unknown_file,
m, unknown_p, unknown_n,
SL, composite
);
}
bool is_last = (mi == last_mi);
if ((config.verbose + is_last >= 1) &&
((s_tests == 1 || s_tests == 10 || s_tests == 100 || s_tests == 500 || s_tests == 1000) ||
(s_tests % 5000 == 0) || is_last) ) {
auto s_stop_t = high_resolution_clock::now();
double secs = duration<double>(s_stop_t - s_start_t).count();
double t_secs = duration<double>(s_stop_t - s_setup_t).count();
printf("\t%ld %4d <- unknowns -> %-4d\n", m, unknown_p, unknown_n);
if (config.verbose + is_last >= 1) {
// Stats!
printf("\t intervals %-10ld (%.2f/sec, with setup per m: %.2g) %.0f seconds elapsed\n",
s_tests, s_tests / secs, t_secs / s_tests, secs);
printf("\t unknowns %-10ld (avg: %.2f), %.2f%% composite %.2f <- %% -> %.2f%%\n",
s_total_unknown, s_total_unknown / ((double) s_tests),
100.0 * (1 - s_total_unknown / ((2.0 * SIEVE_LENGTH + 1) * s_tests)),
100.0 * s_t_unk_prev / s_total_unknown,
100.0 * s_t_unk_next / s_total_unknown);
printf("\t large prime remaining: %d (avg/test: %ld)\n",
s_large_primes_rem, s_large_primes_tested / s_tests);
}
}
}
{
double primes_per_m = s_large_primes_tested / s_tests;
double error_percent = 100.0 * fabs(expected_primes_per - primes_per_m) /
expected_primes_per;
if (config.verbose >= 2 || error_percent > 0.5 ) {
printf("\n");
printf("Estimated primes/m error %.2f%%,\t%.1f vs expected %.1f\n",
error_percent, primes_per_m, expected_primes_per);
}
}
if (config.save_unknowns) {
auto s_stop_t = high_resolution_clock::now();
double secs = duration<double>(s_stop_t - s_setup_t).count();
insert_range_db(config, s_tests, secs);
}
// Should be cleaning up after self.
for(uint32_t mi = 0; mi < M_inc; mi++) {
assert( large_prime_queue[mi].empty() );
}
// ----- cleanup
delete[] large_prime_queue;
mpz_clear(K);
mpz_clear(test);
}
// Method 2
bool g_control_c = false;
void signal_callback_handler(int) {
if (g_control_c) {
cout << "Caught 2nd CTRL+C stopping now." << endl;
exit(2);
} else {
cout << "Caught CTRL+C stopping and saving after next interval " << endl;
g_control_c = true;
}
}
class method2_stats {
public:
method2_stats() {};
method2_stats(
int thread_i,
const struct Config& config,
size_t valid_ms,
uint64_t threshold,
double initial_prob_prime
) {
thread = thread_i;
start_t = high_resolution_clock::now();
interval_t = high_resolution_clock::now();
total_unknowns = (2 * config.sieve_length + 1) * valid_ms;
if (threshold <= 100000)
next_mult = 10000;
prob_prime = initial_prob_prime;
current_prob_prime = prob_prime;
}
// Some prints only happen if thread == 0
int thread = 0;
uint64_t next_print = 0;
uint64_t next_mult = 100000;
// global and interval start times
high_resolution_clock::time_point start_t;
high_resolution_clock::time_point interval_t;
long total_unknowns = 0;
long small_prime_factors_interval = 0;
long large_prime_factors_interval = 0;
// Sum of above two, mostly handled in method2_increment_print
long prime_factors = 0;
size_t pi = 0;
size_t pi_interval = 0;
uint64_t m_stops = 0;
uint64_t m_stops_interval = 0;
uint64_t validated_factors = 0;
// prob prime after sieve up to some prime threshold
double current_prob_prime = 0;
// Constants (more of a stats storage)
double prp_time_estimate = std::nan("");
double prob_prime = 0;
uint64_t last_prime = 0;
size_t count_coprime_p = 0;
};
void method2_increment_print(
uint64_t prime,
size_t valid_ms,
vector<bool> *composite,
method2_stats &stats,
const struct Config& config) {
/**
* verification requires count_coprime_to_P#
* Require that first call (next_print = 0) processes all primes up to P
*/
if (stats.next_print == 0 && stats.count_coprime_p == 0) {
assert(prime == config.p);
if (stats.thread == 0) {
// Other threads don't print details
if (config.threads > 1 && config.verbose) {
printf("\nWARNING stats aren't synchronized when "
"running with multiple threads(%d)\n\n", config.threads);
}
// This sligtly duplicates work below, but we don't care.
auto temp = high_resolution_clock::now();
for (size_t i = 0; i < valid_ms; i++) {
stats.count_coprime_p += std::count(composite[i].begin(), composite[i].end(), false);
}
double interval_count_time = duration<double>(high_resolution_clock::now() - temp).count();
if (config.verbose >= 2) {
printf("\t\t counting unknowns takes ~%.1f seconds\n", interval_count_time);
}
}
}
while (prime >= stats.next_print && stats.next_print < stats.last_prime) {
//printf("\t\tmethod2_increment_print %'ld >= %'ld\n", prime, stats.next_print);
const size_t max_mult = 100'000'000'000L * (config.threads > 2 ? 10L : 1L);
// 10, 20, 30, 40, 50, 100, 200, 300, 400, 500, 1000 ...
// 60, 70, 80, 90, 100, 120, 150, 200, 300 billion because intervals are wider.
size_t extra_multiples = prime > ((config.threads > 4) ? 100'000'000 : 1'000'000);
// With lots of threads small intervals are very fast
// and large % of time is spent counting unknowns
// Next time to increment the interval size
size_t next_next_mult = (5 + 10 * extra_multiples) * stats.next_mult;
if (stats.next_mult < max_mult && stats.next_print == next_next_mult) {
stats.next_mult *= 10;
stats.next_print = 0;
}
// 1,2,3,4,5,6,7,8,9,10, SKIP to 12, SKIP to 15
stats.next_print += stats.next_mult;
assert(stats.next_print % stats.next_mult == 0);
if (stats.next_mult < max_mult) {
int64_t ratio = stats.next_print / stats.next_mult;
assert(ratio >= 1 && ratio <= 14);
if (ratio > 10 && ratio < 12) { // Skip 11 => 12
stats.next_print = 12 * stats.next_mult;
} else if (ratio > 12) { // Skip 13, 14 => 15
stats.next_print = 15 * stats.next_mult;
}
}
// Never set next_print beyond last_prime
stats.next_print = std::min(stats.next_print, stats.last_prime);
}
bool is_last = (prime == stats.last_prime) || g_control_c;
if (config.verbose + is_last >= 1) {
auto s_stop_t = high_resolution_clock::now();
// total time, interval time
double secs = duration<double>(s_stop_t - stats.start_t).count();
double int_secs = duration<double>(s_stop_t - stats.interval_t).count();
uint32_t SIEVE_INTERVAL = 2 * config.sieve_length + 1;
if (stats.thread >= 1) {
printf("Thread %d\t", stats.thread);
}
stats.pi += stats.pi_interval;
printf("%'-10ld (primes %'ld/%ld)\t(seconds: %.2f/%-.1f | per m: %.3g)",
prime,
stats.pi_interval, stats.pi,
int_secs, secs,
secs / valid_ms);
if (int_secs > 240) {
// Add " @ HH:MM:SS" so that it is easier to predict when the next print will happen
time_t rawtime = std::time(nullptr);
struct tm *tm = localtime( &rawtime );
printf(" @ %d:%02d:%02d", tm->tm_hour, tm->tm_min, tm->tm_sec);
}
printf("\n");
stats.interval_t = s_stop_t;
int verbose = config.verbose + (2 * is_last) + (prime > 1e9) + (stats.thread == 0);
if (verbose >= 3) {
stats.prime_factors += stats.small_prime_factors_interval;
stats.prime_factors += stats.large_prime_factors_interval;
stats.m_stops += stats.m_stops_interval;
printf("\tfactors %'14ld \t"
"(interval: %'ld avg m/large_prime interval: %.1f)\n",
stats.prime_factors,
stats.small_prime_factors_interval + stats.large_prime_factors_interval,
1.0 * stats.m_stops_interval / stats.pi_interval);
// See THEORY.md
double prob_prime_after_sieve = stats.prob_prime * log(prime) * exp(GAMMA);
double delta_sieve_prob = (1/stats.current_prob_prime - 1/prob_prime_after_sieve);
double skipped_prp = 2 * valid_ms * delta_sieve_prob;
if (is_last || config.threads <= 1) {
uint64_t t_total_unknowns = 0;
for (size_t i = 0; i < valid_ms; i++) {
t_total_unknowns += std::count(composite[i].begin(), composite[i].end(), false);
}
uint64_t new_composites = stats.total_unknowns - t_total_unknowns;
// count_coprime_sieve * valid_ms also makes sense but leads to smaller numbers
printf("\tunknowns %'9ld/%-5ld\t"
"(avg/m: %.2f) (composite: %.2f%% +%.3f%% +%'ld)\n",
t_total_unknowns, valid_ms,
1.0 * t_total_unknowns / valid_ms,
100.0 - 100.0 * t_total_unknowns / (SIEVE_INTERVAL * valid_ms),
100.0 * new_composites / (SIEVE_INTERVAL * valid_ms),
new_composites);
if (stats.count_coprime_p && prime > 100000 && prime > config.p) {
// verify total unknowns & interval unknowns
const double prob_prime_coprime_P = prob_prime_coprime(config);
float e_unknowns = stats.count_coprime_p * (prob_prime_coprime_P / prob_prime_after_sieve);
float delta_composite_rate = delta_sieve_prob * prob_prime_coprime_P;
float e_new_composites = stats.count_coprime_p * delta_composite_rate;
float error = 100.0 * fabs(e_unknowns - t_total_unknowns) / e_unknowns;
float interval_error = 100.0 * fabs(e_new_composites - new_composites) / e_new_composites;
if (config.verbose >= 3 || error > 0.1 ) {
printf("\tEstimated %.3g unknowns found %.3g (%.2f%% error)\n",
e_unknowns, 1.0f * t_total_unknowns, error);
}
if (config.verbose >= 3 || interval_error > 0.3 ) {
printf("\tEstimated %.3g new composites found %.3g (%.2f%% error)\n",
e_new_composites, 1.0f * new_composites, interval_error);
}
}
stats.total_unknowns = t_total_unknowns;
}
stats.current_prob_prime = prob_prime_after_sieve;
double prp_rate = skipped_prp / (int_secs * config.threads);
if (config.show_timing) {
printf("\t~ 2x %.2f PRP/m\t\t"
"(~ %4.1f skipped PRP => %.1f PRP/%s)\n",
1 / stats.current_prob_prime, skipped_prp,
prp_rate,
config.threads > 1 ? "thread-seconds" : "seconds");
}
if (stats.validated_factors) {
printf("\tValidated %ld factors\n", stats.validated_factors);
}
double run_prp_mult = stats.prp_time_estimate / prp_rate;
if (run_prp_mult > 0.25 && config.show_timing) {
printf("\t\tEstimated ~%.1fx faster to just run PRP now (CTRL+C to stop sieving)\n",
run_prp_mult);