#!/usr/bin/env node
// Verifier for "The Diagonal Won't Divide" — the GEOMETRIC proof that √2 is irrational.
//
// Everything the stratum asserts is checked here with exact (BigInt) integer
// arithmetic, plus a high-precision check of the continued-fraction tail. Run:
//   node research/geometric-irrationality-root2/verify.mjs
// Exit 0 and "ALL CHECKS PASS" iff every claim holds.
//
// The five claims, each pinned to a check below:
//   C1  Tennenbaum's descent map  D(a,b) = (2b−a, a−b)  sends any positive-integer
//       solution of a² = 2b² to ANOTHER positive-integer solution that is STRICTLY
//       smaller. (This is the whole proof: well-ordering forbids an infinite
//       strictly-decreasing chain of positive integers, so no solution exists.)
//   C2  The geometry encodes the algebra: in the overlap figure the central
//       overlap square has side (2b−a) and the two uncovered corner squares have
//       side (a−b), and area-counting forces (2b−a)² = 2(a−b)² exactly when
//       a² = 2b². So the picture IS the map.
//   C3  No positive-integer solution of a² = 2b² exists (brute-force corroboration
//       up to a large bound — the descent is the proof; this only illustrates it).
//   C4  Anthyphairesis (mutual subtraction) of the square's diagonal and side
//       never terminates: the continued fraction of √2 is [1; 2,2,2,…]. Checked to
//       2000 partial quotients via exact surd arithmetic.
//   C5  The duality: the SAME map run BACKWARDS, A(a,b) = (a+2b, a+b), grows the
//       Pell pairs whose ratios are the continued-fraction convergents of √2
//       (1/1, 3/2, 7/5, 17/12, 41/29, …), each satisfying p² − 2q² = ±1 with the
//       sign alternating, and p/q → √2. Descent proves impossibility; ascent
//       builds the best approximations. One map, two directions.

let PASS = true;
const log = [];
function check(name, cond, detail = "") {
  const ok = !!cond;
  PASS = PASS && ok;
  log.push(`${ok ? "PASS" : "FAIL"}  ${name}${detail ? "  —  " + detail : ""}`);
  if (!ok) console.error(`FAIL: ${name} ${detail}`);
}

// ---------------------------------------------------------------------------
// C1 — Tennenbaum descent.  For ANY (a,b) with a,b > 0 and a² = 2b²:
//   (i)  b < a < 2b           (forced by 1 < √2 < 2, but provable from a²=2b²)
//   (ii) D(a,b) = (2b−a, a−b) is again positive integers with (2b−a)² = 2(a−b)²
//   (iii) 0 < 2b−a < a        (strictly smaller, stays positive)
// We verify the ALGEBRAIC IDENTITY (holds for all integers; see the grid argument below), and the
// inequalities under the hypothesis a²=2b², by exhaustively probing the lattice
// of candidate (a,b) that satisfy the relation approximately AND by an exact
// symbolic argument encoded as identities.
//
// Symbolic identity (holds for ALL a,b, no hypothesis):
//     (2b−a)² − 2(a−b)² = (a² − 2b²)·(−1)
// so if a² = 2b² then (2b−a)² = 2(a−b)². Check on a dense grid of integers.
// Why a finite grid suffices (note 2026-09-27, after an audit asked): the difference
// lhs − rhs is a polynomial of degree ≤ 2 in each of a and b. A polynomial of degree
// ≤ d in each variable that vanishes on a product grid with more than d values per
// variable is identically zero, so vanishing on [−40,40]² (81 values each) proves the
// identity for all integers, indeed all reals. The same argument covers C2's [−30,30]².
{
  let idOk = true, exA = "", exB = "";
  for (let a = -40n; a <= 40n; a++) {
    for (let b = -40n; b <= 40n; b++) {
      const lhs = (2n * b - a) ** 2n - 2n * (a - b) ** 2n;
      const rhs = -(a * a - 2n * b * b);
      if (lhs !== rhs) { idOk = false; exA = a.toString(); exB = b.toString(); }
    }
  }
  check("C1.identity  (2b−a)²−2(a−b)² = −(a²−2b²) for all integers a,b",
        idOk, idOk ? "checked on [−40,40]²" : `counterexample a=${exA}, b=${exB}`);
}

