-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathutil.c
3581 lines (3154 loc) · 98.3 KB
/
util.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
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <float.h>
#include "ptypes.h"
#define FUNC_isqrt 1
#define FUNC_icbrt 1
#define FUNC_lcm_ui 1
#define FUNC_ctz 1
#define FUNC_log2floor 1
#define FUNC_is_perfect_square
#define FUNC_is_perfect_cube
#define FUNC_is_perfect_fifth
#define FUNC_is_perfect_seventh
#define FUNC_next_prime_in_sieve 1
#define FUNC_prev_prime_in_sieve 1
#define FUNC_ipow 1
#include "util.h"
#include "sieve.h"
#include "primality.h"
#include "cache.h"
#include "legendre_phi.h"
#include "prime_counts.h"
#include "prime_powers.h"
#include "factor.h"
#include "mulmod.h"
#include "constants.h"
#include "montmath.h"
#include "csprng.h"
#include "inverse_interpolate.h"
#include "rootmod.h"
#include "lucas_seq.h"
static int _numcmp(const void *a, const void *b) {
UV x = *(UV*)a, y = *(UV*)b;
return (x > y) - (x < y);
}
static int _snumcmp(const void *a, const void *b) {
IV x = *(IV*)a, y = *(IV*)b;
return (x > y) - (x < y);
}
void sort_uv_array(UV* L, unsigned long len)
{
(void) qsort(L, len, sizeof(UV), _numcmp);
}
void sort_iv_array(IV* L, unsigned long len)
{
(void) qsort(L, len, sizeof(IV), _snumcmp);
}
void sort_dedup_uv_array(UV* L, int data_is_signed, unsigned long *len)
{
unsigned long i, j;
if (*len > 1) {
(void) qsort(L, *len, sizeof(UV), data_is_signed ? _snumcmp : _numcmp);
for (i=0, j=1; j < *len; j++)
if (L[i] != L[j])
L[++i] = L[j];
*len = i+1;
}
}
/* Returns 0 if not found, index+1 if found (returns leftmost if dups) */
unsigned long index_in_sorted_uv_array(UV v, UV* L, unsigned long len)
{
unsigned long lo, hi;
if (len == 0 || v < L[0] || v > L[len-1])
return 0;
lo = 0;
hi = len-1;
while (lo < hi) {
unsigned long mid = lo + ((hi-lo) >> 1);
if (L[mid] < v) lo = mid + 1;
else hi = mid;
}
return (L[lo] == v) ? lo+1 : 0;
}
unsigned long index_in_sorted_iv_array(IV v, IV* L, unsigned long len)
{
unsigned long lo, hi;
if (len == 0 || v < L[0] || v > L[len-1])
return 0;
lo = 0;
hi = len-1;
while (lo < hi) {
unsigned long mid = lo + ((hi-lo) >> 1);
if (L[mid] < v) lo = mid + 1;
else hi = mid;
}
return (L[lo] == v) ? lo+1 : 0;
}
static int _verbose = 0;
void _XS_set_verbose(int v) { _verbose = v; }
int _XS_get_verbose(void) { return _verbose; }
static int _call_gmp = 0;
void _XS_set_callgmp(int v) { _call_gmp = v; }
int _XS_get_callgmp(void) { return _call_gmp; }
static bool _secure = 0;
void _XS_set_secure(void) { _secure = 1; }
bool _XS_get_secure(void) { return _secure; }
/* We'll use this little static sieve to quickly answer small values of
* is_prime, next_prime, prev_prime, prime_count
* for non-threaded Perl it's basically the same as getting the primary
* cache. It guarantees we'll have an answer with no waiting on any version.
*/
static const unsigned char prime_sieve30[] =
{0x01,0x20,0x10,0x81,0x49,0x24,0xc2,0x06,0x2a,0xb0,0xe1,0x0c,0x15,0x59,0x12,
0x61,0x19,0xf3,0x2c,0x2c,0xc4,0x22,0xa6,0x5a,0x95,0x98,0x6d,0x42,0x87,0xe1,
0x59,0xa9,0xa9,0x1c,0x52,0xd2,0x21,0xd5,0xb3,0xaa,0x26,0x5c,0x0f,0x60,0xfc,
0xab,0x5e,0x07,0xd1,0x02,0xbb,0x16,0x99,0x09,0xec,0xc5,0x47,0xb3,0xd4,0xc5,
0xba,0xee,0x40,0xab,0x73,0x3e,0x85,0x4c,0x37,0x43,0x73,0xb0,0xde,0xa7,0x8e,
0x8e,0x64,0x3e,0xe8,0x10,0xab,0x69,0xe5,0xf7,0x1a,0x7c,0x73,0xb9,0x8d,0x04,
0x51,0x9a,0x6d,0x70,0xa7,0x78,0x2d,0x6d,0x27,0x7e,0x9a,0xd9,0x1c,0x5f,0xee,
0xc7,0x38,0xd9,0xc3,0x7e,0x14,0x66,0x72,0xae,0x77,0xc1,0xdb,0x0c,0xcc,0xb2,
0xa5,0x74,0xe3,0x58,0xd5,0x4b,0xa7,0xb3,0xb1,0xd9,0x09,0xe6,0x7d,0x23,0x7c,
0x3c,0xd3,0x0e,0xc7,0xfd,0x4a,0x32,0x32,0xfd,0x4d,0xb5,0x6b,0xf3,0xa8,0xb3,
0x85,0xcf,0xbc,0xf4,0x0e,0x34,0xbb,0x93,0xdb,0x07,0xe6,0xfe,0x6a,0x57,0xa3,
0x8c,0x15,0x72,0xdb,0x69,0xd4,0xaf,0x59,0xdd,0xe1,0x3b,0x2e,0xb7,0xf9,0x2b,
0xc5,0xd0,0x8b,0x63,0xf8,0x95,0xfa,0x77,0x40,0x97,0xea,0xd1,0x9f,0xaa,0x1c,
0x48,0xae,0x67,0xf7,0xeb,0x79,0xa5,0x55,0xba,0xb2,0xb6,0x8f,0xd8,0x2d,0x6c,
0x2a,0x35,0x54,0xfd,0x7c,0x9e,0xfa,0xdb,0x31,0x78,0xdd,0x3d,0x56,0x52,0xe7,
0x73,0xb2,0x87,0x2e,0x76,0xe9,0x4f,0xa8,0x38,0x9d,0x5d,0x3f,0xcb,0xdb,0xad,
0x51,0xa5,0xbf,0xcd,0x72,0xde,0xf7,0xbc,0xcb,0x49,0x2d,0x49,0x26,0xe6,0x1e,
0x9f,0x98,0xe5,0xc6,0x9f,0x2f,0xbb,0x85,0x6b,0x65,0xf6,0x77,0x7c,0x57,0x8b,
0xaa,0xef,0xd8,0x5e,0xa2,0x97,0xe1,0xdc,0x37,0xcd,0x1f,0xe6,0xfc,0xbb,0x8c,
0xb7,0x4e,0xc7,0x3c,0x19,0xd5,0xa8,0x9e,0x67,0x4a,0xe3,0xf5,0x97,0x3a,0x7e,
0x70,0x53,0xfd,0xd6,0xe5,0xb8,0x1c,0x6b,0xee,0xb1,0x9b,0xd1,0xeb,0x34,0xc2,
0x23,0xeb,0x3a,0xf9,0xef,0x16,0xd6,0x4e,0x7d,0x16,0xcf,0xb8,0x1c,0xcb,0xe6,
0x3c,0xda,0xf5,0xcf};
#define NPRIME_SIEVE30 (sizeof(prime_sieve30)/sizeof(prime_sieve30[0]))
static const unsigned short primes_tiny[] =
{0,2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,
101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,
193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,
293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,
409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503};
#define NPRIMES_TINY (sizeof(primes_tiny)/sizeof(primes_tiny[0]))
/* Return true if n is prime, false if not. Do it fast. */
bool is_prime(UV n)
{
if (n <= 10)
return (n == 2 || n == 3 || n == 5 || n == 7);
if (n < UVCONST(200000000)) {
UV d = n/30;
UV m = n - d*30;
unsigned char mtab = masktab30[m]; /* Bitmask in mod30 wheel */
/* Return 0 if a multiple of 2, 3, or 5 */
if (mtab == 0)
return 0;
/* Check static tiny sieve */
if (d < NPRIME_SIEVE30)
return ((prime_sieve30[d] & mtab) == 0);
if (!(n%7) || !(n%11) || !(n%13)) return 0;
/* Check primary cache */
if (n <= get_prime_cache(0,0)) {
const unsigned char* sieve;
int isprime = -1;
if (n <= get_prime_cache(0, &sieve))
isprime = ((sieve[d] & mtab) == 0);
release_prime_cache(sieve);
if (isprime >= 0)
return isprime;
}
}
return is_prob_prime(n);
}
UV next_prime(UV n)
{
UV m, next;
if (n < 30*NPRIME_SIEVE30) {
next = next_prime_in_sieve(prime_sieve30, n, 30*NPRIME_SIEVE30);
if (next != 0) return next;
}
if (n >= MPU_MAX_PRIME) return 0; /* Overflow */
if (n < get_prime_cache(0,0)) {
const unsigned char* sieve;
UV sieve_size = get_prime_cache(0, &sieve);
next = (n < sieve_size) ? next_prime_in_sieve(sieve, n, sieve_size) : 0;
release_prime_cache(sieve);
if (next != 0) return next;
}
m = n % 30;
do { /* Move forward one. */
n += wheeladvance30[m];
m = nextwheel30[m];
} while (!is_prob_prime(n));
return n;
}
UV prev_prime(UV n)
{
UV m, prev;
if (n < 30*NPRIME_SIEVE30)
return prev_prime_in_sieve(prime_sieve30, n);
if (n < get_prime_cache(0,0)) {
const unsigned char* sieve;
UV sieve_size = get_prime_cache(0, &sieve);
prev = (n < sieve_size) ? prev_prime_in_sieve(sieve, n) : 0;
release_prime_cache(sieve);
if (prev != 0) return prev;
}
m = n % 30;
do { /* Move back one. */
n -= wheelretreat30[m];
m = prevwheel30[m];
} while (!is_prob_prime(n));
return n;
}
/******************************************************************************/
/* PRINTING */
/******************************************************************************/
static int my_sprint(char* ptr, UV val) {
int nchars;
UV t;
char *s = ptr;
do {
t = val / 10; *s++ = (char) ('0' + val - 10 * t);
} while ((val = t));
nchars = s - ptr + 1; *s = '\n';
while (--s > ptr) { char c = *s; *s = *ptr; *ptr++ = c; }
return nchars;
}
static char* write_buf(int fd, char* buf, char* bend) {
int res = (int) write(fd, buf, bend-buf);
if (res == -1) croak("print_primes write error");
return buf;
}
void print_primes(UV low, UV high, int fd) {
char buf[8000+25];
char* bend = buf;
if ((low <= 2) && (high >= 2)) bend += my_sprint(bend,2);
if ((low <= 3) && (high >= 3)) bend += my_sprint(bend,3);
if ((low <= 5) && (high >= 5)) bend += my_sprint(bend,5);
if (low < 7) low = 7;
if (low <= high) {
unsigned char* segment;
UV seg_base, seg_low, seg_high;
void* ctx = start_segment_primes(low, high, &segment);
while (next_segment_primes(ctx, &seg_base, &seg_low, &seg_high)) {
START_DO_FOR_EACH_SIEVE_PRIME( segment, seg_base, seg_low, seg_high )
bend += my_sprint(bend,p);
if (bend-buf > 8000) { bend = write_buf(fd, buf, bend); }
END_DO_FOR_EACH_SIEVE_PRIME
}
end_segment_primes(ctx);
}
if (bend > buf) { bend = write_buf(fd, buf, bend); }
}
/******************************************************************************/
/* TOTIENT, MOEBIUS, MERTENS */
/******************************************************************************/
/* Return a char array with lo-hi+1 elements. mu[k-lo] = µ(k) for k = lo .. hi.
* It is the callers responsibility to call Safefree on the result. */
signed char* range_moebius(UV lo, UV hi)
{
signed char* mu;
UV i, sqrtn = isqrt(hi), count = hi-lo+1;
/* Kuznetsov indicates that the Deléglise & Rivat (1996) method can be
* modified to work on logs, which allows us to operate with no
* intermediate memory at all. Same time as the D&R method, less memory. */
unsigned char logp;
UV nextlog, nextlogi;
if (hi < lo) croak("range_mobius error hi %"UVuf" < lo %"UVuf"\n", hi, lo);
Newz(0, mu, count, signed char);
if (sqrtn*sqrtn != hi && sqrtn < (UVCONST(1)<<(BITS_PER_WORD/2))-1) sqrtn++;
/* For small ranges, do it by hand */
if (hi < 100 || count <= 10 || (hi > (1UL<<25) && count < icbrt(hi)/4)) {
for (i = 0; i < count; i++)
mu[i] = moebius(lo+i);
return mu;
}
logp = 1; nextlog = 3; /* 2+1 */
START_DO_FOR_EACH_PRIME(2, sqrtn) {
UV p2 = p*p;
if (p > nextlog) {
logp += 2; /* logp is 1 | ceil(log(p)/log(2)) */
nextlog = ((nextlog-1)*4)+1;
}
for (i = P_GT_LO(p, p, lo); i >= lo && i <= hi; i += p)
mu[i-lo] += logp;
for (i = P_GT_LO(p2, p2, lo); i >= lo && i <= hi; i += p2)
mu[i-lo] = 0x80;
} END_DO_FOR_EACH_PRIME
logp = log2floor(lo);
nextlogi = (UVCONST(2) << logp) - lo;
for (i = 0; i < count; i++) {
unsigned char a = mu[i];
if (i >= nextlogi) nextlogi = (UVCONST(2) << ++logp) - lo;
if (a & 0x80) { a = 0; }
else if (a >= logp) { a = 1 - 2*(a&1); }
else { a = -1 + 2*(a&1); }
mu[i] = a;
}
if (lo == 0) mu[0] = 0;
return mu;
}
static short* mertens_array(UV hi)
{
signed char* mu;
short* M;
UV i;
/* We could blend this with range_moebius but it seems not worth it. */
mu = range_moebius(0, hi);
New(0, M, hi+1, short);
M[0] = 0;
for (i = 1; i <= hi; i++)
M[i] = M[i-1] + mu[i];
Safefree(mu);
return M;
}
#if 0
IV mertens(UV n) {
/* See Deléglise and Rivat (1996) for O(n^2/3 log(log(n))^1/3) algorithm.
* This implementation uses their lemma 2.1 directly, so is ~ O(n).
* In serial it is quite a bit faster than segmented summation of mu
* ranges, though the latter seems to be a favored method for GPUs.
*/
UV u, j, m, nmk, maxmu;
signed char* mu;
short* M; /* 16 bits is enough range for all 32-bit M => 64-bit n */
IV sum;
if (n <= 1) return n;
u = isqrt(n);
maxmu = (n/(u+1)); /* maxmu lets us handle u < sqrt(n) */
if (maxmu < u) maxmu = u;
mu = range_moebius(0, maxmu);
New(0, M, maxmu+1, short); /* Works up to maxmu < 7613644886 */
M[0] = 0;
for (j = 1; j <= maxmu; j++)
M[j] = M[j-1] + mu[j];
sum = M[u];
for (m = 1; m <= u; m++) {
if (mu[m] != 0) {
IV inner_sum = 0;
UV lower = (u/m) + 1;
UV last_nmk = n/(m*lower);
UV this_k = 0;
UV next_k = n/(m*1);
UV nmkm = m * 2;
for (nmk = 1; nmk <= last_nmk; nmk++, nmkm += m) {
this_k = next_k;
next_k = n/nmkm;
inner_sum += M[nmk] * (this_k - next_k);
}
sum += (mu[m] > 0) ? -inner_sum : inner_sum;
}
}
Safefree(M);
Safefree(mu);
return sum;
}
#endif
typedef struct {
UV n;
IV sum;
} mertens_value_t;
static void _insert_mert_hash(mertens_value_t *H, UV hsize, UV n, IV sum) {
UV idx = n % hsize;
H[idx].n = n;
H[idx].sum = sum;
}
static int _get_mert_hash(mertens_value_t *H, UV hsize, UV n, IV *sum) {
UV idx = n % hsize;
if (H[idx].n == n) {
*sum = H[idx].sum;
return 1;
}
return 0;
}
/* Thanks to Trizen for this algorithm. */
static IV _rmertens(UV n, UV maxmu, short *M, mertens_value_t *H, UV hsize) {
UV s, k, ns, nk, nk1, mk, mnk;
IV sum;
if (n <= maxmu)
return M[n];
if (_get_mert_hash(H, hsize, n, &sum))
return sum;
s = isqrt(n);
ns = n / (s+1);
sum = 1;
#if 0
for (k = 2; k <= ns; k++)
sum -= _rmertens(n/k, maxmu, M, H, hsize);
for (k = 1; k <= s; k++)
sum -= M[k] * (n/k - n/(k+1));
#else
/* Take the above: merge the loops and iterate the divides. */
if (s != ns && s != ns+1) croak("mertens s / ns");
nk = n;
nk1 = n/2;
sum -= (nk - nk1);
for (k = 2; k <= ns; k++) {
nk = nk1;
nk1 = n/(k+1);
mnk = (nk <= maxmu) ? M[nk] : _rmertens(nk, maxmu, M, H, hsize);
mk = (k <= maxmu) ? M[k] : _rmertens(k, maxmu, M, H, hsize);
sum -= mnk + mk * (nk-nk1);
}
if (s > ns)
sum -= _rmertens(s, maxmu, M, H, hsize) * (n/s - n/(s+1));
#endif
_insert_mert_hash(H, hsize, n, sum);
return sum;
}
static short* _prep_rmertens(UV n, UV* pmaxmu, UV* phsize) {
UV j = icbrt(n);
UV maxmu = 1 * j * j;
UV hsize = next_prime(100 + 8*j);
/* At large sizes, start clamping memory use. */
if (maxmu > 100000000UL) {
/* Exponential decay, reduce by factor of 1 to 8 */
float rfactor = 1.0 + 7.0 * (1.0 - exp(-(float)maxmu/8000000000.0));
maxmu /= rfactor;
hsize = next_prime(hsize * 16); /* Increase the result cache size */
}
#if BITS_PER_WORD == 64
/* A 16-bit signed short will overflow at maxmu > 7613644883 */
if (maxmu > UVCONST(7613644883)) maxmu = UVCONST(7613644883);
#endif
*pmaxmu = maxmu;
*phsize = hsize;
return mertens_array(maxmu);
}
IV mertens(UV n) {
UV j, maxmu, hsize;
short* M; /* 16 bits is enough range for all 32-bit M => 64-bit n */
mertens_value_t *H; /* Cache of calculated values */
IV sum;
if (n <= 512) {
static signed char MV16[33] = {0,-1,-4,-3,-1,-4,2,-4,-2,-1,0,-4,-5,-3,3,-1,-1,-3,-7,-2,-4,2,1,-1,-2,1,1,-3,-6,-6,-6,-5,-4};
j = n/16;
sum = MV16[j];
for (j = j*16 + 1; j <= n; j++)
sum += moebius(j);
return sum;
}
M = _prep_rmertens(n, &maxmu, &hsize);
Newz(0, H, hsize, mertens_value_t);
sum = _rmertens(n, maxmu, M, H, hsize);
Safefree(H);
Safefree(M);
return sum;
}
static const signed char _small_liouville[16] = {-1,1,-1,-1,1,-1,1,-1,-1,1,1,-1,-1,-1,1,1};
static signed char* liouville_array(UV hi)
{
signed char* l;
UV a, b, k;
if (hi < 16) hi = 15;
New(0, l, hi+1, signed char);
memcpy(l, _small_liouville, 16);
if (hi >= 16) memset(l+16, -1, hi-16+1);
for (a = 16; a <= hi; a = b+1) {
/* TODO: 2*a >= UV_MAX */
b = (2*a-1 <= hi) ? 2*a-1 : hi;
START_DO_FOR_EACH_PRIME(2, isqrt(b)) {
for (k = 2*p; k <= b; k += p) {
if (k >= a)
l[k] = -1 * l[k/p];
}
} END_DO_FOR_EACH_PRIME
}
return l;
}
int liouville(UV n) {
if (n < 16)
return _small_liouville[n];
else
return( (prime_bigomega(n) & 1) ? -1 : 1 );
}
IV sumliouville(UV n) {
short* M;
mertens_value_t *H;
UV j, maxmu, hsize, k, nk, sqrtn;
IV sum;
if (n <= 96) {
signed char* l = liouville_array(n);
for (sum = 0, j = 1; j <= n; j++)
sum += l[j];
Safefree(l);
return sum;
}
M = _prep_rmertens(n, &maxmu, &hsize);
Newz(0, H, hsize, mertens_value_t);
sqrtn = isqrt(n);
sum = _rmertens(n, maxmu, M, H, hsize);
for (k = 2; k <= sqrtn; k++) {
nk = n / (k*k);
if (nk == 1) break;
sum += (nk <= maxmu) ? M[nk] : _rmertens(nk, maxmu, M, H, hsize);
}
sum += (sqrtn + 1 - k); /* all k where n/(k*k) == 1 */
/* TODO: find method to get exact number of n/(k*k)==1 .. 4. Halves k */
/* Ends up with method like Lehmer's g. */
Safefree(H);
Safefree(M);
return sum;
}
/* This paper shows an algorithm for sieving an interval:
*https://www.ams.org/journals/mcom/2008-77-263/S0025-5718-08-02036-X/S0025-5718-08-02036-X.pdf */
signed char* range_liouville(UV lo, UV hi)
{
UV i;
signed char *l;
unsigned char *nf;
if (hi < lo) croak("range_liouvillle error hi %"UVuf" < lo %"UVuf"\n",hi,lo);
nf = range_nfactor_sieve(lo, hi, 1);
New(0, l, hi-lo+1, signed char);
for (i = 0; i < hi-lo+1; i++)
l[i] = (nf[i] & 1) ? -1 : 1;
Safefree(nf);
return l;
}
UV carmichael_lambda(UV n) {
unsigned char _totient[8] = {0,1,1,2,2,4,2,6};
UV fac[MPU_MAX_FACTORS+1];
int i, nfactors;
UV lambda = 1;
if (n < 8) return _totient[n];
if ((n & (n-1)) == 0) return n >> 2;
i = ctz(n);
if (i > 0) {
n >>= i;
lambda <<= (i>2) ? i-2 : i-1;
}
nfactors = factor(n, fac);
for (i = 0; i < nfactors; i++) {
UV p = fac[i], pk = p-1;
while (i+1 < nfactors && p == fac[i+1]) {
i++;
pk *= p;
}
lambda = lcm_ui(lambda, pk);
}
return lambda;
}
/******************************************************************************/
/* POWERS and ROOTS */
/******************************************************************************/
/* There are at least 4 ways to do this, plus hybrids.
* 1) use a table. Great for 32-bit, too big for 64-bit.
* 2) Use pow() to check. Relatively slow and FP is always dangerous.
* 3) factor or trial factor. Slow for 64-bit.
* 4) Dietzfelbinger algorithm 2.3.5. Quite slow.
* This currently uses a hybrid of 1 and 2.
*/
uint32_t powerof(UV n) {
UV t;
if ((n <= 3) || (n == UV_MAX)) return 1;
if ((n & (n-1)) == 0) return ctz(n); /* powers of 2 */
if (is_perfect_square(n)) return 2 * powerof(isqrt(n));
if (is_perfect_cube(n)) return 3 * powerof(icbrt(n));
/* Simple rejection filter for non-powers of 5-37. Rejects 47.85%. */
t = n & 511; if ((t*77855451) & (t*4598053) & 862) return 1;
if (is_perfect_fifth(n)) return 5 * powerof(rootint(n,5));
if (is_perfect_seventh(n)) return 7 * powerof(rootint(n,7));
if (n > 177146 && n <= UVCONST(1977326743)) {
switch (n) { /* Check for powers of 11, 13, 17, 19 within 32 bits */
case 177147: case 48828125: case 362797056: case 1977326743: return 11;
case 1594323: case 1220703125: return 13;
case 129140163: return 17;
case 1162261467: return 19;
default: break;
}
}
#if BITS_PER_WORD == 64
if (n >= UVCONST(8589934592)) {
/* The Bloom filters reject about 90% of inputs each, about 99% for two.
* Bach/Sorenson type sieves do about as well, but are much slower due
* to using a powmod. */
if ( (t = n %121, !((t*19706187) & (t*61524433) & 876897796)) &&
(t = n % 89, !((t*28913398) & (t*69888189) & 2705511937U)) ) {
/* (t = n % 67, !((t*117621317) & (t*48719734) & 537242019)) ) { */
UV root = rootint(n,11);
if (n == ipow(root,11)) return 11;
}
if ( (t = n %131, !((t*1545928325) & (t*1355660813) & 2771533888U)) &&
(t = n % 79, !((t*48902028) & (t*48589927) & 404082779)) ) {
/* (t = n % 53, !((t*79918293) & (t*236846524) & 694943819)) ) { */
UV root = rootint(n,13);
if (n == ipow(root,13)) return 13;
}
switch (n) {
case UVCONST(762939453125):
case UVCONST(16926659444736):
case UVCONST(232630513987207):
case UVCONST(100000000000000000):
case UVCONST(505447028499293771):
case UVCONST(2218611106740436992):
case UVCONST(8650415919381337933): return 17;
case UVCONST(19073486328125):
case UVCONST(609359740010496):
case UVCONST(11398895185373143):
case UVCONST(10000000000000000000): return 19;
case UVCONST(94143178827):
case UVCONST(11920928955078125):
case UVCONST(789730223053602816): return 23;
case UVCONST(68630377364883): return 29;
case UVCONST(617673396283947): return 31;
case UVCONST(450283905890997363): return 37;
default: break;
}
}
#endif
return 1;
}
int is_power(UV n, UV a)
{
int ret;
if (a > 0) {
uint32_t r; /* The root */
if (a == 1 || n <= 1) return 1;
if ((a % 2) == 0)
return !is_perfect_square_ret(n,&r) ? 0 : (a == 2) ? 1 : is_power(r,a>>1);
if ((a % 3) == 0)
return !is_perfect_cube(n) ? 0 : (a == 3) ? 1 : is_power(icbrt(n),a/3);
if ((a % 5) == 0)
return !is_perfect_fifth(n) ? 0 : (a == 5) ? 1 :is_power(rootint(n,5),a/5);
}
ret = powerof(n);
if (a != 0) return !(ret % a); /* Is the max power divisible by a? */
return (ret == 1) ? 0 : ret;
}
#if BITS_PER_WORD == 64
static const uint32_t root_max[1+MPU_MAX_POW3] = {0,0,4294967295U,2642245,65535,7131,1625,565,255,138,84,56,40,30,23,19,15,13,11,10,9,8,7,6,6,5,5,5,4,4,4,4,3,3,3,3,3,3,3,3,3};
#else
static const uint32_t root_max[1+MPU_MAX_POW3] = {0,0,65535,1625,255,84,40,23,15,11,9,7,6,5,4,4,3,3,3,3,3};
#endif
UV rootint(UV n, UV k) {
UV lo, hi, max;
if (k == 0) return 0;
if (k == 1) return n;
if (k == 2) return isqrt(n);
if (k == 3) return icbrt(n);
/* Bracket between powers of 2, but never exceed max power so ipow works */
max = 1 + ((k > MPU_MAX_POW3) ? 2 : root_max[k]);
lo = UVCONST(1) << (log2floor(n)/k);
hi = ((lo*2) < max) ? lo*2 : max;
/* Binary search */
while (lo < hi) {
UV mid = lo + (hi-lo)/2;
if (ipow(mid,k) <= n) lo = mid+1;
else hi = mid;
}
return lo-1;
}
/* Like ipow but returns UV_MAX if overflow */
UV ipowsafe(UV n, UV k) {
UV p = 1;
if (k <= MPU_MAX_POW3) {
if (k == 0) return 1;
if (k == 1) return n;
return (n <= root_max[k]) ? ipow(n,k) : UV_MAX;
}
while (k) {
if (k & 1) { if (UV_MAX/n < p) return UV_MAX; p *= n; }
k >>= 1;
if (k) { if (UV_MAX/n < n) return UV_MAX; n *= n; }
}
return p;
}
/* Like lcm_ui, but returns 0 if overflow */
UV lcmsafe(UV x, UV y) {
y /= gcd_ui(x,y);
if (UV_MAX/x < y) return 0;
return x*y;
}
UV valuation(UV n, UV k)
{
UV v = 0;
UV kpower = k;
if (k < 2 || n < 2) return 0;
if (k == 2) return ctz(n);
while ( !(n % kpower) ) {
kpower *= k;
v++;
}
return v;
}
/* N => k^s * t => s = valuation_remainder(N, k, &t); */
UV valuation_remainder(UV n, UV k, UV *r) {
UV v;
if (k <= 1) { v = 0; }
else if (k == 2) { v = ctz(n); n >>= v; }
else {
for (v=0; !(n % k); v++)
n /= k;
}
*r = n;
return v;
}
UV logint(UV n, UV b)
{
/* UV e; for (e=0; n; n /= b) e++; return e-1; */
UV v, e = 0;
if (b == 2)
return log2floor(n);
if (b > n)
return 0;
if (n > UV_MAX/b) {
n /= b;
e = 1;
}
for (v = b; v <= n; v *= b)
e++;
return e;
}
unsigned char* range_issquarefree(UV lo, UV hi) {
unsigned char* isf;
UV i, p2, range = hi-lo+1, sqrthi = isqrt(hi);
if (hi < lo) return 0;
New(0, isf, range, unsigned char);
memset(isf, 1, range);
if (lo == 0) isf[0] = 0;
{ /* Sieve multiples of 2^2,3^2,5^2 */
UV p = 2;
while (p < 7 && p <= sqrthi) {
for (p2=p*p, i = P_GT_LO(p2, p2, lo); i >= lo && i <= hi; i += p2)
isf[i-lo] = 0;
p += 1 + (p > 2);
}
}
if (sqrthi >= 7) { /* Sieve multiples of higher prime squares */
unsigned char* segment;
UV seg_base, seg_low, seg_high;
void* ctx = start_segment_primes(7, sqrthi, &segment);
while (next_segment_primes(ctx, &seg_base, &seg_low, &seg_high)) {
START_DO_FOR_EACH_SIEVE_PRIME( segment, seg_base, seg_low, seg_high )
for (p2=p*p, i = P_GT_LO(p2, p2, lo); i >= lo && i <= hi; i += p2)
isf[i-lo] = 0;
END_DO_FOR_EACH_SIEVE_PRIME
}
end_segment_primes(ctx);
}
return isf;
}
#if BITS_PER_WORD == 32
static const uint32_t _maxpowersumn[32] = {0,92681,2343,361,116,53,30,20,14,11,8,7,6,5,4,4,3,3,3,3,3,2,2,2,2,2,2,2,2,2,2,2};
#else
static const UV _maxpowersumn[64] = {0,6074000999,3810777,92681,9839,2190,745,331,175,105,69,49,36,28,22,18,15,13,11,10,9,8,7,6,6,5,5,5,4,4,4,4,3,3,3,3,3,3,3,3,3,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2};
#endif
UV powersum(UV n, UV k)
{
UV a, a2, i, sum;
if (n <= 1 || k == 0) return n;
if (k >= BITS_PER_WORD || n > _maxpowersumn[k]) return 0;
if (n == 2) return 1 + (UVCONST(1) << k);
a = (n & 1) ? n*((n+1)>>1) : (n>>1)*(n+1);
a2 = a*a;
if (k == 1) return a;
if (k == 3) return a2;
#if BITS_PER_WORD == 64
if (k == 2 && n <=2642245) return a * (2*n+1) / 3;
if (k == 4 && n <= 5724) return a * (2*n+1) * (3*n*(n+1)-1) / 15;
if (k == 5 && n <= 1824) return a2 * (4*a - 1) / 3;
if (k == 6 && n <= 482) return a * (2*n+1) * (n*((n*(n*(3*n+6)))-3)+1) /21;
if (k == 7 && n <= 288) return a2 * (6*a2 - 4*a + 1) / 3;
if (k == 8 && n <= 115) return a * (2*n+1) * (n*(n*(n*(n*(n*(5*n+15)+5)-15)-1)+9)-3) / 45;
#else
/* TODO: find the 32-bit limits */
#endif
if (k <= 8 && k < n) {
UV r, fac = 1;
for (sum = 0, r = 1; r <= k; r++) {
/* sum += factorial(r) * stirling2(k,r) * binomial(n+1,r+1); */
sum += fac * stirling2(k,r) * binomial(n+1,r+1);;
fac *= (r+1);
}
return sum;
}
sum = 1 + (UVCONST(1)<<k);
for (i = 3; i <= n; i++)
sum += ipow(i, k);
return sum;
}
UV mpu_popcount_string(const char* ptr, uint32_t len)
{
uint32_t count = 0, i, j, d, v, power, slen, *s, *sptr;
while (len > 0 && (*ptr == '0' || *ptr == '+' || *ptr == '-'))
{ ptr++; len--; }
/* Create s as array of base 10^8 numbers */
slen = (len + 7) / 8;
Newz(0, s, slen, uint32_t);
for (i = 0; i < slen; i++) { /* Chunks of 8 digits */
for (j = 0, d = 0, power = 1; j < 8 && len > 0; j++, power *= 10) {
v = ptr[--len] - '0';
if (v > 9) croak("Parameter '%s' must be a single decimal number",ptr);
d += power * v;
}
s[slen - 1 - i] = d;
}
/* Repeatedly count and divide by 2 across s */
while (slen > 1) {
if (s[slen-1] & 1) count++;
sptr = s;
if (s[0] == 1) {
if (--slen == 0) break;
*++sptr += 100000000;
}
for (i = 0; i < slen; i++) {
if ( (i+1) < slen && sptr[i] & 1 ) sptr[i+1] += 100000000;
s[i] = sptr[i] >> 1;
}
}
/* For final base 10^8 number just do naive popcnt */
for (d = s[0]; d > 0; d >>= 1)
if (d & 1)
count++;
Safefree(s);
return count;
}
/* How many times does 2 divide n? */
#define padic2(n) ctz(n)
#define IS_MOD8_3OR5(x) (((x)&7)==3 || ((x)&7)==5)
static int kronecker_uu_sign(UV a, UV b, int s) {
while (a) {
int r = padic2(a);
if (r) {
if ((r&1) && IS_MOD8_3OR5(b)) s = -s;
a >>= r;
}
if (a & b & 2) s = -s;
{ UV t = b % a; b = a; a = t; }
}
return (b == 1) ? s : 0;
}
int kronecker_uu(UV a, UV b) {
int r, s;
if (b & 1) return kronecker_uu_sign(a, b, 1);
if (!(a&1)) return 0;
s = 1;
r = padic2(b);
if (r) {
if ((r&1) && IS_MOD8_3OR5(a)) s = -s;
b >>= r;
}
return kronecker_uu_sign(a, b, s);
}
int kronecker_su(IV a, UV b) {
int r, s;
UV rem;
if (a >= 0) return kronecker_uu(a, b);
if (b == 0) return (a == 1 || a == -1) ? 1 : 0;
s = 1;
r = padic2(b);
if (r) {
if (!(a&1)) return 0;
if ((r&1) && IS_MOD8_3OR5(a)) s = -s;
b >>= r;
}
rem = (-a) % b;
a = (rem == 0) ? 0 : b-rem;
return kronecker_uu_sign(a, b, s);
}
int kronecker_ss(IV a, IV b) {
if (a >= 0 && b >= 0)
return (b & 1) ? kronecker_uu_sign(a, b, 1) : kronecker_uu(a,b);
if (b >= 0)
return kronecker_su(a, b);
return kronecker_su(a, -b) * ((a < 0) ? -1 : 1);
}
#define MAX_PNPRIM ( (BITS_PER_WORD == 64) ? 15 : 9 )
#define MAX_PRIM ( (BITS_PER_WORD == 64) ? 52 : 28 )
#if BITS_PER_WORD == 64
static const UV _pn_prim[MAX_PNPRIM+1] =
{1,2,6,30,210,2310,30030,510510,9699690,223092870,
UVCONST(6469693230),UVCONST(200560490130),UVCONST(7420738134810),UVCONST(304250263527210),UVCONST(13082761331670030),UVCONST(614889782588491410)};
static const unsigned char _prim_map[MAX_PRIM+1] =
{0,0,1,2,2,3,3,4,4,4,4,5,5,6,6,6,6,7,7,8,8,8,8,9,9,9,9,9,9,10,10,11,11,11,11,11,11,12,12,12,12,13,13,14,14,14,14,15,15,15,15,15,15};
#else
static const UV _pn_prim[MAX_PNPRIM+1] =
{1,2,6,30,210,2310,30030,510510,9699690,223092870};
static const unsigned char _prim_map[MAX_PRIM+1] =
{0,0,1,2,2,3,3,4,4,4,4,5,5,6,6,6,6,7,7,8,8,8,8,9,9,9,9,9,9};
#endif
UV pn_primorial(UV n) {
return (n > MAX_PNPRIM) ? 0 : _pn_prim[n];
}
UV primorial(UV n) {
return (n > MAX_PRIM) ? 0 : _pn_prim[_prim_map[n]];
}
UV factorial(UV n) {
UV i, r = 1;
if ( (n > 12 && sizeof(UV) <= 4) || (n > 20 && sizeof(UV) <= 8) ) return 0;
for (i = 2; i <= n; i++)
r *= i;
return r;
}