// verify.mjs: finite arithmetic checks for The Ulam Spiral.
// Run: node research/ulam-spiral/verify.mjs
// These checks cover the four central outward rays, counterexamples to global
// diagonal claims, Euler's prime counts, and reduced-form class numbers.
// For integers c >= 2, Rabinowitsch's full c-1 run requires BOTH squarefree
// 4c-1 and field class number one. A nonfundamental discriminant instead counts
// classes in an order; the field class number uses its fundamental discriminant.
// The six lucky constants map to six of the nine Heegner fields. This explains
// the full c-1 runs, without bounding arbitrary quadratic prime streaks.
// Hardy-Littlewood's predicted enhancement for Euler's polynomial is compared
// with a finite count. Neither that conjecture nor the complete Heegner
// classification is proved by this program.

let pass = 0, fail = 0;
const ok = (name, cond, extra = '') => {
  if (cond) { pass++; console.log(`  ok   ${name}${extra ? '   ' + extra : ''}`); }
  else { fail++; console.log(`FAIL   ${name}${extra ? '   ' + extra : ''}`); }
};

// ---------- primality: deterministic Miller–Rabin in BigInt ----------
// Bases {2,3,5,7,11,13,17,19,23,29,31,37} are a proven deterministic witness set
// for all n < 3.3 × 10^24, far beyond anything tested here.
function isPrime(n) {
  n = Math.abs(n);
  const N = BigInt(n);
  if (N < 2n) return false;
  for (const p of [2n, 3n, 5n, 7n, 11n, 13n, 17n, 19n, 23n, 29n, 31n, 37n]) {
    if (N === p) return true;
    if (N % p === 0n) return false;
  }
  let d = N - 1n, r = 0n;
  while (d % 2n === 0n) { d /= 2n; r++; }
  const mod = (b, e, m) => { let res = 1n; b %= m; while (e > 0n) { if (e & 1n) res = (res * b) % m; b = (b * b) % m; e >>= 1n; } return res; };
  for (const a of [2n, 3n, 5n, 7n, 11n, 13n, 17n, 19n, 23n, 29n, 31n, 37n]) {
    let x = mod(a, d, N);
    if (x === 1n || x === N - 1n) continue;
    let composite = true;
    for (let i = 0n; i < r - 1n; i++) { x = (x * x) % N; if (x === N - 1n) { composite = false; break; } }
    if (composite) return false;
  }
  return true;
}
const gcd = (a, b) => { a = Math.abs(a); b = Math.abs(b); while (b) { [a, b] = [b, a % b]; } return a; };

console.log('\n: 1. The four central outward rays are quadratics :\n');

// Build the Ulam square spiral: place 1,2,3,... on a grid spiralling out from the
// origin. Standard counter-clockwise spiral with 1 at centre, 2 to the right.
function buildSpiral(N) {
  const pos = new Map();          // value -> [x,y]
  const at = new Map();           // "x,y" -> value
  let x = 0, y = 0, v = 1;
  pos.set(1, [0, 0]); at.set('0,0', 1);
  // movement: R, U, L, D with growing run lengths 1,1,2,2,3,3,...
  const dirs = [[1, 0], [0, 1], [-1, 0], [0, -1]];
  let di = 0, run = 1;
  while (v < N) {
    for (let rep = 0; rep < 2 && v < N; rep++) {
      const [dx, dy] = dirs[di % 4];
      for (let s = 0; s < run && v < N; s++) {
        x += dx; y += dy; v++;
        pos.set(v, [x, y]); at.set(`${x},${y}`, v);
      }
      di++;
    }
    run++;
  }
  return { pos, at };
}

const { pos, at } = buildSpiral(40000);

// Fit the four outward diagonal rays starting at the centre, n >= 0.
function diagValues(stepx, stepy, count) {
  const out = [];
  for (let k = 0; k < count; k++) {
    const key = `${k * stepx},${k * stepy}`;
    if (at.has(key)) out.push(at.get(key));
  }
  return out;
}
// fit a quadratic through three equally spaced samples -> exact integer coeffs
function fitQuad(vals) {
  // vals[k] = a k^2 + b k + c
  const c = vals[0];
  const a = (vals[2] - 2 * vals[1] + vals[0]) / 2;
  const b = vals[1] - vals[0] - a;
  return { a, b, c };
}