// Inequalities under the hypothesis: if a,b>0 and a²=2b² then b<a<2b, hence
// 0 < 2b−a < a and 0 < a−b. We prove these from a²=2b² as exact integer facts.
//   a²=2b² ⇒ a² > b² ⇒ a > b (a,b>0)            ⇒ a−b > 0
//   a²=2b² ⇒ a² < 4b² = (2b)² ⇒ a < 2b (a,b>0)   ⇒ 2b−a > 0
//   a > b ⇒ 2b−a < b < a                          ⇒ 0 < 2b−a < a  (strict descent)
// There are no positive integer solutions, so we cannot exhibit one; instead we
// confirm the deductions hold for EVERY positive (a,b) with a² ≥ 2b² near-miss
// pattern is irrelevant — we verify the pure implications as Boolean tautologies
// over a grid that INCLUDES the would-be region, asserting the chain is sound.
{
  let chainOk = true;
  for (let a = 1n; a <= 60n; a++) {
    for (let b = 1n; b <= 60n; b++) {
      if (a * a === 2n * b * b) { chainOk = false; } // (none expected; see C3)
      // verify the logical chain on the hypothesis surrogate a²=2b² would force:
      const hyp = a * a === 2n * b * b;
      if (hyp) {
        if (!(a > b && a < 2n * b && 2n * b - a > 0n && a - b > 0n && 2n * b - a < a))
          chainOk = false;
      }
    }
  }
  check("C1.inequalities  a²=2b², a,b>0 ⇒ 0 < 2b−a < a and a−b > 0 (strict descent)",
        chainOk, "implication is vacuously confirmed (no solutions) and algebra above closes it");
}

// ---------------------------------------------------------------------------
// C2 — The geometry IS the map.  Inclusion–exclusion on the a×a square with two
// b×b squares in opposite corners (they overlap because 2b>a):
//   a² = b² + b² − (overlap) + (uncovered)
// with overlap a square of side (2b−a) and uncovered = two squares of side (a−b).
// Substituting a²=2b² must give (2b−a)² = 2(a−b)². Verify the inclusion–exclusion
// bookkeeping as an identity (independent of the hypothesis) and the conclusion.
{
  // For arbitrary a with b<a<2b, the figure's areas (continuous, real) satisfy:
  //   overlapSide = 2b−a ,  cornerSide = a−b
  //   b² + b² − (2b−a)² + 2(a−b)²  ==  a²    ⟺   identity below
  // Expand: 2b² − (4b²−4ab+a²) + 2(a²−2ab+b²)
  //        = 2b² − 4b² + 4ab − a² + 2a² − 4ab + 2b² = a².   ✓ for ALL a,b.
  let ieOk = true, ex = "";
  for (let a = -30n; a <= 30n; a++) {
    for (let b = -30n; b <= 30n; b++) {
      const reconstruct = 2n * b * b - (2n * b - a) ** 2n + 2n * (a - b) ** 2n;
      if (reconstruct !== a * a) { ieOk = false; ex = `a=${a},b=${b}`; }
    }
  }
  check("C2.inclusion-exclusion  2b² − (2b−a)² + 2(a−b)² = a² for all integers a,b",
        ieOk, ieOk ? "the picture's area bookkeeping is an identity" : ex);
  // and the punchline: hypothesis a²=2b² collapses it to overlap = 2·corner
  let punchOk = true;
  for (let a = -30n; a <= 30n; a++)
    for (let b = -30n; b <= 30n; b++)
      if (a * a === 2n * b * b && (2n * b - a) ** 2n !== 2n * (a - b) ** 2n) punchOk = false;
  check("C2.punchline  a²=2b² ⇒ (2b−a)² = 2(a−b)²  (overlap square is twice the corner square)",
        punchOk, "the smaller square is a smaller solution — descent in pictures");
}

// ---------------------------------------------------------------------------
// C3 — Brute force: no positive integer a ≤ N has a²/2 a perfect square (b²).
{
  const N = 5_000_000n;
  let found = null;
  for (let a = 1n; a <= N; a++) {
    const t = a * a;
    if (t % 2n === 0n) {
      const half = t / 2n;
      // integer sqrt of half
      let lo = 0n, hi = a;
      while (lo < hi) { const m = (lo + hi + 1n) >> 1n; if (m * m <= half) lo = m; else hi = m - 1n; }
      if (lo * lo === half && lo > 0n) { found = [a, lo]; break; }
    }
  }
  check(`C3.brute  no positive integer solution of a²=2b² with a ≤ ${N}`,
        found === null, found ? `solution found?! ${found}` : "none — corroborates the descent");
}

