#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Exact CRT cover instrument for the twin-opener doubling ladder (route 173). A *cover of length m* for the base tile T_s (slots `a` modulo `W = P(s)#`, `D = |T_s|`) and the entering primes `Q` (primes in `(s, 2s]`) is one residue `r_q` per `q in Q` such that every one of `m` cyclically consecutive base slots `a_i..a_{i+m-1}` meets a === r_q (mod q) or a === r_q - 2 (mod q) for some q. By the CRT equivalence used by return #2017 (copy `c` kills slot `a` at prime `q` iff `c*W === -a` or `-a-2 (mod q)`), a copy that kills `m` consecutive base slots exists if and only if some start admits a cover of length `m`; hence `K*` = largest coverable length. This module implements (a) the wheel construction of `T_s`, (b) the exact cyclic maxsum, (c) a vectorised all-start *root capacity* necessary test (upper bound on the extra coverage each remaining prime can supply), (d) an exact backtracking cover search for one window (the same first-uncovered-slot branching as the served `doubling-check.js`, re-implemented here), and (e) the physical-copy brute force used only for small-period controls. Nothing here is a proof and nothing bounds G2, beta_2 or twin-prime infinitude. """ import numpy as np # ----------------------------------------------------------------------------- primes / wheels def primes_upto(n): ps = [] for k in range(2, n + 1): ok = True for p in ps: if p * p > k: break if k % p == 0: ok = False break if ok: ps.append(k) return ps def primorial(p): r = 1 for q in primes_upto(p): r *= q return r def twin_slots(base): """Twin-opener slots modulo base# as a sorted int64 array in [0, base#). Built by wheel extension: T_3 = [5] mod 6, and T_{w*p} = { r + c*w# : r in T_w, c in [0,p), r + c*w# not === 0,-2 (mod p) }. """ assert base >= 3 A = np.array([5], dtype=np.int64) W = 6 for p in primes_upto(base): if p < 5: continue cand = np.concatenate([A + c * W for c in range(p)]) keep = (cand % p != 0) & ((cand + 2) % p != 0) A = np.sort(cand[keep]) W *= p return A, W def slot_count_formula(base): r = 1 for p in primes_upto(base): if p >= 3: r *= p - 2 return r # ----------------------------------------------------------------------------- exact spans def base_gap(a, W): """Maximal cyclic gap between consecutive slots of the tile (G-hat of the base level).""" inner = int((a[1:] - a[:-1]).max()) wrap = int(a[0] + W - a[-1]) return max(inner, wrap) def maxsum(a, W, m): """Largest sum of m cyclically consecutive gaps, exact.""" D = len(a) r = m % D shift = m // D return int((np.roll(a, -r) - a).max()) + shift * W def gaps(a, W): g = np.empty(len(a), dtype=np.int64) g[:-1] = a[1:] - a[:-1] g[-1] = a[0] + W - a[-1] return g # ----------------------------------------------------------------------------- cover search def residue_masks(res, q): """List `masks` of length q with masks[t] = bitmask of window positions j having res[j]==t.""" masks = [0] * q for j, t in enumerate(res): masks[t] |= 1 << j return masks def window_cover(positions_mod_q, Q, capacity_prune=True): """Exact existence test for a cover of one window. positions_mod_q[k][j] = a_{i+j} mod Q[k] for the window's slots. Returns (found, assignment) where assignment maps q -> chosen residue r (the r of the mask definition: slot a is killed iff a === r or r-2 (mod q)). """ m = len(positions_mod_q[0]) nq = len(Q) rmasks = [residue_masks(positions_mod_q[k], Q[k]) for k in range(nq)] full = (1 << m) - 1 assign = {} def popcount(x): return x.bit_count() def capacity(left, unused): tot = 0 for k in range(nq): if (unused >> k) & 1: q = Q[k] mk = rmasks[k] best = 0 for t in range(q): v = popcount((mk[t] | mk[(t - 2) % q]) & left) if v > best: best = v tot += best return tot # iterative DFS with explicit stack of (left, unused, option-index, chosen list) best_masks = {} def rec(left, unused, depth): if left == 0: return True if unused == 0: return False if capacity_prune and capacity(left, unused) < popcount(left): return False bit = left & -left j = bit.bit_length() - 1 for k in range(nq): if not ((unused >> k) & 1): continue q = Q[k] mk = rmasks[k] r1 = positions_mod_q[k][j] r2 = (r1 + 2) % q for r in ((r1, r2) if r1 != r2 else (r1,)): mask = mk[r] | mk[(r - 2) % q] nl = left & ~mask if nl == left: continue if rec(nl, unused & ~(1 << k), depth + 1): assign[q] = r return True return False ok = rec(full, (1 << nq) - 1, 0) return ok, (assign if ok else None) # ----------------------------------------------------------------------------- all-start root test def cyclic_extension(a, W, m): """First m terms of the periodic extension a_i = a_{i mod D} + floor(i/D)*W.""" D = len(a) idx = np.arange(D + m) return a[idx % D] + (idx // D) * W def window_residues_ext(a, W, m, Q): """Per prime q, the extended residue array of length D+m so that window i is [i:i+m].""" ext = cyclic_extension(a, W, m) return [(ext % q).astype(np.int32) for q in Q], ext def root_capacity_all(a, W, m, Q, chunk=131072): """Exact root-capacity value for every one of the D windows (vectorised). capacity_i = sum_{q in Q} max_{r in Z/q} #{ j in [0,m) : a_{i+j} === r or r-2 (mod q) }. A window with capacity < m cannot be covered. """ D = len(a) res, ext = window_residues_ext(a, W, m, Q) total = np.zeros(D, dtype=np.int64) for q, amq in zip(Q, res): win = np.lib.stride_tricks.sliding_window_view(amq, m) # shape (D+1, m) cap = np.empty(D, dtype=np.int32) for lo in range(0, D, chunk): hi = min(lo + chunk, D) C = hi - lo R = win[lo:hi] idx = R.astype(np.int64) + np.int64(q) * np.arange(C, dtype=np.int64)[:, None] hist = np.bincount(idx.ravel(), minlength=q * C).reshape(C, q) V = hist + np.roll(hist, -2, axis=1) cap[lo:hi] = V.max(axis=1) total += cap return total, res def scan_all(a, W, m, Q, chunk=131072, capacity_prune=True, stop_first=False, progress=None, cpu=None): """Exact all-start cover scan at length m. Returns dict with the root-capacity array summary, the number of root-filtered starts, the number of starts actually backtracked, the number of covers found and the first witness (start index, assignment) if any. `stop_first` stops at the first cover. """ D = len(a) total, res = root_capacity_all(a, W, m, Q, chunk=chunk) survivors = np.nonzero(total >= m)[0] n_cover = 0 first = None n_bt = 0 for i in survivors: ii = int(i) ok, asg = window_cover([r[ii:ii + m].tolist() for r in res], Q, capacity_prune=capacity_prune) n_bt += 1 if ok: n_cover += 1 if first is None: first = (ii, asg) if stop_first: break return {"m": m, "D": D, "root_min": int(total.min()), "root_max": int(total.max()), "root_pass": int(survivors.size), "backtracked": n_bt, "covers": n_cover, "first": first} # ----------------------------------------------------------------------------- physical brute force def brute_kstar(base, top): """Direct physical-copy walk for small periods: longest run of consecutive base slots killed by the entering primes, over all copies c in [0, prod Q).""" a, W = twin_slots(base) Q = [p for p in primes_upto(top) if p > base] M = W for q in Q: M *= q ncop = 1 for q in Q: ncop *= q reps = M // W assert len(a) * reps <= 5_000_000, "brute force only for small periods" # physical slots over one full period M: extend the base tile periodically pos = np.concatenate([a + c * W for c in range(reps)]) killed = np.zeros(pos.size, dtype=bool) for q in Q: killed |= (pos % q == 0) | ((pos + 2) % q == 0) if killed.all(): return int(pos.size), pos, killed # longest cyclic run of killed slots idx = np.nonzero(~killed)[0] if idx.size == 0: return int(pos.size), pos, killed D = pos.size best = 0 for t in range(idx.size): s = int(idx[t]) e = int(idx[(t + 1) % idx.size]) run = (e - s - 1) % D if run > best: best = run return best, pos, killed # ----------------------------------------------------------------------------- small helpers def crt_copy(W, Q, assign): """Copy c (mod prod Q) realizing a cover assignment: c === -r_q * W^{-1} (mod q).""" from functools import reduce mods = [] rems = [] for q in Q: r = assign[q] % q inv = pow(W % q, -1, q) mods.append(q) rems.append((-r * inv) % q) M = 1 for q in mods: M *= q x = 0 for mi, ri in zip(mods, rems): Mi = M // mi x = (x + ri * Mi * pow(Mi % mi, -1, mi)) % M return x, M def verify_run(a, W, Q, start, m, copy): """Direct divisibility certificate: the m physical slots a_start+cW .. are all killed and the two neighbouring base slots survive.""" D = len(a) Wb = int(W) cb = int(copy) ok_kill = [] for j in range(m): x = int(a[(start + j) % D]) + (start + j) // D * Wb + cb * Wb ok_kill.append(any((x % q == 0) or ((x + 2) % q == 0) for q in Q)) # absolute position of the slot before the run and after the run if start > 0: p_prev = int(a[start - 1]) else: p_prev = int(a[D - 1]) - Wb if start + m < D: p_next = int(a[start + m]) else: p_next = int(a[(start + m) % D]) + Wb surv = [] for x in (p_prev + cb * Wb, p_next + cb * Wb): surv.append(not any((x % q == 0) or ((x + 2) % q == 0) for q in Q)) return all(ok_kill), surv, p_next - p_prev