for (const [name, sx, sy] of [['SE (k,−k)', 1, -1], ['NW (−k,k)', -1, 1], ['NE (k,k)', 1, 1], ['SW (−k,−k)', -1, -1]]) {
  const vals = diagValues(sx, sy, 60);
  const { a, b, c } = fitQuad(vals);
  let exact = true;
  for (let k = 0; k < vals.length; k++) if (a * k * k + b * k + c !== vals[k]) { exact = false; break; }
  ok(`diagonal ${name} is exactly ${a}n²${b >= 0 ? '+' : ''}${b}n${c >= 0 ? '+' : ''}${c}`, exact && a === 4, `first vals ${vals.slice(0, 5).join(',')}`);
}

// An offset ray needs the eventual qualification: its first second difference
// is 16, followed by 8. An even diagonal refutes the all-odd claim.
const offset = Array.from({ length: 6 }, (_, k) => at.get(`${1+k},${-1+k}`));
const seconds = offset.slice(2).map((v, i) => v - 2*offset[i+1] + offset[i]);
ok('offset ray (1,-1)+k(1,1) is eventually quadratic, not from its first cell',
  offset.join(',') === '9,11,29,55,89,131' && seconds.join(',') === '16,8,8,8');
const evenDiagonal = Array.from({ length: 7 }, (_, k) => at.get(`${1+k},${k}`));
ok('diagonal through 2 is all even', evenDiagonal.join(',') === '2,12,30,56,90,132,182');

console.log('\n— 2. Euler’s polynomial n² + n + 41 —\n');

const euler = n => n * n + n + 41;
let streak = 0;
for (let n = 0; n < 41; n++) { if (isPrime(euler(n))) streak = n + 1; else break; }
ok('n²+n+41 is prime for n = 0..39 (40 in a row)', streak === 40, `streak=${streak}, values 41,43,47,53,…,1601`);
ok('first value euler(0) = 41', euler(0) === 41);
ok('last prime euler(39) = 1601 and is prime', euler(39) === 1601 && isPrime(1601));
ok('euler(40) = 1681 = 41² (composite — streak breaks at n = p−1)', euler(40) === 1681 && 1681 === 41 * 41);
// the reason: euler(40) = 40²+40+41 = 41·(40+1) = 41²; generally euler(p-1) divisible by p
ok('streak breaks because euler(p−1) ≡ 0 (mod p) for p=41', euler(40) % 41 === 0);

// how prime-rich overall in 0..10000?
let cnt = 0; for (let n = 0; n <= 10000; n++) if (isPrime(euler(n))) cnt++;
ok('n²+n+41 yields primes for 4149 of n=0..10000 (~41%)', cnt === 4149, `count=${cnt}`);

const oddNear1000 = Array.from({ length: 100 }, (_, k) => 901 + 2*k);
ok('30 of the 100 odd integers 901..1099 are prime', oddNear1000.filter(isPrime).length === 30,
  `odd-integer estimate 2/log(1000)=${(2/Math.log(1000)).toFixed(6)}`);
const shiftedEuler = Array.from({ length: 80 }, (_, n) => n*n-79*n+1601);
ok('a shifted Euler quadratic has 80 prime outputs, with 40 distinct values',
  shiftedEuler.every(isPrime) && new Set(shiftedEuler).size === 40);

console.log('\n— 3. Class numbers by counting reduced binary quadratic forms —\n');

