#!/usr/bin/env python3 # -*- coding: utf-8 -*- """K*(P,R), the two-class covering run, computed exactly from the record's definitions. DEFINITION (read off the served record, not invented here): * the tile T_P for a squarefree P is the twin tile: the slots in [0,P) are the residues r with gcd(r,P)=1 and gcd(r+2,P)=1; * for a set R of odd primes the period is M = P * prod(R); * the slot word is the increasing list of x = r + k*P (r a T_P slot, 0 <= k < M/P), read cyclically; * slot x is R-KILLED iff x = 0 or x = -2 (mod q) for some q in R; * K*(P,R) is the maximal length of a CYCLIC run of consecutive KILLED slots. CUSTODY GATES (published values this must reproduce before any new number is reported): K*(30 ,{7,11,19}) = 9 and it loses ONE slot on the base change 30 -> 390, K*(390,{7,11,19}) = 8 (return #1246's witness), with K*(30 ,{7,11,13,19}) = 10 (return #1250's C on the same witness); K*(30 ,{7,13,19,23}) = 12 and K*(330,{7,13,19,23}) = 10, a DROP OF 2 (return #1267, which refuted the sharp-drop conjecture). """ import argparse import itertools import json import os import sys import time from math import gcd import numpy as np HERE = os.path.dirname(os.path.abspath(__file__)) def primorial_gcd(a, b): return gcd(a, b) def twin_slots(P): """The T_P twin slots: r coprime to P with r+2 coprime to P as well.""" return [r for r in range(P) if gcd(r, P) == 1 and gcd(r + 2, P) == 1] def slot_count(P): """prod over p | P of (p-2) for p >= 5, times 1 for p = 2 and p = 3.""" n, m = 1, P p = 2 while p * p <= m: if m % p == 0: n *= 1 if p in (2, 3) else (p - 2) while m % p == 0: m //= p p += 1 if m > 1: n *= 1 if m in (2, 3) else (m - 2) return n def max_cyclic_run(killed): """Longest cyclic run of True in a boolean array (the slot word is cyclic). Measured on the ALIVE positions: the killed run that follows an alive slot j is (next alive position) - j - 1, cyclically. Counting from the killed positions instead gives the number of alive gaps between them, which is a different and wrong number -- the first draft of this file did exactly that and the custody gate caught it (7 against the record's 9). """ n = killed.size if not killed.any(): return 0 if killed.all(): return n alive = np.flatnonzero(~killed) gaps = np.diff(np.concatenate([alive, alive[:1] + n])) return int(gaps.max()) - 1 def kstar(P, R, want_runs=False): """K*(P,R) exactly, by full-period enumeration of the slot word. Returns (K*, slots, M, argmax_runs) where argmax_runs lists the maximal killed runs attaining K*, each as a list of slot indices into the slot word. """ R = sorted(R) M = P for q in R: M *= q reps = twin_slots(P) per = M // P # the slot word: x = r + k*P, k fastest so the word is increasing in x x = (np.asarray(reps, dtype=np.int64)[:, None] * 1 + np.asarray(range(per), dtype=np.int64)[None, :] * P).reshape(-1) x.sort() killed = np.zeros(x.size, dtype=bool) for q in R: killed |= (x % q == 0) | ((x + 2) % q == 0) K = max_cyclic_run(killed) runs = [] if want_runs and K: # every maximal killed run of length K (cyclic): start one step after each # alive slot and walk forward while killed n = killed.size if killed.all(): runs = [list(range(n))] else: for j in np.flatnonzero(~killed): s = (int(j) + 1) % n if not killed[s]: continue ln, k = 0, s while killed[k]: ln += 1 k = (k + 1) % n if ln >= n: break if ln == K: runs.append([(s + t) % n for t in range(ln)]) return K, x, M, runs def fork_profile(x, run, p): """p-forked slots inside a run's span: slot x with p | x or p | x+2. These are exactly the slots of T_P that are NOT slots of T_Pp, so they are the only way the run can lose a member when the base grows P -> P*p. """ return [i for i in run if (x[i] % p == 0) or ((x[i] + 2) % p == 0)] def longest_survivor(x, run, p): """Longest contiguous chain inside the run that survives passing to T_Pp. A slot survives iff it is not p-forked AND the killing by R is unchanged (the killers are divisible by neither p nor the rest, so R-killed is inherited). """ surv = [((x[i] % p != 0) and ((x[i] + 2) % p != 0)) for i in run] best = cur = 0 for s in surv: cur = cur + 1 if s else 0 best = max(best, cur) return best # ---------------------------------------------------------------------------- gates GATES = [ ("K*(30,{7,11,19})", 30, [7, 11, 19], 9), ("K*(390,{7,11,19})", 390, [7, 11, 19], 8), ("K*(30,{7,11,13,19})", 30, [7, 11, 13, 19], 10), ("K*(30,{7,13,19,23})", 30, [7, 13, 19, 23], 12), ("K*(330,{7,13,19,23})", 330, [7, 13, 19, 23], 10), ] def run_gates(): out = [] ok = True for name, P, R, want in GATES: t0 = time.time() K, x, M, _ = kstar(P, R) good = (K == want) ok = ok and good out.append({"gate": name, "expected": want, "observed": K, "pass": good, "P": P, "R": R, "modulus": M, "slots": int(x.size), "seconds": round(time.time() - t0, 3)}) print("%-24s expected %2d observed %2d M=%-9d slots=%-8d %s" % (name, want, K, M, x.size, "PASS" if good else "FAIL")) return ok, out # ---------------------------------------------------------------------------- sweep def primes_upto(n): s = np.ones(n + 1, dtype=bool) s[:2] = False for i in range(2, int(n ** 0.5) + 1): if s[i]: s[i * i::i] = False return [int(i) for i in np.flatnonzero(s)] def sweep(bases, ps, sizes, max_modulus, np_ps=None): """For each (P, p, R) record A = K*(P,R), B = K*(P*p,R), C = K*(P,R u {p}). Also, on every maximal attaining run: the p-fork count and the longest chain that survives the base change, to test whether the drop is *determined* by the argmax. """ rows = [] np_ps = primes_upto(np_ps) if np_ps else [] for P in bases: for size in sizes: others = [q for q in (np_ps or ps) if q != 2 and gcd(q, P) == 1] for R in itertools.combinations(others, size): R = list(R) for p in ps: if p in R or gcd(p, P) != 1: continue M3 = P * p for q in R: M3 *= q if M3 > max_modulus: continue A, xa, Ma, runs = kstar(P, R, want_runs=True) B, xb, Mb, _ = kstar(P * p, R) C, xc, Mc, _ = kstar(P, R + [p]) row = {"P": P, "p": p, "R": R, "A": A, "B": B, "C": C, "drop": A - B, "bound": (2 * A) // p, "right_gap": C - B, "modulus": M3, "C_modulus": Mc} # argmax structure if runs: spans = [] for rn in runs: spans.append({ "forks": len(fork_profile(xa, rn, p)), "surv": longest_survivor(xa, rn, p), "len": len(rn), }) row["n_runs"] = len(runs) row["fork_counts"] = sorted({s["forks"] for s in spans}) row["best_surv"] = max(s["surv"] for s in spans) row["max_forks"] = max(s["forks"] for s in spans) rows.append(row) return rows def summarise(rows): out = {"rows": len(rows)} out["left_violations"] = [r for r in rows if r["B"] < r["A"] - 1] out["drop_bound_violations"] = [r for r in rows if r["drop"] > r["bound"]] out["right_violations"] = [r for r in rows if r["B"] > r["C"] - 1] out["bound_attained"] = [r for r in rows if r["drop"] == r["bound"] and r["bound"] > 0] out["drop_hist"] = {} for r in rows: out["drop_hist"][r["drop"]] = out["drop_hist"].get(r["drop"], 0) + 1 # does the argmax structure determine B? out["argmax_holds"] = [r for r in rows if "best_surv" in r and r["best_surv"] == r["B"]] out["argmax_fails"] = [r for r in rows if "best_surv" in r and r["best_surv"] != r["B"]] out["fork_law_violations"] = [r for r in rows if "max_forks" in r and r["drop"] > r["max_forks"]] return {k: (len(v) if isinstance(v, list) else v) for k, v in out.items()} def main(): ap = argparse.ArgumentParser() ap.add_argument("--mode", default="gates", choices=["gates", "record", "extend", "killer"]) ap.add_argument("--out", default=None) a = ap.parse_args() log = {} if a.mode in ("gates", "record", "extend"): t0 = time.time() ok, gate_rows = run_gates() log["gates"] = gate_rows log["gates_ok"] = ok print("gates: %s (%.1fs)" % ("PASS" if ok else "FAIL", time.time() - t0)) if not ok: print(json.dumps(log, indent=1)) return 2 if a.mode == "record": # return #1250's shape: P in {30,210,2310}, p in 7..47, |R| <= 3, M <= 2.2e6 rows = sweep([30, 210, 2310], primes_upto(47), [1, 2, 3], 2_200_000, np_ps=48) log["record_sweep"] = {"rows": len(rows), "summary": summarise(rows), "detail": rows} print(json.dumps(log["record_sweep"]["summary"], indent=1)) if a.mode == "killer": # the KILLER dial at fixed tile: A = K*(P,R) and Aq = K*(P,R u {q}). # Is the marginal a function of (A, q) alone -- a one-number law -- or does it # need the argmax structure? This dial is the one the certificate uses (the # entering-prime set Q(s) grows while the tile grows). rows = [] for P in (30, 210, 2310): pool = [q for q in primes_upto(53) if q >= 7 and gcd(q, P) == 1] for size in (1, 2, 3): for R in itertools.combinations(pool, size): R = list(R) for q in pool: if q in R: continue base = P for r in R: base *= r withq = base * q if withq > 40_000_000: continue A, xa, _M, runs = kstar(P, R, want_runs=True) Aq, _xq, _Mq, _ = kstar(P, R + [q]) if not A: continue forks = max((len(fork_profile(xa, rn, q)) for rn in runs), default=None) rows.append({"P": P, "R": R, "q": q, "A": A, "Aq": Aq, "delta": A - Aq, "floor_2A_q": (2 * A) // q, "floor_A_q": A // q, "forks_of_argmax": forks}) # the one-number test: group by (A, q) and see whether delta is constant groups = {} for r in rows: groups.setdefault((r["A"], r["q"]), set()).add(r["delta"]) split = {k: sorted(v) for k, v in groups.items() if len(v) > 1} log["killer_sweep"] = { "rows": len(rows), "delta_hist": {str(d): sum(1 for r in rows if r["delta"] == d) for d in sorted({r["delta"] for r in rows})}, "delta_ge_1": sum(1 for r in rows if r["delta"] >= 1), "delta_le_0": sum(1 for r in rows if r["delta"] <= 0), "one_number_law_failures": len(split), "example_failures": {"%s|%s" % k: v for k, v in itertools.islice(split.items(), 8)}, "delta_eq_floor_2A_q": sum(1 for r in rows if r["delta"] == r["floor_2A_q"]), "delta_eq_floor_A_q": sum(1 for r in rows if r["delta"] == r["floor_A_q"]), "distinct_A_q_pairs": len(groups), "detail": rows, } print(json.dumps({k: v for k, v in log["killer_sweep"].items() if k not in ("detail",)}, indent=1, default=str)) if a.mode == "extend": # |R| up to 4, p up to 97, one tile larger, M <= 2.2e6 rows = sweep([30, 210, 2310], primes_upto(97), [2, 3, 4], 2_200_000, np_ps=98) log["extended_sweep"] = {"rows": len(rows), "summary": summarise(rows), "detail": rows} print(json.dumps(log["extended_sweep"]["summary"], indent=1)) if a.out: with open(a.out, "w", encoding="utf-8", newline="\n") as fh: json.dump(log, fh, indent=1, sort_keys=True) fh.write("\n") print("wrote", a.out) return 0 if log.get("gates_ok", True) else 2 if __name__ == "__main__": sys.exit(main())