// ---------------------------------------------------------------------------
// C4 — Continued fraction of √2 is [1; 2,2,2,…].  Exact surd arithmetic: the CF
// algorithm on x = (√2) using the standard integer recurrence for √n. For n=2:
// a0 = 1, and the periodic part is all 2s. We run the exact algorithm (m,d,a)
// recurrence — no floats — for 2000 steps and confirm every quotient after the
// first equals 2 and the period-1 state repeats.
{
  const n = 2n;
  const a0 = 1n; // floor(√2)
  let m = 0n, d = 1n, a = a0;
  const quotients = [a0];
  let allTwos = true;
  let stateRepeats = true;
  let firstState = null;
  for (let i = 0; i < 2000; i++) {
    m = d * a - m;
    d = (n - m * m) / d;
    a = (a0 + m) / d; // floor((√n + m)/d) = floor((a0 + m)/d) since 0<√n−a0<1 ... exact for the periodic tail
    quotients.push(a);
    if (a !== 2n) allTwos = false;
    const st = `${m},${d}`;
    if (firstState === null) firstState = st;
    else if (st !== firstState) stateRepeats = false;
  }
  check("C4.cf  continued fraction of √2 is [1; 2,2,2,…] (2000 quotients, exact surd recurrence)",
        allTwos && quotients[0] === 1n,
        `a0=${quotients[0]}, tail all 2s = ${allTwos}, period-1 state stable = ${stateRepeats}`);
  // The geometric reading: anthyphairesis of (diagonal d, side s) of a square
  // subtracts the side ONCE (quotient 1, leaving d−s), then the recurrence is
  // self-similar forever (quotient 2 repeating) — it NEVER terminates, so the
  // diagonal and side share no common measure. A terminating CF ⇔ a rational;
  // [1;2,2,2,…] is infinite ⇒ √2 irrational.
  check("C4.never-terminates  the CF is infinite (no quotient is the last) ⇒ incommensurable",
        allTwos, "mutual subtraction of diagonal & side recurs forever");
}

// ---------------------------------------------------------------------------
// C5 — Duality.  Ascent map A(a,b) = (a+2b, a+b) from the seed (1,1):
//   (1,1) → (3,2) → (7,5) → (17,12) → (41,29) → (99,70) → …
// These are the numerator/denominator convergents of [1;2,2,2,…] to √2, and each
// satisfies p² − 2q² = ±1 with the sign alternating; p/q → √2. Verify exactly,
// and verify A is the exact inverse of the descent D on these pairs.
{
  let p = 1n, q = 1n;
  const pell = [[p, q]];
  let signsAlternate = true, invOk = true, monotoneToRoot2 = true;
  let prevErr = null, expectSign = -1n; // p²−2q² for (1,1) is 1−2 = −1
  for (let i = 0; i < 30; i++) {
    const val = p * p - 2n * q * q;
    if (val !== expectSign) signsAlternate = false;
    expectSign = -expectSign;
    // ascent
    const np = p + 2n * q, nq = p + q;
    // descent of the NEW pair must return the OLD pair: D(np,nq) = (2nq−np, np−nq)
    if (2n * nq - np !== p || np - nq !== q) invOk = false;
    // monotone approach: |p/q − √2| should shrink — compare via cross-multiplied
    // exact rationals against successive convergents (ratios bracket √2)
    if (prevErr !== null) {
      // |p²−2q²|/q² is the squared-scale error proxy; check q grows so error→0
      if (!(nq > q)) monotoneToRoot2 = false;
    }
    prevErr = val;
    p = np; q = nq; pell.push([p, q]);
  }
  const head = pell.slice(0, 5).map(([a, b]) => `${a}/${b}`).join(", ");
  check("C5.pell  ascent A(a,b)=(a+2b,a+b) from (1,1) gives Pell pairs, p²−2q²=±1 alternating",
        signsAlternate, `first five: ${head}`);
  check("C5.inverse  ascent A is the exact inverse of descent D (same map, two directions)",
        invOk, "D(A(a,b)) = (a,b)");
  check("C5.convergence  denominators strictly grow ⇒ p/q → √2 (best rational approximations)",
        monotoneToRoot2, "the impossibility map, reversed, is the approximation machine");
}

// ---------------------------------------------------------------------------
console.log("\n" + log.join("\n"));
console.log("\n" + (PASS ? "ALL CHECKS PASS ✓" : "SOME CHECKS FAILED ✗"));
process.exit(PASS ? 0 : 1);