// Order h(D), equal to field h only for fundamental D: count primitive reduced positive-definite
// forms (a,b,c) with b²−4ac = D, |b| ≤ a ≤ c, and b ≥ 0 whenever |b| = a or a = c.
function classNumber(D) {
  if (D >= 0 || (D % 4 !== 0 && (((D % 4) + 4) % 4) !== 1)) return null; // D ≡ 0 or 1 (mod 4)
  const absD = -D;
  let h = 0;
  const aMax = Math.floor(Math.sqrt(absD / 3));
  for (let a = 1; a <= aMax; a++) {
    for (let b = -a; b <= a; b++) {
      if (((b * b - D) % (4 * a)) !== 0) continue;
      const c = (b * b - D) / (4 * a);
      if (c < a) continue;
      if (gcd(gcd(a, Math.abs(b)), c) !== 1) continue;     // primitive
      if (b < 0 && (Math.abs(b) === a || a === c)) continue; // boundary: keep only b≥0
      h++;
    }
  }
  return h;
}
function fieldDiscriminant(D) {
  for (let k = 2; k*k <= Math.abs(D); k++) while (D % (k*k) === 0) D /= k*k;
  return ((D % 4) + 4) % 4 === 1 ? D : 4*D;
}
ok('nonfundamental discriminants distinguish order and field class numbers',
  fieldDiscriminant(-27) === -3 && classNumber(-27) === 1 && classNumber(-3) === 1 &&
  fieldDiscriminant(-75) === -3 && classNumber(-75) === 2 &&
  fieldDiscriminant(-99) === -11 && classNumber(-99) === 2 && classNumber(-11) === 1);

// calibrate against published class numbers (Cohen, "A Course in Computational ANT", tables)
const known = { '-3': 1, '-4': 1, '-7': 1, '-8': 1, '-11': 1, '-15': 2, '-19': 1, '-20': 2, '-23': 3, '-24': 2, '-43': 1, '-47': 5, '-67': 1, '-71': 7, '-163': 1, '-164': 8 };
let calOK = true, calDetail = [];
for (const [d, hv] of Object.entries(known)) { const got = classNumber(+d); if (got !== hv) { calOK = false; } calDetail.push(`h(${d})=${got}`); }
ok('class-number counter matches published values', calOK, calDetail.join(' '));

console.log('\n— 4. Rabinowitsch (1913) + Euler’s lucky numbers —\n');

// For prime p: streak length; squarefree 1-4p is already fundamental.
function streakOf(p) { let s = 0; for (let n = 0; ; n++) { if (isPrime(n * n + n + p)) s = n + 1; else break; } return s; }
const lucky = [2, 3, 5, 11, 17, 41];
const heegnerDiscs = [-7, -11, -19, -43, -67, -163];
let allLucky = true, luckyDetail = [];
for (let i = 0; i < lucky.length; i++) {
  const p = lucky[i];
  const D = 1 - 4 * p;
  const s = streakOf(p);
  const h = classNumber(D);
  // Rabinowitsch: streak should be exactly p−1 (n=0..p−2), and h should be 1, and D = the matching Heegner disc
  const good = s === p - 1 && h === 1 && D === heegnerDiscs[i];
  if (!good) allLucky = false;
  luckyDetail.push(`p=${p}: streak=${s} (=p−1=${p - 1}?), 1−4p=${D}, h=${h}`);
}
ok('each lucky p ∈ {2,3,5,11,17,41}: streak = p−1, field h = 1, D is minus a Heegner number', allLucky);
for (const d of luckyDetail) console.log('         ' + d);

// the converse direction: non-lucky primes do NOT give a full Rabinowitsch run.
// Rabinowitsch's exact hypothesis needs 1−4p to be a *fundamental* discriminant
// (squarefree): a lucky p is precisely a prime where 1−4p is squarefree AND has
// class number 1. Each non-lucky prime fails one of those — show which.
const squarefree = m => { m = Math.abs(m); for (let k = 2; k * k <= m; k++) if (m % (k * k) === 0) return false; return true; };
const notLucky = [7, 13, 23, 31];
let convOK = true, convDetail = [];
for (const p of notLucky) {
  const s = streakOf(p);
  const D = 1 - 4 * p;
  const sf = squarefree(D);
  const h = classNumber(D);
  const why = !sf ? 'NOT squarefree (1−4p not fundamental)' : `squarefree but h=${h}>1`;
  convDetail.push(`p=${p}: streak=${s}<p−1=${p - 1}, 1−4p=${D} — ${why}`);
  if (s >= p - 1 || (sf && h === 1)) convOK = false;
}
ok('non-lucky primes 7,13,23,31 fall short — each fails “1−4p squarefree with h=1”', convOK);
for (const d of convDetail) console.log('         ' + d);

