-
Notifications
You must be signed in to change notification settings - Fork 9
/
PrimeNumber.cpp
executable file
·2486 lines (2158 loc) · 72.1 KB
/
PrimeNumber.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
/*Fast Single-thread segmented sieve of Eratosthenes prime number n < 2^64 ***/
////http://ntheory.org/sieves/benchmarks.html
static const char* Benchmark =
"g++ -DFDIV -march=native -funroll-loops -O2 -s -pipe PrimeNumber.cpp -o prime\n"
"Windows 10 x64 i3-350M,i5-3470,i7-7500u,i7-6700,r7-1700,r7-5800H,i7-9700\n"
"Pi(0, 1e10) = 455052511 3.10 1.84 1.55 1.32 1.65 1.03 1.19\n"
"Pi(1e11, 1e10) = 394050419 4.35 2.50 2.02 1.78 2.00 1.31 1.50\n"
"Pi(1e12, 1e10) = 361840208 5.30 3.00 2.40 2.04 2.25 1.52 1.77\n"
"Pi(1e13, 1e10) = 334067230 6.52 3.50 2.85 2.39 2.67 1.71 2.06\n"
"Pi(1e14, 1e10) = 310208140 7.90 4.20 3.50 2.87 3.20 2.06 2.55\n"
"Pi(1e15, 1e10) = 289531946 9.90 5.10 4.22 3.49 3.91 2.50 3.14\n"
"Pi(1e16, 1e10) = 271425366 11.7 6.10 4.81 4.12 4.73 3.11 3.75\n"
"Pi(1e17, 1e10) = 255481287 13.9 7.09 5.55 4.84 5.63 3.72 4.45\n"
"Pi(1e18, 1e10) = 241272176 17.2 8.58 6.70 5.82 6.88 4.53 5.31\n"
"Pi(1e19, 1e10) = 228568014 24.0 11.6 9.57 8.00 9.50 6.14 7.45\n"
"Pi(0-1e9,10^9) = 22537866 8.15 4.28 3.92 3.02 3.64 2.28 2.05\n"
"Pi(1e18, 10^6) = 24280 0.65 0.46 0.34 0.48 0.60 0.27 0.35\n"
"Pi(1e18, 10^8) = 2414886 1.30 0.81 0.70 0.60 0.70 0.50 0.65\n"
"Pi(1e18, 10^9) = 24217085 3.50 1.80 1.51 1.26 1.50 0.95 1.25\n"
"Pi(0, 1e12) = 37607912018 500 270 224 200 220\n"
"Pi(1e14, 1e12) = 31016203073 790 420 354 295 320\n"
"Pi(1e16, 1e12) = 27143405794 1160 600 512 420 485\n"
"Pi(1e18, 1e12) = 24127637783 1500 760 622 520 640\n"
"Pi(1e19, 1e12) = 22857444126 1700 830 702 600 665\n";
static const char* Help = "\
[B: Benchmark (0 - 12, 0 - 40)]\n\
[D: D[T, R] dump time and result]\n\
[M: Progress of calculating (0 - 20)]\n\
[C: Cpu L1/L2 data cache size (L1:16-64, L2:256-4096)k]\n\
[S: Set the sieve size (32 - 4096)k]\n\
[L: Set sieve cache segs L(2-12)1, L(2-8)2 L(2-12)3, L(1-32)4]\n\
[I: Info of programming]\n\
[P: Print prime in [start, end]]\n\n\
Example:\n\
1e16 10^10 s2048 c321 c2562";
#include <ctype.h>
#include <math.h>
#include <memory.h>
#include <assert.h>
#include <time.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#if __x86_64__ || __amd64__ || _M_X64 || __amd64 || __x86_64
# define X86_64 1
#elif __i386__ || _M_IX86 || _X86_ || __i386
# define X86 1
#endif
#if (X86_64 || X86) && (__GNUC__ || _MSC_VER || __clang__ || __TINYC__ || __INTEL_COMPILER)
# define BIT_SCANF 1
#if X86 || _MSC_VER == 0
# define ASM_X86 1
#endif
#endif
// likely/unlikely
#if (__GNUC__ >= 4 || __clang__)
# define ELIKELY(condition) __builtin_expect(condition, 1)
# define EUNLIKELY(condition) __builtin_expect(condition, 0)
#else
# define ELIKELY(condition) condition
# define EUNLIKELY(condition) condition
#endif
#if _MSC_VER
typedef unsigned __int64 uint64;
typedef __int64 int64;
#else
typedef unsigned long long uint64;
typedef long long int64;
#endif
typedef unsigned int uint;
typedef unsigned char uchar;
typedef unsigned short ushort;
#if BIT_SCANF == 0
#define PRIME_OFFSET(mask) Lsb[mask]
typedef ushort stype;
#else
#define PRIME_OFFSET(mask) Pattern30[bitScanForward(mask)]
#if X86_64
typedef uint64 stype;
#else
typedef uint stype;
#endif
#endif
#ifndef WMH11
#define WHEEL210 210
#else
#define WHEEL210 2310
#endif
#ifndef M210 //big sieve wheel
# define WHEEL WHEEL30
# define WHEEL_DATA WheelData30
# define WHEEL_INIT WheelInit30
# define WHEEL_FIRST WheelFirst30
#else
# define WHEEL WHEEL210
# define WHEEL_DATA WheelData210
# define WHEEL_INIT WheelInit210
# define WHEEL_FIRST WheelFirst210
#endif
#ifndef __cplusplus
#define bool int
#define true 1
#define false 0
typedef struct WheelElement WheelElement;
typedef struct WheelInit WheelInit;
typedef struct SievePrime SievePrime;
typedef struct BucketInfo_ BucketInfo_;
typedef struct Stock Stock;
typedef struct Bucket_ Bucket_;
typedef struct PrimeCall PrimeCall;
#endif
#define MIN(a, b) (a < b ? a : b)
#define MAX(a, b) (a > b ? a : b)
enum ECONST
{
ERAT_SMALL = 4, //4 - 16
ERAT_MEDIUM = 6, //2 - 6
ERAT_BIG = 8, //2 - 8
#ifndef CHAR_BIT
# define CHAR_BIT 8
#endif
WHEEL30 = 30,
PRIME_PRODUCT = 210 * 11 * 13 * 17 * 19,
FIRST_INDEX = PRIME_PRODUCT / 9699690 + 7,
NEXT_MULTIPLE = 0x5A28A6, //magic number from 0x799b799b. 4 bit shrift into 3 bit
PI_65536 = 6542 + 1, //pi(2^16) + 1
MAX_SEGMENT = 8 << 10, //4Mkb
#ifndef UINT_MAX
UINT_MAX = 0-1u,
#endif
#if WHEEL210 < 2310
PWS = 48,
SP_BIT = 6, //PWS < 2^SP_BIT < 210 [6-7]
SI_BIT = 8, //SI_BIT >= SP_BIT [8 - 10]
MAX_WHEEL_GAP = 11 - 1, //max prime wheel 210 gap
#else
PWS = 480,
SP_BIT = 10, //PWS < 2^SP_BIT < 2310 [9-10]
SI_BIT = 10, //SI_BIT >= SP_BIT [8 - 10]S
MAX_WHEEL_GAP = 15 - 1, //max prime wheel 210 gap
#endif
#if (L2_DCACHE_SIZE < 256 || L2_DCACHE_SIZE > 4096)
L2_DCACHE_SIZE= 256,
#endif
#ifndef SIEVE_SIZE
SIEVE_SIZE = 4096
#endif
};
enum EBUCKET
{
UINT_PIMAX = 203280221, //= pi(2^32)
MAX_BUCKET = 5465 * 2, //= 0xffffffff / (256 * (1 << 10) * 3) + 4, 5465 (sqrtp * (8 + 2) / sieve_size + 2);
WHEEL_SIZE = 1 << 12, //= 2048 11: 16k, [10 - 13]
MEM_WHEEL = WHEEL_SIZE * sizeof(int) * 2, //=32768
MEM_BLOCK = (1 << 19) / WHEEL_SIZE, //19:4 MB
MAX_STOCK = UINT_PIMAX / WHEEL_SIZE + MAX_BUCKET + MEM_BLOCK, //=55221
MAX_POOL = UINT_PIMAX / (MEM_BLOCK * WHEEL_SIZE) + 100 //=487
};
enum EFLAG
{
PRINT_TIME = 1 << ('T' - 'A'),
SLOW_TEST = 1 << ('A' - 'A'),
SAVE_DATA = 1 << ('F' - 'A'),
PRINT_RET = 1 << ('R' - 'A')
};
enum EBITMASK
{
BIT0 = 1 << 0, BIT1 = 1 << 1,
BIT2 = 1 << 2, BIT3 = 1 << 3,
BIT4 = 1 << 4, BIT5 = 1 << 5,
BIT6 = 1 << 6, BIT7 = 1 << 7
};
struct Threshold_
{
uint L1Size;
uint L2Size;
uint L1Maxp;
uint L1Index;
uint L2Maxp;
uint L2Index;
uint Medium;
uint64 BucketStart; //min bucket start
};
struct Config_
{
uint SieveSize;
uint Progress;
uint Flag;
uint L1Segs;
uint L2Segs;
uint Msegs;
uint Bsegs;
};
struct WheelElement
{
#if WHEEL210 < 2310
uchar WheelIndex;
uchar Multiple;
uchar Correct;
uchar MaskBit;
#else
ushort WheelIndex;
ushort Multiple;
ushort Correct;
uchar MaskBit;
#endif
};
/**
struct WheelFirst
{
#if WHEEL210 < 2310
uchar WheelIndex;
uchar Multiple;
uchar Correct;
#else
ushort WheelIndex;
ushort Multiple;
ushort Correct;
#endif
};**/
struct WheelInit
{
#if WHEEL210 < 2310
uchar WheelIndex;
uchar MaskBit;
#else
ushort WheelIndex;
uchar MaskBit;
#endif
};
struct SievePrime
{
//[0 - 7]: sieve_index % wheel, [8 - 31]: sieve_index / WHEEL30
uint Si;
//[0 - 6]: p % wheel, [7 - 31]: p / wheel
uint Sp;
};
struct BucketInfo_
{
uint Log2Size;
uint MaxBucket;
uint LoopSize;
uint ModuloSize;
uint CurStock;
uint StockSize;
uint PoolSize;
};
struct Stock
{
SievePrime* Sprime; //read only
Stock* Next;
};
struct Bucket_
{
SievePrime* Sprime; //write only
Stock* Head; //Head->s1->s2->....->sn
};
//api start
typedef void (*callback)(void* data, const uint64 prime);
struct PrimeCall
{
void* data;
callback func;
uint64 primes;
};
#if 0
void printInfo();
void initPrime( );
//uint64 doSieve(const uint64 start, const uint64 end, PrimeCall* pcall);
uint setSieveSize(uint sieve_size);
void setCacheSegs(uint level, uint cachesegs);
void setCacheSize(uint level, uint cachecpu);
#endif
//common cache
typedef WheelElement WheelFirst;
static WheelFirst WheelFirst210[WHEEL210][PWS];
static WheelFirst WheelFirst30[WHEEL30][8];
static WheelInit WheelInit210[WHEEL210];
static WheelElement WheelData210[PWS][PWS];
static WheelInit WheelInit30[WHEEL30];
static uchar Pattern30[64];
static WheelElement WheelData30[8][8];
//presieved with prime <= 19
static uchar PreSieved[PRIME_PRODUCT / WHEEL30];
#if BIT_SCANF == 0
static uchar Lsb[1 << 16];
#endif
#if _MSC_VER >= 1400
# include <intrin.h>
#endif
#if POPCNT == 0
//number of bits 1 binary representation table in Range[0-2^16)
static uchar WordNumBit1[1 << 16];
#if (__GNUC__ || __clang__) && (X86 || X86_64)
# include <popcntintrin.h>
#endif
#endif
////////////////thread/task data //////////////////////////////
/**********************************
stock pool for big sieve
bucket.array[n]
|----
|3|.|---- ----------------
|2|2| | |---> |s1->s2->...->sn|---> wheel.array(4k size)
|1|1|.|n| ----------------
--------- stock.list
b1.b2.bn
*******************************/
static BucketInfo_ BucketInfo;
static Stock* StockHead;
static Stock StockCache [MAX_STOCK];
//big/bucket wheel pool
static Bucket_ Bucket [MAX_BUCKET];
static SievePrime* WheelPool [MAX_POOL];
//medium prime
typedef struct SievePrime MediumSieve;
static MediumSieve* MediumPrime;
//small cache
static SievePrime SmallPrime[PI_65536];
//config
static struct Threshold_ Threshold =
{
32 << 10, L2_DCACHE_SIZE << 10,
(32 << 10) / ERAT_SMALL, 0,
(L2_DCACHE_SIZE << 10) / ERAT_MEDIUM, 0,
SIEVE_SIZE * (WHEEL30 << 10) / ERAT_BIG,
100000000,
};
static struct Config_ Config =
{
SIEVE_SIZE << 10,
(1 << 6) - 1,
PRINT_RET | PRINT_TIME,
ERAT_SMALL,
ERAT_MEDIUM,
ERAT_BIG,
1 << 3,
};
////////////////basic func //////////////////////////////
//the simple sieve of Eratosthenes p < 2^16
static int eratoSimple()
{
int primes = 1;
const uint maxp = (1 << 16) + 1;
uchar bitarray[maxp >> 4] = {0};
for (uint p = 3; p < maxp; p += 2) {
if (0 == (bitarray[p >> 4] & (1 << (p / 2 & 7)))) {
SmallPrime[primes ++].Sp = p;
for (uint j = p * p; j <= maxp; j += p * 2)
bitarray[j >> 4] |= 1 << (j / 2 & 7);
}
}
SmallPrime[primes ++].Sp = maxp;
return primes;
}
//The first presieved template, cross off the first 8th prime multiples
static void initBitTable()
{
uint i = 0;
#if POPCNT == 0
const uint nbitsize = sizeof(WordNumBit1) / sizeof (WordNumBit1[0]);
for (i = 1; i < nbitsize; i ++)
WordNumBit1[i] = WordNumBit1[i >> 1] + (i & 1);
#endif
const uchar pattern[] = {1, 7, 11, 13, 17, 19, 23, 29};
for (i = 0; i < sizeof(Pattern30) / sizeof (Pattern30[0]); i ++)
Pattern30[i] = pattern[i % 8] + WHEEL30 * (i / 8);
#if BIT_SCANF == 0
const uint nbitsize2 = sizeof(Lsb) / sizeof(Lsb[0]);
for (i = 0; i < nbitsize2; i += 2)
Lsb[i + 0] = Lsb[i >> 1] + 1;
for (i = 0; i < nbitsize2; i += 2) {
Lsb[i + 0] = Pattern30[Lsb[i]];
Lsb[i + 1] = 1;
}
#endif
for (int j = 0, wj = 0; j < WHEEL30; j ++) {
WheelInit30[j].MaskBit = 0;
WheelInit30[j].WheelIndex = wj;
if (j == Pattern30[wj])
WheelInit30[j].MaskBit = 1 << (wj ++);
}
for (i = 1; PRIME_PRODUCT % pattern[i] == 0; i ++) {
const int p = pattern[i];
for (uint offset = p; offset < sizeof(PreSieved) * WHEEL30; offset += p * 2)
PreSieved[offset / WHEEL30] |= WheelInit30[offset % WHEEL30].MaskBit;
}
}
static void initWheel30()
{
//how to calculate the magic number ?
const uint nextMultiple[8] =
{
0x74561230, 0x67325401,
0x51734062, 0x42170653,
0x35607124, 0x26043715,
0x10452376, 0x03216547
};
const int psize = 8;
for (int i = 0; i < WHEEL30; i ++) {
for (int pi = 0; pi < psize; pi ++) {
int multiples = 1 - (i % 2);
int next = i + multiples * Pattern30[pi];
while (WheelInit30[next % WHEEL30].MaskBit == 0)
next = i + Pattern30[pi] * (multiples += 2);
int wi = WheelInit30[next % WHEEL30].WheelIndex;
WheelFirst* wf = &WheelFirst30[i][pi];
wf->WheelIndex = wi;
wf->Multiple = (nextMultiple[wi] >> (pi * 4)) & 15;
wf->Correct = multiples;
}
}
for (int wi = 0; wi < psize; wi ++) {
for (int pi = 0; pi < psize; pi ++) {
int multiples = 2;
int next = Pattern30[wi] + Pattern30[pi] * multiples;
while (WheelInit30[next % WHEEL30].MaskBit == 0)
next = Pattern30[wi] + Pattern30[pi] * (multiples += 2);
WheelElement* we30 = &WheelData30[pi][wi];
we30->WheelIndex = WheelInit30[next % WHEEL30].WheelIndex;
we30->Multiple = multiples;
we30->Correct = next / WHEEL30 - Pattern30[wi] / WHEEL30;
we30->MaskBit = 1 << wi;
}
}
}
static void initWheel210()
{
int wi = 0, i = 0;
const int psize = PWS;
uint wpattern[PWS];
#if WHEEL210 < 2310
const ushort pattern[] = {3, 5, 7, 2311};
#else
const ushort pattern[] = {3, 5, 7, 11, 2311};
#endif
for (int j = 1; j < WHEEL210; j += 2) {
WheelInit210[j - 1].WheelIndex = WheelInit210[j].WheelIndex = wi;
int i = 0;
while (i < sizeof(pattern) / sizeof(pattern[0]) && j % pattern[i] != 0)
i++;
if (i == sizeof(pattern) / sizeof(pattern[0]))
wpattern[wi++] = j;
}
for (i = 0; i < WHEEL210; i ++) {
for (int pi = 0; pi < psize; pi ++) {
int multiples = 1 - (i % 2);
uint next = i + wpattern[pi] * multiples;
WheelFirst* wf = &WheelFirst210[i][pi];
while (WheelInit210[next % WHEEL210].WheelIndex == WheelInit210[(next + 1) % WHEEL210].WheelIndex)
next = i + wpattern[pi] * (multiples += 2);
wf->WheelIndex = WheelInit210[next % WHEEL210].WheelIndex;
wf->Correct = multiples;
assert(multiples < MAX_WHEEL_GAP);
}
}
for (int pi = 0; pi < psize; pi ++) {
for (wi = 0; wi < psize; wi ++) {
int multiples = 2;
uint next = wpattern[wi] + wpattern[pi] * 2;
while (WheelInit210[next % WHEEL210].WheelIndex == WheelInit210[(next + 1) % WHEEL210].WheelIndex) {
next += wpattern[pi] * 2;
multiples += 2;
}
assert(multiples <= MAX_WHEEL_GAP);
WheelElement* we210 = &WheelData210[pi][wi];
we210->Correct = next / WHEEL30 - wpattern[wi] / WHEEL30;
we210->MaskBit = WheelInit30[wpattern[wi] % WHEEL30].MaskBit;
we210->WheelIndex = WheelInit210[next % WHEEL210].WheelIndex;
we210->Multiple = multiples * (WHEEL210 / WHEEL30);
}
}
}
#if __linux__ || __unix__
#include <sys/resource.h>
#elif _WIN32
#include <windows.h>
#endif
static int64 getTime()
{
#ifdef _WIN32
FILETIME ptime[4] = {0};
GetThreadTimes(GetCurrentThread(), &ptime[0], &ptime[1], &ptime[2], &ptime[3]);
return (ptime[2].dwLowDateTime + ptime[3].dwLowDateTime) / 10000;
#elif __linux__ || __unix__
struct rusage rup;
getrusage(RUSAGE_SELF, &rup);
uint64 sec = rup.ru_utime.tv_sec + rup.ru_stime.tv_sec;
uint64 usec = rup.ru_utime.tv_usec + rup.ru_stime.tv_usec;
return sec * 1000 + usec / 1000;
#elif _WIN32
return clock();
#else
return clock() / 1000;
#endif
}
//n > 1
static int ilog(uint64 x, const uint n)
{
int logn = 0;
while (x / n) {
logn ++;
x /= n;
}
return logn;
}
//x^n < 2^64, n < 64
static uint64 mpow(const uint x, uint n)
{
uint64 pown = 1;
while (n --)
pown *= x;
return pown;
}
//x > 1
static uint isqrt(const uint64 x)
{
const uint s = ilog(x - 1, 2);
uint64 g0 = (uint64)1 << s;
uint64 g1 = (g0 + (x >> s)) >> 1;
while (g1 < g0) {
g0 = g1;
g1 = (g1 + x / g1) >> 1;
}
return (uint)g0;
}
#if BIT_SCANF
inline static uint bitScanForward(const stype n)
{
#if _WIN32
unsigned long index;
#if _WIN64
_BitScanForward64(&index, n);
#else
_BitScanForward(&index, n);
#endif
#elif __GNUC__ || __clang__
#if X86_64
// uint index = __builtin_ffsll(n) - 1;
uint index = __builtin_ctzll(n);
#else
uint index = __builtin_ctzl(n);
#endif
#elif ASM_X86
stype index;
#if X86_64
#if __GNUC__ || __TINYC__ || __clang__
__asm__ ("bsfq %1, %0\n" : "=r" (index) : "rm" (n) : "cc");
#else
__asm
{
bsfq eax, n
mov index, eax
}
#endif
#else
#if __GNUC__ || __TINYC__ || __clang__
__asm__ ("bsfl %1, %0\n" : "=r" (index) : "rm" (n) : "cc");
#else
__asm
{
bsf eax, n
mov index, eax
}
#endif
#endif
#endif
return (uint)index;
}
#endif
//(n / p) < 2^32 is more efficient
inline static uint fastllDiv(const uint64 n, uint p)
{
#if ASM_X86 == 0
p = (uint)(n % p);
#elif __GNUC__ || __TINYC__ || __clang__
const uint loww = (uint)n, higw = (uint)(n >> 32);
__asm__ ( "divl %%ecx\n" : "=d" (p) : "d"(higw), "a"(loww), "c"(p));
#else
const uint loww = (uint)n, higw = (uint)(n >> 32);
__asm
{
mov eax, loww
mov edx, higw
div p
mov p, edx
}
#endif
return p;
}
//valid is [number][e][+-*^][number]
//ex: 1000, 2e9, 300-2e1, 2^32*2-e5 2^30-1E2, 2e9+2^20
static uint64 atoint64(const char* str)
{
uint64 ret = 0;
while (isdigit(*str))
ret = ret * 10 + *str ++ - '0';
if (*str && isdigit(str[1])) {
if (str[0] == '^') {
ret = mpow((uint)ret, atoi(str + 1));
} else if (str[0] == 'e' || str[0] == 'E') {
if (ret == 0)
ret = 1;
ret *= mpow(10, atoi(str + 1));
}
}
const char* ps = str;
if ((ps = strchr(str, '+')) != NULL) {
ret += atoint64(ps + 1);
} else if ((ps = strchr(str, '-')) != NULL) {
ret -= atoint64(ps + 1);
} else if ((ps = strchr(str, '*')) != NULL) {
ret *= atoi(ps + 1);
} else if ((ps = strchr(str, '/')) != NULL) {
ret /= atoi(ps + 1);
}
return ret;
}
//count number of bit 0 in binary representation of array, bytes % 8 = 0
static uint countBit0sArray(uint64 bitarray[], const uint bytes)
{
uint bit1s = 0, bit2s = 0;
uint loops = bytes / sizeof(uint64);
while (loops -- > 0) {
const uint64 qw = *bitarray++;
#if (__GNUC__ || __clang__ ) && X86_64
bit2s += _mm_popcnt_u64(qw);
#elif POPCNT
bit2s += __builtin_popcountll(qw);
#else
const uint hig = (uint)(qw >> 32);
const uint low = (uint)(qw);
//if (sizeof(uint64) != sizeof(uint)) //uint64 == uint ?
bit1s += WordNumBit1[(ushort)hig] + WordNumBit1[hig >> 16];
bit2s += WordNumBit1[(ushort)low] + WordNumBit1[low >> 16];
#endif
}
return bytes * CHAR_BIT - bit1s - bit2s;
}
//////////////////////// core code //////////////////////////////////
static void allocWheelBlock(const uint blocks)
{
#if 0
SievePrime *pSprime = (SievePrime*)_aligned_malloc(MEM_BLOCK * MEM_WHEEL, MEM_WHEEL);
WheelPool[BucketInfo.PoolSize ++] = pSprime;
#else
SievePrime *pSprime = (SievePrime*)malloc((MEM_BLOCK + 1) * MEM_WHEEL);
WheelPool[BucketInfo.PoolSize++] = pSprime;
pSprime = (SievePrime*)((size_t)pSprime + MEM_WHEEL - (size_t)pSprime % MEM_WHEEL);
#endif
//assert (BucketInfo.PoolSize < sizeof(WheelPool) / sizeof(WheelPool[0]));
//assert (BucketInfo.StockSize + blocks < sizeof(StockCache) / sizeof(StockCache[0]));
Stock* pStock = StockCache + BucketInfo.StockSize;
for (uint i = 0; i < MEM_BLOCK; i ++) {
pStock->Sprime = pSprime + WHEEL_SIZE * i;
pStock->Next = pStock + 1;
pStock ++;
}
pStock[-1].Next = StockHead;
StockHead = pStock - MEM_BLOCK;
BucketInfo.StockSize += MEM_BLOCK;
BucketInfo.CurStock += MEM_BLOCK;
}
#define PI(x, r) x / log((double)x) * (1 + r / log((double)x))
static int setBucketInfo(const uint sieve_size, const uint sqrtp, const uint64 range)
{
//assert (range >> 32 < sieve_size);
BucketInfo.MaxBucket = range / sieve_size + 1;//overflow for big range
BucketInfo.LoopSize = sqrtp / (sieve_size / MAX_WHEEL_GAP) + 2; //add the first, last bucket
BucketInfo.Log2Size = ilog(sieve_size / WHEEL30, 2);
BucketInfo.ModuloSize = (1 << BucketInfo.Log2Size) - 1;
assert (BucketInfo.Log2Size <= (32 - SI_BIT) && SI_BIT >= SP_BIT);
return 0;
}
static void initSmallWheel(const uint64 start, const uint maxp)
{
const uint segsize = Threshold.L1Size * WHEEL30;
uint64 offset = start - start % WHEEL210;
for (uint p = SmallPrime[FIRST_INDEX].Sp, j = FIRST_INDEX; p < maxp; p = SmallPrime[++j].Sp) {
const uint64 p2 = (uint64)p * p;
if (p2 > offset && p2 > offset + segsize) //overflow
offset += (p2 - offset) / segsize * segsize;
uint sieve_index = p - (uint)(offset % p);
if (p2 > offset)
sieve_index = (uint)(p2 - offset);
const int pi = WheelInit30[p % WHEEL30].WheelIndex;
const WheelFirst& wf = WheelFirst30[sieve_index % WHEEL30][pi];
sieve_index += wf.Correct * p;
#ifndef SM0
SmallPrime[j].Si = 0-((sieve_index << 4) | wf.Multiple);
#else
SmallPrime[j].Si = (sieve_index << 4) | wf.Multiple;
#endif
}
}
static int segmentedSieve2(uchar bitarray[], const uint start, const uint sieve_size, bool bcopy);
static void initMediumWheel(uchar* bitarray, const uint sieve_size, const uint medium, const uint64 start)
{
uint j = Threshold.L1Index, l1_maxp = Threshold.L1Maxp - Threshold.L1Maxp % WHEEL210;
Threshold.L2Index = 0;
uint segsize = MIN(sieve_size, Threshold.L2Size * WHEEL30);
const int bytes = segmentedSieve2(bitarray, l1_maxp, medium - l1_maxp, false);
stype mask = 0, *sbitarray = (stype*)bitarray;
uint noffset = l1_maxp - sizeof(mask) * WHEEL30;
const uint pn = 1 + bytes / sizeof(mask);
for (uint i = 0; i < pn; ) {
if (EUNLIKELY(mask == 0)) {
mask = ~sbitarray[i ++];
noffset += sizeof(mask) * WHEEL30;
continue;
}
const uint p = noffset + PRIME_OFFSET(mask); mask &= mask - 1;
if (EUNLIKELY(Threshold.L2Index == 0 && p >= Threshold.L2Maxp)) {
MediumPrime[j + 0].Sp = MediumPrime[j + 1].Sp = UINT_MAX;
Threshold.L2Maxp = p;
Threshold.L2Index = j += 2;
segsize = sieve_size;
}
uint64 offset = start;
const uint64 p2 = (uint64)p * p;
if (EUNLIKELY(p2 > offset && p2 >= offset + segsize)) //overflow
offset += (p2 - offset) / segsize * segsize;
uint sieve_index = p - (uint)(offset % p);
if (EUNLIKELY(p2 > offset))
sieve_index = (uint)(p2 - offset);
if (Threshold.L2Index == 0) {
const int pi = WheelInit30[p % WHEEL30].WheelIndex;
const WheelFirst& wf = WheelFirst30[sieve_index % WHEEL30][pi];
sieve_index += wf.Correct * p;
#ifdef SL2
MediumPrime[j + 0].Sp = p;
#ifndef SM0
MediumPrime[j++].Si = 0-((sieve_index << 4) + wf.Multiple);
#else
MediumPrime[j++].Si = (sieve_index << 4) + wf.Multiple;
#endif
#else
MediumPrime[j + 0].Sp = (p / WHEEL30 << SI_BIT) + pi;
MediumPrime[j ++ ].Si = (sieve_index / WHEEL30 << SI_BIT) + wf.WheelIndex;
#ifdef SM0
MediumPrime[j - 1].Si = -MediumPrime[j - 1].Si;
#endif
#endif
} else {
const int pi = WHEEL_INIT[p % WHEEL].WheelIndex;
const WheelFirst& wf = WHEEL_FIRST[(sieve_index + (uint)(offset % WHEEL)) % WHEEL][pi];
sieve_index += wf.Correct * p;
MediumPrime[j + 0].Sp = (p / WHEEL << SI_BIT) + pi;
MediumPrime[j ++ ].Si = (sieve_index / WHEEL30 << SI_BIT) + wf.WheelIndex;
}
}
MediumPrime[j + 0].Sp = MediumPrime[j + 1].Sp = UINT_MAX;
}
inline static void pushBucket(const uint offset, const uint sp, const ushort wi)
{
const uint next_bucket = offset >> BucketInfo.Log2Size;
#ifndef B_R
if (next_bucket >= BucketInfo.MaxBucket)
return;
#endif
SievePrime* pSprime = Bucket[next_bucket].Sprime ++;
if (EUNLIKELY((size_t)(pSprime) % MEM_WHEEL == 0)) {
Bucket_* pbucket = Bucket + next_bucket;
#ifndef P_B
if (EUNLIKELY(BucketInfo.CurStock -- == 0)) allocWheelBlock(1);
#else
BucketInfo.CurStock --;
#endif
//pop from free stock list
Stock* psfree = StockHead; StockHead = psfree->Next;
psfree->Next = pbucket->Head;
pbucket->Head = psfree;
pbucket->Sprime = (pSprime = psfree->Sprime) + 1;
}
// *(uint64*)pSprime = ((uint64)sp << 32) | (offset & BucketInfo.ModuloSize) << SI_BIT | wi;
pSprime->Sp = sp;
pSprime->Si = (offset & BucketInfo.ModuloSize) << SI_BIT | wi;
}
static void initBigWheel(uchar* bitarray, uint medium, uint sqrtp, const uint64 start, const uint64 range)
{
uint nextp = 0; uint64 remp = 0;
if (ELIKELY(sqrtp < UINT_MAX)) sqrtp ++; //watch overflow if sqrtp = 2^32 - 1
const uint irange = (uint)((range >> 32) > WHEEL30 ? UINT_MAX : range / WHEEL30);
for (uint l2_size = L2_DCACHE_SIZE * WHEEL30 << 10; medium < sqrtp; medium += l2_size) {
if (l2_size > sqrtp - medium)
l2_size = sqrtp - medium;
const int bytes = segmentedSieve2(bitarray, medium, l2_size, nextp > 0);
stype mask = 0, *sbitarray = (stype*)bitarray; //little endian
uint offset = medium - sizeof(mask) * WHEEL30;
const uint pn = 1 + bytes / sizeof(mask);
for (uint j = 0; j < pn; ) {
if (EUNLIKELY(mask == 0)) {
mask = ~sbitarray[j ++];
offset += sizeof(mask) * WHEEL30;
continue;
}
const uint p = offset + PRIME_OFFSET(mask); mask &= mask - 1;
#ifdef FDIV
if (EUNLIKELY (p > nextp)) { //ugly & difficult to understand but efficient
remp = start / (nextp = p + (uint64)p * p / (uint)(start >> 32));
if (EUNLIKELY(p > nextp)) //overflow
remp = start >> 32, nextp = UINT_MAX;
}
uint sieve_index = p - fastllDiv(start - remp * p, p);
#else
uint sieve_index = p - (uint)(start % p);
#endif
#ifndef P_C
if (EUNLIKELY(sieve_index > range)) continue;
#endif
const uint sp = (p / WHEEL210 << SP_BIT) + WheelInit210[p % WHEEL210].WheelIndex;
const uint modulo_210 = sieve_index % WHEEL210;
const WheelFirst* wf = &WheelFirst210[modulo_210][sp % (1 << SP_BIT)];
if (sizeof(int*) == sizeof(uint64))
sieve_index = (sieve_index + wf->Correct * (uint64)p) / WHEEL30;
else {
sieve_index = (sieve_index / WHEEL210 + (sp >> SP_BIT) * wf->Correct) * (WHEEL210 / WHEEL30);
sieve_index += (wf->Correct * (p % WHEEL210) + modulo_210) / WHEEL30;
}
#ifndef B_R
if (sieve_index > irange)
continue;
#endif
#ifndef P_B
pushBucket(sieve_index, sp, wf->WheelIndex);
#else
const uint next_bucket = sieve_index >> BucketInfo.Log2Size;
SievePrime* pSprime = Bucket[next_bucket].Sprime ++;
if (EUNLIKELY((size_t)(pSprime) % MEM_WHEEL == 0)) {
Bucket_* pbucket = Bucket + next_bucket;
if (EUNLIKELY(BucketInfo.CurStock -- == 0)) allocWheelBlock(1);
//pop from free stock list
Stock* psfree = StockHead; StockHead = psfree->Next;
psfree->Next = pbucket->Head;
pbucket->Head = psfree;
pbucket->Sprime = (pSprime = psfree->Sprime) + 1;
}
pSprime->Sp = sp;
pSprime->Si = (sieve_index & BucketInfo.ModuloSize) << SI_BIT | wf->WheelIndex;
#endif
}
}
}
static int crossSmall0(uchar bitarray[], const uchar* pend, const uint p, uint offset, uint multiples)
{
uchar* ppbeg[8], wi;
for (int i = 0; i < 8; i ++) {
wi = WheelInit30[offset % WHEEL30].WheelIndex;
ppbeg[wi] = bitarray + offset / WHEEL30;
offset += (multiples % 8) * p; multiples /= 8;
}
#define OR_ADD(n) *ps##n |= BIT##n, ps##n += p
uchar* ps0 = ppbeg[0], *ps1 = ppbeg[1], *ps2 = ppbeg[2], *ps3 = ppbeg[3];
uchar* ps4 = ppbeg[4], *ps5 = ppbeg[5], *ps6 = ppbeg[6], *ps7 = ppbeg[7];
uchar* pmax = ppbeg[wi] - p;
while (pmax <= pend) {
pmax += p; //05143627
OR_ADD(0); OR_ADD(5); OR_ADD(1); OR_ADD(4); OR_ADD(3); OR_ADD(6); OR_ADD(2); OR_ADD(7);
}
return (int)(pmax - ppbeg[wi]) * WHEEL30;
}
static int crossSmall1(uchar bitarray[], const uchar* pend, const uint p, uint offset, uint multiples)
{
int mini = 1 << 31;
for (int i = 0; i < 4; i ++) {
uchar* ps1 = bitarray + offset / WHEEL30;
const uchar masks1 = WheelInit30[offset % WHEEL30].MaskBit;
offset += (multiples % 8) * p; multiples /= 8;
uchar* ps2 = bitarray + offset / WHEEL30;
const uchar masks2 = WheelInit30[offset % WHEEL30].MaskBit;
offset += (multiples % 8) * p; multiples /= 8;
while (ps2 <= pend) {
*ps2 |= masks2, *ps1 |= masks1;