#!/usr/bin/env node
// Gilbreath's conjecture — the leading entry of every row of iterated absolute
// differences of the primes is 1 — verified to a real bound, then taken apart:
// WHY it works (the {0,2} self-perpetuation), whether it is "about the primes"
// (controls), and where bounded gaps alone fail to force the leading 1.
//
// The finite numerical checks below are reproduced from a fresh checkout.
// Historical figures and theorems are cited. Run: node research/gilbreath/verify.mjs
//
// Facts cited (NOT recomputed here, marked in the stratum's apparatus):
//   - Odlyzko, A. M. (1993), "Iterated absolute values of differences of
//     consecutive primes," Math. Comp. 61, 373-380: verified the leading-1
//     property for the first n = pi(10^13) ~ 3.4e11 terms, via a row that is
//     1 followed only by 0s and 2s for the next n terms (the argument we
//     reproduce in miniature below).
//   - Gardner, M. (Dec 1980), Scientific American 243(6), 18-28: published
//     Croft's suggestion about odd numbers with reasonable growth and gaps.
//   - Eppstein, D. (2011), "Anti-Gilbreath sequences": counterexamples under
//     every unbounded, nondecreasing gap bound f(n) >= 2. The small bounded-gap
//     witnesses below are separate finite calculations.

const PASS = [];
const FAIL = [];
function check(name, cond, detail = "") {
  (cond ? PASS : FAIL).push(name + (detail ? `  [${detail}]` : ""));
  const tag = cond ? "PASS" : "FAIL";
  console.log(`  ${tag}  ${name}${detail ? "  — " + detail : ""}`);
}
function h(s) { console.log("\n" + s); console.log("=".repeat(s.length)); }

// ---------------------------------------------------------------------------
// Primes — a simple sieve, enough for a few hundred thousand of them.
// ---------------------------------------------------------------------------
function primesUpTo(limit) {
  const sieve = new Uint8Array(limit + 1);
  const out = [];
  for (let i = 2; i <= limit; i++) {
    if (!sieve[i]) {
      out.push(i);
      for (let j = i * i; j <= limit; j += i) sieve[j] = 1;
    }
  }
  return out;
}

// ---------------------------------------------------------------------------
// The leading-edge algorithm. To know the FIRST entry of difference-row k of a
// sequence, you need only its first k+1 terms. Feeding terms one at a time and
// maintaining the trailing anti-diagonal `edge`, the value appended when the
// (k+1)-th term arrives IS d^k_0 — the leading entry of row k. O(rows) per term.
// Returns the array L where L[k] = leading entry of row k (L[0] = first term).
// ---------------------------------------------------------------------------
function leadingEntries(seqIterLen, termAt) {
  const edge = [];
  const L = [];
  for (let m = 0; m < seqIterLen; m++) {
    let x = termAt(m);
    for (let k = 0; k < edge.length; k++) {
      const nx = Math.abs(x - edge[k]);
      edge[k] = x;
      x = nx;
    }
    edge.push(x);
    L.push(x); // x here is d^(m)_0, the leading entry of row m
  }
  return L;
}

// Full triangle (only for small M — O(M^2) memory) so we can inspect whole rows.
function fullTriangle(seq) {
  const rows = [seq.slice()];
  while (rows[rows.length - 1].length > 1) {
    const prev = rows[rows.length - 1];
    const next = new Array(prev.length - 1);
    for (let i = 0; i < next.length; i++) next[i] = Math.abs(prev[i + 1] - prev[i]);
    rows.push(next);
  }
  return rows;
}

// ===========================================================================
h("1 · Gilbreath's conjecture on the primes — the leading entry of every row is 1");
// ===========================================================================
// Independent verification far past any hand check. ROWS rows of differences;
// needs the first ROWS+1 primes.
const ROWS = 100000;
// nth prime is below n*(ln n + ln ln n) for n>=6; pad generously.
const need = ROWS + 2;
const upper = Math.ceil(need * (Math.log(need) + Math.log(Math.log(need))) * 1.15);
const primes = primesUpTo(upper);
check("sieve produced enough primes", primes.length >= need, `have ${primes.length}, need ${need}`);

const Lp = leadingEntries(need, (m) => primes[m]);
// Lp[0] is the first prime (2). The conjecture is about rows k>=1.
let firstBad = -1;
for (let k = 1; k < Lp.length; k++) if (Lp[k] !== 1) { firstBad = k; break; }
check(
  `leading entry of all ${ROWS} difference-rows of the primes equals 1`,
  firstBad === -1,
  firstBad === -1 ? `rows 1..${Lp.length - 1} all lead with 1` : `row ${firstBad} leads with ${Lp[firstBad]}`
);
console.log(`     (row 0 is the primes themselves; leads with ${Lp[0]}. Rows 1..${Lp.length - 1} are the difference rows.)`);