let criterionOK = true;
for (let c = 2; c <= 200; c++) {
  const D = 1 - 4*c;
  const fullRun = streakOf(c) === c - 1;
  const criterion = squarefree(D) && classNumber(fieldDiscriminant(D)) === 1;
  if (fullRun !== criterion) criterionOK = false;
}
ok('full c-1 run agrees with squarefreeness AND field h=1 for c=2..200', criterionOK);

console.log('\n: 5. The Heegner list gives the six full c-1 runs :\n');

// The nine Heegner numbers: positive squarefree d with Q(√−d) class number 1.
const heegner = [1, 2, 3, 7, 11, 19, 43, 67, 163];
// Verify each has class number 1 (using fundamental discriminant: D=−d for d≡3 mod4, D=−4d otherwise)
let heeOK = true, heeDetail = [];
for (const d of heegner) {
  const D = (d % 4 === 3) ? -d : -4 * d;
  const h = classNumber(D);
  if (h !== 1) heeOK = false;
  heeDetail.push(`d=${d}(D=${D}):h=${h}`);
}
ok('all nine Heegner numbers {1,2,3,7,11,19,43,67,163} have class number 1', heeOK, heeDetail.join(' '));
// and there is no tenth below a large bound (exhaustive small check; full proof is Baker–Stark)
let extra = [];
for (let d = 1; d <= 100000; d++) {
  // squarefree test
  let sf = true; for (let k = 2; k * k <= d; k++) if (d % (k * k) === 0) { sf = false; break; }
  if (!sf) continue;
  const D = (d % 4 === 3) ? -d : -4 * d;
  if (classNumber(D) === 1 && !heegner.includes(d)) extra.push(d);
}
ok('no tenth class-number-one d up to 100,000 (Baker–Stark proved there is none, ever)', extra.length === 0, extra.length ? 'found ' + extra : 'exhaustive to 1e5');

console.log('\n— 6. Hardy–Littlewood Conjecture F (1923) — matches, but UNPROVEN —\n');

// For Euler's polynomial, compare the finite prime count with the baseline
// sum 1/log(n*n+n+41). Jacobson and Williams (2003), p. 500, give the
// conjectural odd-integer enhancement C(-163)=3.3197732; the all-integer
// enhancement is twice that. The infinite product is quoted, not computed here.
const M = 1000000;
let primeCount = 0;
for (let n = 0; n <= M; n++) if (isPrime(n * n + n + 41)) primeCount++;
// baseline: ∫_0^M dn/ln(n²+n+41)
let baseline = 0;
for (let n = 2; n <= M; n++) baseline += 1 / Math.log(n * n + n + 41);
const enhancement = primeCount / baseline;
// n²+n+41 is ALWAYS odd (n²+n is even), so vs a random integer of the same size it
// runs ≈ 6.6× as prime-rich — the figure usually quoted for Euler's polynomial.
// The Hardy–Littlewood constant proper compares against ODD integers (baseline 2/ln),
// so it is exactly half: ≈ 3.3198. (Hardy & Littlewood, "Some problems of 'Partitio
// Numerorum' III", Acta Math 44 (1923), Conjecture F.)
ok('measured enhancement vs random integers ≈ 6.6 (the quoted figure for Euler’s polynomial)', Math.abs(enhancement - 6.64) < 0.2, `measured=${enhancement.toFixed(4)}, count=${primeCount}`);
ok('measured odd-baseline enhancement is close to the quoted 3.3198', Math.abs(enhancement / 2 - 3.3198) < 0.1, `HL=${(enhancement / 2).toFixed(4)}`);
console.log('         NOTE: Conjecture F PREDICTS this density; it remains UNPROVEN.');
console.log('         It is not even known whether n²+n+41 is prime infinitely often.');

console.log(`\n${fail === 0 ? '✓' : '✗'}  ${pass}/${pass + fail} checks passed\n`);
process.exit(fail === 0 ? 0 : 1);
