#!/usr/bin/env python3 """Route 4, job 764: the weighted certificate, and a multi-support tightness census. The frozen support (p=97, a=97^2=9409) is decided by tight capacity: at the record prefix sum_q M(q) = |D|, any cover must attain every per-prime maximum with pairwise disjoint kill sets, and one slot in no argmax kill set refutes it. This script asks the two questions the route's own next_step names. (a) THE WEIGHTED (FRACTIONAL) CERTIFICATE. For weights w >= 0 on D, a cover (one phase b_q per prime) implies sum_q max_b W(q,b) >= sum_q W(q,b_q) >= W(D), W(q,b) = sum_{s in K(q,b)} w_s, so a UNIFORM w reproduces the counting bound F1 = |D| - sum_q M(q). The weighted family is strictly larger: it decides every prefix where V = max over w,t >= 0 of [ sum_s w_s - sum_q t_q ] with t_q >= max_b W(q,b) is positive, i.e. where the per-prime maxima can be brought below W(D) simultaneously. V > 0 gives an integer certificate; V = 0 says the counting relaxation is exhausted at that prefix. Both are exact, not sampled: V is the optimum of a rational LP, and a V > 0 witness is re-verified in integer arithmetic. (b) THE MULTI-SUPPORT CENSUS. The frozen support is one starting interval at p = 97. For every support a in a scanned block this recomputes the capacity scan, collects the tight prefixes (F1 = 0), and decides each: a slot in no argmax kill set, or an exhaustive disjoint-argmax-tiling search. It reports how often tightness recurs and which branch refutes it. stdout is the artifact and must reproduce byte for byte; timing goes to stderr. python3 route4-weighted.py --scan-a 9409 120 """ import sys import time from collections import Counter import numpy as np T0 = time.time() sys.stdout.reconfigure(newline='\n') NODE_CAP = 2_000_000 def log(*a): print(*a, file=sys.stderr) def is_prime(n): return n >= 2 and all(n % d for d in range(2, n) if d * d <= n) def old_primes(p): return [n for n in range(2, p + 1) if is_prime(n)] def new_primes(p): return [n for n in range(p + 1, 2 * p + 1) if is_prime(n)] def slots_from(a, limit, old): """Admissible old-twin starts s = a, a+1, ... with gcd(s(s+2), prod old)==1.""" out = [] s = a while len(out) < limit: if all(s % r and (s + 2) % r for r in old): out.append(s) s += 1 return out def capacity(D, qs): """c[q][b] = |K(q,b)|, M[q] = max_b, argmax[q] = maximising phases.""" c = {q: Counter() for q in qs} for s in D: for q in qs: c[q][(-s) % q] += 1 c[q][(-s - 2) % q] += 1 M = {q: max(c[q].values()) for q in qs} am = {q: tuple(b for b in range(q) if c[q][b] == M[q]) for q in qs} return c, M, am def kill(D, q, b): return frozenset(s for s in D if (s + b) % q == 0 or (s + b + 2) % q == 0) def maxima(D, qs, w): """sum_q max_b W(q,b) for rational weights w (exact Fractions).""" tot = 0 for q in qs: W = Counter() for s, x in zip(D, w): if x: W[(-s) % q] += x W[(-s - 2) % q] += x tot += max(W.values()) if W else 0 return tot class WeightedSolver: """Min-max for sum_q max_b W(q,b) over w >= 0, sum w = 1. f(w) = sum_q max_b W(q,b) = max over phase vectors b of a_b . w, so the minimum over the simplex is a zero-sum game: the minimiser picks weights, the maximiser picks the per-prime argmax phase. Multiplicative weights on the minimiser plus the running average of the maximiser's pure replies gives BOTH directions exactly: * a w with f(w) < 1, re-verified with integer weights -> a strict deficit, hence non-coverability (a cover forces f(w) >= 1 for every w); * a reply-average lambda = cnt/T with sum_q (lambda(q,-s)+lambda(q,-s-2)) >= 1 for every s -> lamdba is a feasible FRACTIONAL cover, which forces f(w) >= 1 for every w, hence the weighted family is silent there. The check is integer arithmetic on the counts, so it is not a tolerance. Both checks are exact; whether a branch was FOUND is what the search decides. """ def __init__(self, qs): self.qs = qs def evaluate(self, D, qs, w): f = 0.0 Darr = np.array(D, dtype=np.int64) for q in qs: Wq = np.zeros(q) np.add.at(Wq, (-Darr) % q, w) np.add.at(Wq, (-Darr - 2) % q, w) f += float(Wq.max()) return f def search(self, D, qs, iters, seed=0, w0=None): n = len(D) Darr = np.array(D, dtype=np.int64) i1 = [(-Darr) % q for q in qs] i2 = [(-Darr - 2) % q for q in qs] w = np.full(n, 1.0 / n) if w0 is None else np.asarray(w0, dtype=float).copy() w /= w.sum() cnt = [np.zeros(q, dtype=np.int64) for q in qs] best = (float('inf'), None, 0) for t in range(1, iters + 1): eta = 0.7 / np.sqrt(t) gain = np.zeros(n) for qi, q in enumerate(qs): Wq = np.zeros(q) np.add.at(Wq, i1[qi], w) np.add.at(Wq, i2[qi], w) b = int(np.argmax(Wq)) cnt[qi][b] += 1 gain[i1[qi] == b] += 1.0 gain[i2[qi] == b] += 1.0 f = self.evaluate(D, qs, w) if f < best[0]: best = (f, w.copy(), t) w = w * np.exp(-eta * gain) w = np.maximum(w, 1e-300) w /= w.sum() # fractional-cover witness from the reply average, as integer counts slack = [] for s in D: cov = 0 for qi, q in enumerate(qs): cov += int(cnt[qi][(-s) % q]) + int(cnt[qi][(-s - 2) % q]) slack.append(cov - iters) return best, min(slack), cnt def integer_certificate(self, D, qs, w, den=10 ** 6): """Round w to integers over a common denominator and verify f < W(D).""" from fractions import Fraction wi = [int(Fraction(float(x)).limit_denominator(den) * den) for x in w] if sum(wi) == 0: return None tot = sum(wi) per = {} for q in qs: W = Counter() for s, x in zip(D, wi): if x: W[(-s) % q] += x W[(-s - 2) % q] += x per[q] = max(W.values()) if W else 0 if sum(per.values()) < tot: return sum(per.values()), tot, per return None def tight_verdict(D, qs, M, am, nodes): nodes = [nodes] union = {s: [] for s in D} for q in qs: for b in am[q]: for s in kill(D, q, b): union[s].append(q) dead = [s for s in D if not union[s]] if dead: return 'noncoverable', 'slot_in_no_argmax_kill_set', dead[0], nodes[0] order = sorted(qs, key=lambda q: (-M[q], q)) sets = {q: [kill(D, q, b) for b in am[q]] for q in qs} def rec(i, used, picked): nodes[0] += 1 if nodes[0] > NODE_CAP: raise RuntimeError('node cap') if len(used) == len(D): return list(picked) rest = sum(M[order[j]] for j in range(i, len(order))) if len(used) + rest < len(D): return None q = order[i] for b, K in zip(am[q], sets[q]): if K & used: continue r = rec(i + 1, used | K, picked + [(q, b)]) if r is not None: return r return None try: tiling = rec(0, frozenset(), []) except RuntimeError: return 'undecided', 'search_cap', None, nodes[0] if tiling is None: return 'noncoverable', 'argmax_disjoint_tiling_absent', None, nodes[0] return 'coverable', 'tiling', tiling, nodes[0] def scan_prefixes(slots, qs, upto): """F1(n) = n - sum_q max_b |K(prefix_n, q, b)| for n = 1..upto.""" c = {q: Counter() for q in qs} out = [] for n in range(1, upto + 1): s = slots[n - 1] for q in qs: c[q][(-s) % q] += 1 c[q][(-s - 2) % q] += 1 out.append((n, n - sum(max(c[q].values()) for q in qs))) return out ITERS = 6000 def section_a(out, old, qs, frozen_a): # ---------------- (a) the frozen support ---------------- slots = slots_from(frozen_a, 200, old) f1 = scan_prefixes(slots, qs, 70) first_pos = next(n for n, v in f1 if v > 0) out.append('## (a) The weighted (fractional) certificate') out.append(f'frozen support a = {frozen_a} = {int(round(frozen_a ** 0.5))}^2; ' f'first capacity-positive prefix ' f'N = {first_pos} at interval length L = {slots[first_pos - 1] - frozen_a + 1}') out.append('') sol = WeightedSolver(qs) out.append('n L F1 min f(w) found one-sided lower bd exact verdict') total_cert = 0 cert, silent, undecided = [], [], [] first_cert = None for n, F1 in f1: L = slots[n - 1] - frozen_a + 1 D = slots[:n] (f, w, it), slack, cnt = sol.search(D, qs, ITERS) ic = sol.integer_certificate(D, qs, w) if ic is not None: sw, tot, per = ic verdict = 'STRICT DEFICIT: noncoverable (integer w)' total_cert += 1 cert.append((n, L, F1, f, sw, tot, per)) if first_cert is None: first_cert = (n, L, F1) elif slack >= 0: verdict = 'silent: fractional cover verified (min f >= 1)' silent.append((n, L, F1, f, slack)) else: verdict = 'undecided: neither branch verified' undecided.append((n, L, F1, f)) out.append(f'{n:<5d} {L:<8d} {F1:<6d} {f:<16.6f} {("f>=1 (lambda)" if slack >= 0 else "-"):<19s} {verdict}') out.append('') if cert: out.append('weighted certificates (integer weights, re-verified in integer arithmetic):') for n, L, F1, f, sw, tot, per in cert[:6]: out.append(f' n={n} L={L} F1={F1}: sum_q max_b W(q,b) = {sw} < sum_s w_s = {tot} ' f'(deficit {tot - sw} of {tot}; min f <= {f:.6f})') out.append(' per-prime maxima: ' + ', '.join(f'{q}:{per[q]}' for q in qs)) if len(cert) > 6: out.append(f' ... and {len(cert) - 6} more certified prefixes') if silent: last = silent[-1] out.append(f'prefixes certified SILENT by a verified fractional cover: n = ' f'{silent[0][0]}..{last[0]} (largest L = {last[1]}), counts stored in the JSON sidecar') out.append(f'prefixes scanned: {len(f1)}; capacity-tight (F1 = 0): ' f'{sum(1 for _, v in f1 if v == 0)}; strict weighted deficits: {total_cert}; ' f'silent: {len(silent)}; undecided: {len(undecided)}') if first_cert is not None: out.append(f'WEIGHTED FRONTIER: the smallest certified non-coverable prefix is n = {first_cert[0]} ' f'(L = {first_cert[1]}), where F1 = {first_cert[2]}' + (' <-- F1 < 0: the counting bound is SILENT here' if first_cert[2] < 0 else ' (also capacity-tight)')) out.append('') def section_b(out, old, qs, a0, count): # ---------------- (b) the multi-support census ---------------- out.append('## (b) Multi-support tightness census at p = 97') out.append(f'supports scanned: a = {a0} .. {a0 + count - 1} ({count} values)') stat = Counter() tight_rows = [] for a in range(a0, a0 + count): sl = slots_from(a, 200, old) f1a = scan_prefixes(sl, qs, 90) pos = next((n for n, v in f1a if v > 0), None) tights = [n for n, v in f1a if v == 0] stat['supports'] += 1 if len(tights) == 0: stat['no_tight_prefix'] += 1 else: stat['has_tight_prefix'] += 1 for n in tights: D = sl[:n] c, M, am = capacity(D, qs) nodes = 0 v, why, wit, nodes = tight_verdict(D, qs, M, am, nodes) stat['tight_prefixes'] += 1 stat['tight_' + v] += 1 stat['branch_' + why] += 1 tight_rows.append((a, n, sl[n - 1] - a + 1, v, why, wit, nodes, None if wit is None or why != 'slot_in_no_argmax_kill_set' else wit - a)) if tight_rows: out.append('a n L verdict branch witness') for a, n, L, v, why, wit, nodes, off in tight_rows: if why == 'slot_in_no_argmax_kill_set': w = f's = {wit} (offset {off} from a)' elif why == 'argmax_disjoint_tiling_absent': w = f'nodes = {nodes}' else: w = str(wit) out.append(f'{a:<6d} {n:<3d} {L:<6d} {v:<14s} {why:<33s} {w}') out.append('') offs = [off for *_x, off in tight_rows if off is not None] out.append(f'dead-slot offsets from a: {sorted(set(offs))} (n = {len(offs)})') out.append('') out.append('summary: ' + '; '.join(f'{k}={stat[k]}' for k in sorted(stat))) free = sum(1 for *_x, off in tight_rows if off is None) out.append(f'tight prefixes with a dead slot: {len(tight_rows) - free} of {len(tight_rows)}') def main(): global ITERS p = 97 a0, count = 9409, 60 argv = sys.argv[1:] if '--iters' in argv: ITERS = int(argv[argv.index('--iters') + 1]) if '--scan-a' in argv: i = argv.index('--scan-a') a0, count = int(argv[i + 1]), int(argv[i + 2]) old, qs = old_primes(p), new_primes(p) out = [] out.append('# Route 4, job 764: weighted certificate and multi-support tightness census') out.append(f'# p = {p}; Q = {qs} ({len(qs)} primes); old primes up to {p}') out.append('') if '--only-b' not in argv: section_a(out, old, qs, 9409) section_b(out, old, qs, a0, count) sys.stdout.write('\n'.join(out) + '\n') log('done in %.1fs' % (time.time() - T0)) if __name__ == '__main__': main()