// ===========================================================================
h("2 · WHY — the {0,2} regime, and why a leading 1 then perpetuates forever");
// ===========================================================================
// The mechanism (Odlyzko's, in miniature): a ROW of the form [1, then values
// all in {0,2}] reproduces its own shape one row down, regenerating the leading
// 1 indefinitely. Proof: if a_0=1 and a_i in {0,2} for i>=1, the next row b has
// b_0 = |a_1 - 1| = 1 (since a_1 in {0,2}); and b_i = | a_{i+1} - a_i | with both
// in {0,2}, so b_i in {0,2}. The shape is a fixed point of the difference map.
function isOneThenZeroTwo(row) {
  if (row.length === 0 || row[0] !== 1) return false;
  for (let i = 1; i < row.length; i++) if (row[i] !== 0 && row[i] !== 2) return false;
  return true;
}
// (a) verify the self-perpetuation lemma exhaustively on random [1,{0,2}*] rows.
let lemmaOK = true;
let lemmaTrials = 0;
for (let t = 0; t < 200000; t++) {
  const len = 2 + (Math.random() * 30 | 0);
  const row = [1];
  for (let i = 1; i < len; i++) row.push(Math.random() < 0.5 ? 0 : 2);
  const next = new Array(row.length - 1);
  for (let i = 0; i < next.length; i++) next[i] = Math.abs(row[i + 1] - row[i]);
  lemmaTrials++;
  if (!isOneThenZeroTwo(next)) { lemmaOK = false; break; }
}
check(
  "self-perpetuation lemma: any row [1, then only 0s and 2s] maps to another such row",
  lemmaOK,
  `${lemmaTrials} random rows, every image kept the shape (regenerating the leading 1)`
);

// (b) For the first M primes, find the FIRST row that is already [1, {0,2}*]
// across its whole width — from there down, every leading entry is forced to 1.
const M = 4000;
const tri = fullTriangle(primes.slice(0, M));
let firstStableRow = -1;
for (let r = 1; r < tri.length; r++) {
  if (isOneThenZeroTwo(tri[r])) { firstStableRow = r; break; }
}
check(
  `the primes reach the self-sustaining {0,2} regime early`,
  firstStableRow !== -1,
  `first row that is [1, then only 0s and 2s] across the first ${M} primes is row ${firstStableRow}`
);
// Confirm: from that row down, the triangle's whole left edge is 1 (within this triangle).
let edgeAllOne = firstStableRow !== -1;
for (let r = firstStableRow; r < tri.length; r++) if (tri[r][0] !== 1) { edgeAllOne = false; break; }
check(
  `below the stable row, every leading entry in this triangle is 1`,
  edgeAllOne,
  `rows ${firstStableRow}..${tri.length - 1} (the lemma, watched directly)`
);
// Show the first few rows for the apparatus.
console.log("\n     The first eight rows over the primes (leading column boxed by eye):");
for (let r = 0; r < 8; r++) {
  console.log(`       row ${r}:  ` + tri[r].slice(0, 14).join("  ") + (tri[r].length > 14 ? "  …" : ""));
}

// ===========================================================================
h("3 · IS IT ABOUT THE PRIMES? — controls: random odd sequences with small gaps");
// ===========================================================================
// Croft's intuition: the property is about the gap STRUCTURE, not primality.
// Test it. Build sequences that start 2, 3, then odd numbers with random small
// even gaps, and ask how often the WHOLE difference triangle leads with 1.
// This is a genuine experiment — outcome printed, whatever it is.
function rng(seed) { // small deterministic PRNG (mulberry32) for reproducibility
  let a = seed >>> 0;
  return function () {
    a |= 0; a = (a + 0x6D2B79F5) | 0;
    let t = Math.imul(a ^ (a >>> 15), 1 | a);
    t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
    return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
  };
}
function allLeadingOne(seq) {
  const L = leadingEntries(seq.length, (m) => seq[m]);
  for (let k = 1; k < L.length; k++) if (L[k] !== 1) return k; // returns failing row, or -1
  return -1;
}
function randomOddSeq(seed, len, gapPool) {
  const r = rng(seed);
  const seq = [2, 3]; // start like the primes
  while (seq.length < len) {
    const g = gapPool[(r() * gapPool.length) | 0];
    seq.push(seq[seq.length - 1] + g);
  }
  return seq;
}

function trialBatch(label, gapPool, len, trials, seed0) {
  let ok = 0;
  let firstFail = null;
  for (let s = 0; s < trials; s++) {
    const seq = randomOddSeq(seed0 + s * 101, len, gapPool);
    const f = allLeadingOne(seq);
    if (f === -1) ok++;
    else if (!firstFail) firstFail = { seed: seed0 + s * 101, row: f, head: seq.slice(0, 8) };
  }
  console.log(`     ${label}: ${ok}/${trials} random length-${len} sequences satisfy Gilbreath (all rows lead with 1)`);
  if (firstFail) console.log(`        a failing one: seed ${firstFail.seed}, first bad row ${firstFail.row}, starts ${firstFail.head.join(",")}…`);
  return { ok, trials, firstFail };
}

