// zone46.c -- solveathome job #46: the twin-slot counts of research/01-zone-twin-share.js recomputed a different // way, sharing no code with it. // // The script sieves [1, p_{n+1}^2) by the primes <= p_n only and counts r >= 3 with r + 2 < p_{n+1}^2 and neither r // nor r + 2 divisible by any prime <= p_n (the primes <= p_n themselves count as hit). Below p_{n+1}^2 such an r is // prime and exceeds p_n, so the count is the number of twin-prime pairs (r, r+2) with p_n < r and r + 2 < p_{n+1}^2. // Here: one full sieve of Eratosthenes over the odd numbers below the largest window, the list of twin-pair starts, // and a binary search per level. // ./zone46 prints one line per level: pn, pNext, window, cand #include #include #include #include typedef long long ll; static const int LEVELS[] = {5, 7, 11, 13, 17, 19, 23, 31, 43, 61, 89, 127, 179, 251, 353, 499, 701, 997, 1409, 1999, 2999, 4001, 5003, 7001, 9973, 12007, 14009, 16001, 18013, 20011}; static const int NL = sizeof(LEVELS) / sizeof(LEVELS[0]); static int isprime_small(int n) { if (n < 2) return 0; for (int d = 2; (ll)d * d <= n; d++) if (n % d == 0) return 0; return 1; } static int nextprime(int n) { int q = n + 1; while (!isprime_small(q)) q++; return q; } int main(void) { ll N = 0; // sieve every odd number below N for (int i = 0; i < NL; i++) { ll q = nextprime(LEVELS[i]); if (q * q > N) N = q * q; } ll half = N / 2 + 1; unsigned char *comp = calloc(half, 1); // comp[k] = 1 iff 2k+1 is composite (k >= 1) if (!comp) { fprintf(stderr, "calloc\n"); return 1; } comp[0] = 1; // 1 is not prime for (ll k = 1; (2 * k + 1) * (2 * k + 1) < N; k++) { if (comp[k]) continue; ll p = 2 * k + 1; for (ll m = p * p; m < N; m += 2 * p) comp[m / 2] = 1; } // twin-pair starts r (odd, r and r+2 prime), r + 2 < N; (3,5) is the first ll cap = 1 << 22, n = 0; ll *tw = malloc(cap * sizeof(ll)); for (ll k = 1; 2 * k + 3 < N; k++) { if (!comp[k] && !comp[k + 1]) { if (n == cap) { cap *= 2; tw = realloc(tw, cap * sizeof(ll)); } tw[n++] = 2 * k + 1; } } free(comp); printf("# twin-prime pairs (r, r+2) with r + 2 < %lld: %lld\n", N, n); for (int i = 0; i < NL; i++) { ll pn = LEVELS[i]; if (!isprime_small((int)pn)) { printf("pn=%lld is not prime\n", pn); continue; } ll q = nextprime((int)pn), W = q * q; // count r with pn < r and r + 2 < W, i.e. r in (pn, W - 2) ll lo = 0, hi = n; // first index with tw > pn while (lo < hi) { ll mid = (lo + hi) / 2; if (tw[mid] > pn) hi = mid; else lo = mid + 1; } ll a = lo; lo = 0; hi = n; // first index with tw + 2 >= W while (lo < hi) { ll mid = (lo + hi) / 2; if (tw[mid] + 2 >= W) hi = mid; else lo = mid + 1; } printf("pn=%lld pNext=%lld window=%lld cand=%lld\n", pn, q, W, lo - a); } free(tw); return 0; }