const tightGaps = trialBatch("gaps in {2}        ", [2], 300, 200, 1);
const smallGaps = trialBatch("gaps in {2,4}      ", [2, 4], 300, 2000, 1);
const widerGaps = trialBatch("gaps in {2,4,6}    ", [2, 4, 6], 300, 2000, 1);
const wideGaps = trialBatch("gaps in {2,4,6,8,10}", [2, 4, 6, 8, 10], 300, 2000, 1);

check(
  "the property is NOT unique to primes — many random small-gap odd sequences also satisfy it",
  smallGaps.ok > 0 && widerGaps.ok > 0,
  `e.g. ${widerGaps.ok}/${widerGaps.trials} of the {2,4,6}-gap sequences pass`
);
check(
  "but it is NOT automatic for any bounded-gap odd sequence — many random ones FAIL",
  smallGaps.firstFail !== null || widerGaps.firstFail !== null || wideGaps.firstFail !== null,
  `bounded gaps alone do not force it (explicit finite witnesses below)`
);

// ===========================================================================
h("4 · WHERE IT BREAKS — bounded-gap, 2-then-odd sequences that FAIL");
// ===========================================================================
// Croft (Gardner 1980) suggested sequences starting with 2, then odd numbers
// growing at a "reasonable" rate with gaps of "reasonable" size. Eppstein
// (2011) constructs failures under unbounded, nondecreasing bounds f(n) >= 2.
// These two finite witnesses show that bounded gaps alone do not force it.
function firstFailingRow(seq) {
  const L = leadingEntries(seq.length, (m) => seq[m]);
  for (let k = 1; k < L.length; k++) if (L[k] !== 1) return { row: k, val: L[k] };
  return null;
}
// Exhaustive search by length: shortest sequence starting `prefix`, continued
// with odd terms (gaps drawn from `gaps`), whose triangle fails to lead with 1.
function shortestWitness(prefix, gaps, maxLen) {
  let best = null;
  function dfs(seq) {
    if (best && seq.length >= best.seq.length) return; // can't beat current best
    const f = firstFailingRow(seq);
    if (f) { if (!best || seq.length < best.seq.length) best = { seq: seq.slice(), ...f }; return; }
    if (seq.length >= maxLen) return;
    for (const g of gaps) { seq.push(seq[seq.length - 1] + g); dfs(seq); seq.pop(); }
  }
  dfs(prefix.slice());
  return best;
}
function showWitness(w) {
  if (!w) { console.log("     (none found within the search budget)"); return; }
  const gaps = w.seq.slice(1).map((v, i) => v - w.seq[i]);
  console.log(`     sequence (len ${w.seq.length}): ${w.seq.join(", ")}`);
  console.log(`     gaps: ${gaps.join(",")}   (max gap ${Math.max(...gaps)}; all terms after the 2 are odd)`);
  console.log(`     first row to break: row ${w.row} leads with ${w.val}, not 1.`);
  const wtri = fullTriangle(w.seq);
  console.log(`     that row in full: ${wtri[w.row].join("  ")}`);
}

// (a) The shortest possible witness at all (start 2,3; gaps in {2,4}).
console.log("  (a) shortest bounded-gap (<=4) witness, starting only 2,3:");
const wShort = shortestWitness([2, 3], [2, 4], 8);
showWitness(wShort);

// (b) How long can a witness AGREE with the primes and still fail? Fix a prefix
// equal to the first P primes, then continue with bounded gaps. The longer the
// agreement we can still break, the clearer that primality — not a gap bound —
// is what the primes are really supplying.
let deepest = null;
for (let P = 4; P <= 10; P++) {
  const w = shortestWitness(primes.slice(0, P), [2, 4, 6], primes.slice(0, P).length + 8);
  if (w) deepest = { P, w };
}
console.log(`\n  (b) a witness that copies the primes' first ${deepest ? deepest.P : "?"} terms exactly, then fails:`);
if (deepest) showWitness(deepest.w);

check(
  "explicit shortest bounded-gap (<=4) 2-then-odd sequence whose Gilbreath triangle fails to lead with 1",
  wShort !== null,
  wShort ? `length ${wShort.seq.length}, first fails at row ${wShort.row} (leads with ${wShort.val})` : "none found"
);
check(
  "a bounded-gap continuation can copy the primes for several terms and still fail; bounded gaps alone are NOT sufficient",
  deepest !== null && deepest.P >= 4,
  deepest ? `copies the first ${deepest.P} primes, then breaks at row ${deepest.w.row}` : "none found"
);

// ===========================================================================
h("RESULT");
// ===========================================================================
console.log(`  ${PASS.length} checks PASSED, ${FAIL.length} FAILED.`);
if (FAIL.length) { console.log("  FAILURES:"); for (const f of FAIL) console.log("   - " + f); process.exit(1); }
console.log("  The finite numerical checks listed above have passed; historical claims and theorems are cited, not re-derived.");
