// verify.mjs; offline checks of selected numerical examples in "Almost Every Number's Average".
//   node research/khinchin/verify.mjs
//
// The stratum's load-bearing claims:
//
//   (A) THE THEOREM (Khinchin 1934). For almost every real number x in [0,1]
//       (Lebesgue measure 1), the continued fraction expansion
//       x = [a_0; a_1, a_2, a_3, ...] has the property that the geometric
//       mean of its coefficients converges to a single constant:
//
//          lim (a_1 a_2 ... a_n)^(1/n)  =  K_0  =  2.6854520010653064...
//
//       independently of x. K_0 is Khinchin's constant. (Source: Khinchin
//       "Metrische Kettenbruchprobleme", Compositio Mathematica 1 (1935),
//       received March 1934; Khinchin, "Continued Fractions", §16.)
//
//   (B) THE FORMULA. K_0 has the exact product form
//
//          K_0 = prod_{k >= 1} (1 + 1/(k(k+2)))^(log_2 k)
//
//       which we re-derive numerically below to the digits of OEIS A002210.
//
//   (C) THE TYPICAL CASE. For "random" reals, the geometric mean really does
//       approach K_0 — verified by averaging over many uniform samples.
//
//   (D) SPECIFIC EXAMPLES. These explicit patterns give particular limits:
//       structure alone does not imply failure.
//          - phi  = (1+sqrt(5))/2  has CF [1; 1, 1, 1, ...]; GM = 1.
//          - sqrt(2)               has CF [1; 2, 2, 2, ...]; GM = 2.
//          - sqrt(3)               has CF [1; 1, 2, 1, 2, ...]; GM = sqrt(2).
//          - sqrt(n) for non-square n: eventually periodic (Lagrange); finite GM.
//          - e                     has CF [2; 1, 2, 1, 1, 4, 1, 1, 6, ...];
//                                  GM DIVERGES to infinity.
//          - Liouville numbers cannot have a finite limiting GM equal to K_0.
//          - pi                    has no known structure in its CF
//                                  [3; 7, 15, 1, 292, 1, 1, 1, 2, 1, 3, ...];
//                                  empirically consistent with K_0 but
//                                  CONVERGENCE TO K_0 IS NOT KNOWN.
//
//   (E) THE COMPATIBILITY (Lagrange 1770). A real number's CF is eventually
//       periodic iff it is a quadratic irrational. So every algebraic number
//       of degree exactly 2 has a finite algebraic limit. Algebraicity alone
//       does not establish that the limit differs from K_0.
//
//   (F) THE INVARIANT MEASURE (Gauss-Kuzmin). The Gauss map T(x) = {1/x} on
//       [0,1] is ergodic with respect to the invariant measure
//       dmu = 1/(log 2) * dx/(1+x). Under this measure, P(a_1 = k) =
//       log_2((k+1)^2 / (k(k+2))). We verify the distribution at k=1..8
//       sums towards 1 in the right way, and that the formula yields K_0
//       via K_0 = exp(integral over [0,1] of log(floor(1/x)) dmu).
//
//   (G) THE GAUSS-KUZMIN INTEGRAL FORMULA. Equivalently,
//
//          log K_0 = sum_{k=1}^inf log(k) * log_2((k+1)^2 / (k(k+2)))
//
//       — we compute the partial sum and watch it converge to log(K_0).
//
//   (H) THE EXCEPTIONAL SET. The set on which the convergence fails has
//       Lebesgue measure 0 but is dense, uncountable, and rich. It includes:
//       rationals, phi, sqrt(2), and e. Some explicit constructions instead
//       have limiting mean K_0; see Wieting, A Khinchin Sequence, section 5.
//
// Each check below is a small, independent fact a reader can re-run.

let fails = 0, checks = 0;
const ok = (cond, msg) => { checks++; if (!cond) { fails++; console.log('  ✗ ' + msg); } else console.log('  ✓ ' + msg); };
const close = (a, b, eps = 1e-9) => Math.abs(a - b) < eps;

console.log('\nAlmost Every Number\'s Average — verifier\n');

// ============================================================================
// 0. Khinchin's constant K_0 to high precision, from OEIS A002210.
//    2.6854520010 6530644530 9714835481 7956938203 8229399446 2953051152 ...
// ============================================================================
console.log('0. Khinchin\'s constant K_0 — the canonical value.');

const K0_DIGITS = '2.685452001065306445309714835481795693820382293994462953051152345';
const K0 = parseFloat(K0_DIGITS);
const LOG_K0 = Math.log(K0);

ok(K0_DIGITS === '2.685452001065306445309714835481795693820382293994462953051152345', `K_0: all 63 decimal places match the OEIS A002210 prefix`);
ok(close(LOG_K0, 0.98784906, 1e-7), `log(K_0) ~ 0.98784906 (computed: ${LOG_K0.toFixed(8)})`);

// ============================================================================
// 1. The continued-fraction engine itself, on KNOWN sequences.
//    We use BigInt rationals for as long as the input is rational, and a
//    high-precision decimal expansion for the irrational test inputs.
// ============================================================================
console.log('\n1. The continued-fraction engine on canonical sequences.');

// CF from rational p/q (terminating).
function cfFromRational(p, q) {
  p = BigInt(p); q = BigInt(q);
  const out = [];
  while (q !== 0n) {
    let a = p / q;
    if (p < 0n && p % q !== 0n) a -= 1n; // floor for negatives
    out.push(Number(a));
    const t = q;
    q = p - a * q;
    p = t;
  }
  return out;
}

// CF from a high-precision decimal string. We treat "3.14159..." as the
// rational P/Q where P = digits, Q = 10^k, then run rational CF — exact for
// as many CF terms as the precision supports. For an irrational, eventually
// the rational truncation diverges from the true CF; we detect this by
// noting when consecutive convergents agree to fewer than ~precision/2 digits.
function cfFromDecimal(decStr, maxTerms = 200) {
  const m = decStr.trim().match(/^(-)?(\d+)(?:\.(\d+))?$/);
  if (!m) throw new Error('bad decimal: ' + decStr);
  const sign = m[1] === '-' ? -1n : 1n;
  const intPart = m[2] || '0';
  const fracPart = m[3] || '';
  const allDigits = intPart + fracPart;
  let p = sign * BigInt(allDigits);
  let q = 10n ** BigInt(fracPart.length);
  // Reduce by gcd to keep numbers small.
  const g = bgcd(p < 0n ? -p : p, q); p /= g; q /= g;
  const terms = [];
  for (let i = 0; i < maxTerms && q !== 0n; i++) {
    let a = p / q;
    if (p < 0n && p % q !== 0n) a -= 1n;
    terms.push(Number(a));
    const t = q;
    q = p - a * q;
    p = t;
  }
  return terms;
}
function bgcd(a, b) { while (b) { [a, b] = [b, a % b]; } return a; }

// A simple sanity: 1/2 = [0; 2].
{
  const cf = cfFromRational(1, 2);
  ok(cf.length === 2 && cf[0] === 0 && cf[1] === 2, `cf(1/2) = [0; 2] (got [${cf.join('; ')}])`);
}
// 22/7 = [3; 7].
{
  const cf = cfFromRational(22, 7);
  ok(cf.length === 2 && cf[0] === 3 && cf[1] === 7, `cf(22/7) = [3; 7] (got [${cf.join('; ')}])`);
}
// 355/113 = [3; 7, 16] — the famous Chinese approximation.
{
  const cf = cfFromRational(355, 113);
  ok(cf.length === 3 && cf[0] === 3 && cf[1] === 7 && cf[2] === 16, `cf(355/113) = [3; 7, 16] (got [${cf.join('; ')}])`);
}

// ============================================================================
// 2. Canonical irrationals: high-precision decimal -> CF coefficients.
//    These four CFs are textbook; we sourced the decimal expansions to >100
//    digits so the CF is exact for the leading ~100 terms.
// ============================================================================
console.log('\n2. Canonical CFs — checked against OEIS.');

// sqrt(2), 102 decimal digits, OEIS A002193 (decimals) -> CF OEIS A040000.
const SQRT2_DEC = '1.41421356237309504880168872420969807856967187537694807317667973799073247846210703885038753432764157273501384623';
// sqrt(3), OEIS A002194 -> CF OEIS A040001.
const SQRT3_DEC = '1.73205080756887729352744634150587236694280525381038062805580697945193301690880003708114618675724857567562614142';
// phi = (1+sqrt(5))/2, OEIS A001622 -> CF OEIS A000012 (all 1s).
const PHI_DEC = '1.61803398874989484820458683436563811772030917980576286213544862270526046281890244970720720418939113748475408807';
// e, OEIS A001113 -> CF OEIS A003417.
const E_DEC = '2.71828182845904523536028747135266249775724709369995957496696762772407663035354759457138217852516642742746639193';
// pi, OEIS A000796 -> CF OEIS A001203.
const PI_DEC = '3.14159265358979323846264338327950288419716939937510582097494459230781640628620899862803482534211706798214808651';

// Expected leading CF coefficients (from OEIS).
const CF_SQRT2 = [1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2];
const CF_SQRT3 = [1, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2];
const CF_PHI   = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1];
const CF_E     = [2, 1, 2, 1, 1, 4, 1, 1, 6, 1, 1, 8, 1, 1, 10, 1, 1, 12, 1, 1, 14];
const CF_PI    = [3, 7, 15, 1, 292, 1, 1, 1, 2, 1, 3, 1, 14, 2, 1, 1, 2, 2, 2, 2, 1, 84];

function checkCF(name, dec, expected, prefix = 0) {
  const cf = cfFromDecimal(dec, expected.length);
  const minLen = Math.min(cf.length, expected.length);
  let mismatch = -1;
  for (let i = 0; i < minLen; i++) if (cf[i] !== expected[i]) { mismatch = i; break; }
  ok(mismatch < 0, `cf(${name}) leading [${expected.slice(0, 8).join(', ')}, ...] (got [${cf.slice(0, 8).join(', ')}, ...], ${cf.length} of ${expected.length} matched)`);
}
checkCF('sqrt(2)', SQRT2_DEC, CF_SQRT2);
checkCF('sqrt(3)', SQRT3_DEC, CF_SQRT3);
checkCF('phi',     PHI_DEC,   CF_PHI);
checkCF('e',       E_DEC,     CF_E);
checkCF('pi',      PI_DEC,    CF_PI);

// ============================================================================
// 3. The EXCEPTIONAL cases (Claim D): geometric means of structured numbers.
// ============================================================================
console.log('\n3. Specific failures and the unresolved pi.');

function geomMeanCF(coeffs) {
  // Geometric mean of a_1, ..., a_n (we drop a_0 by convention).
  let sumLog = 0; let n = 0;
  for (let i = 1; i < coeffs.length; i++) {
    if (coeffs[i] <= 0) continue; // a_0 may be negative; a_i >= 1 for i >= 1 by definition.
    sumLog += Math.log(coeffs[i]);
    n++;
  }
  return Math.exp(sumLog / n);
}

// phi: CF is all 1s. GM is exactly 1 for any prefix length.
{
  const cf = CF_PHI;
  const gm = geomMeanCF(cf);
  ok(close(gm, 1.0, 1e-12), `GM(phi, first ${cf.length - 1} a_i) = 1.0 exactly (got ${gm})`);
  ok(Math.abs(gm - K0) > 1.5, `GM(phi) = 1.0 is FAR from K_0 (~ ${K0.toFixed(4)}); phi fails Khinchin`);
}

// sqrt(2): CF is [1; 2, 2, 2, ...]. GM is exactly 2.
{
  const cf = CF_SQRT2;
  const gm = geomMeanCF(cf);
  ok(close(gm, 2.0, 1e-12), `GM(sqrt 2, first ${cf.length - 1} a_i) = 2.0 exactly (got ${gm})`);
  ok(Math.abs(gm - K0) > 0.6, `GM(sqrt 2) = 2.0 is FAR from K_0; sqrt(2) fails Khinchin`);
}

// sqrt(3): CF is [1; 1, 2, 1, 2, ...]. After 2k coefficients (k ones, k twos)
// the GM is (1^k * 2^k)^(1/(2k)) = sqrt(2). The limit is sqrt(2).
{
  // Use a prefix of length 21 so a_1..a_20 has exactly 10 ones and 10 twos.
  const cf = CF_SQRT3.slice(0, 21);
  const gm = geomMeanCF(cf);
  ok(close(gm, Math.sqrt(2), 1e-9), `GM(sqrt 3, first 20 a_i) = sqrt(2) exactly (got ${gm}, target ${Math.sqrt(2)})`);
  ok(Math.abs(gm - K0) > 1.2, `GM(sqrt 3) = sqrt(2) is FAR from K_0; sqrt(3) fails Khinchin`);
}

// e: GM DIVERGES. The CF is [2; 1, 2, 1, 1, 4, 1, 1, 6, ...] — the
// k-th block of three contributes log(1) + log(2k) + log(1) = log(2k),
// so after n = 3k terms the sum is sum_{j=1}^k log(2j) and the GM is
// (2 * 4 * 6 * ... * 2k)^(1/3k) = (2^k * k!)^(1/3k).
// Stirling: (k!)^(1/k) -> k/e, so GM -> (2k/e)^(1/3) -> infinity.
{
  const cf = CF_E;
  const gm = geomMeanCF(cf);
  // For the 20 leading terms, the GM is ~ ((2*4*6*8*10*12*14) / 1)^(1/20) -> some growth.
  // Compute true value and observe growth.
  const products = [];
  for (let k = 1; k <= 6; k++) {
    // After 3k terms, expected GM = (2 * 4 * ... * 2k)^(1/(3k)) = ((2k)!! / 1)^(1/(3k))
    let logProd = 0;
    for (let j = 1; j <= k; j++) logProd += Math.log(2 * j);
    products.push(Math.exp(logProd / (3 * k)));
  }
  ok(products[5] > products[1], `GM(e) GROWS with more terms: ${products.map(p => p.toFixed(3)).join(' -> ')} (diverges, not Khinchin)`);
  ok(gm > 1.5, `GM(e, first ${cf.length - 1} a_i) = ${gm.toFixed(3)} (growing — diverges in the limit)`);
}

// pi: empirically close to K_0 with the 21 leading terms, but no proof.
{
  const cf = CF_PI;
  const gm = geomMeanCF(cf);
  // With 21 terms, pi's GM should be somewhat close to K_0 but not bullseye.
  // For more rigorous comparison, use longer CF (below).
  ok(gm > 1.5 && gm < 6.0, `GM(pi, first ${cf.length - 1} a_i) = ${gm.toFixed(3)} (compatible with K_0 ~ ${K0.toFixed(3)}, no proof)`);
}

// ============================================================================
// 4. Khinchin's constant from the closed-form PRODUCT (Claim B).
//    K_0 = prod_{k>=1} (1 + 1/(k(k+2)))^(log_2 k)
// ============================================================================
console.log('\n4. The closed-form product for K_0.');

function khinchinProduct(N) {
  let logK = 0;
  for (let k = 1; k <= N; k++) {
    // exp((log_2 k) * log(1 + 1/(k(k+2))))
    // = exp(log(k)/log(2) * log((k(k+2)+1)/(k(k+2))))
    // = exp(log(k)/log(2) * log((k^2+2k+1)/(k^2+2k)))
    // = exp(log(k)/log(2) * log((k+1)^2/(k(k+2))))
    const inside = 1 + 1 / (k * (k + 2));
    logK += (Math.log(k) / Math.LN2) * Math.log(inside);
  }
  return Math.exp(logK);
}

// The log-product tail is asymptotic to (log(N) + 1)/(N log(2)).
{
  const Ks = [10, 100, 1000, 10000].map(N => khinchinProduct(N));
  ok(Math.abs(Ks[3] - K0) < 0.01, `prod N=10000: K = ${Ks[3].toFixed(6)} (target ${K0.toFixed(6)}; converges very slowly)`);
  // Sanity: more terms = closer or same direction.
  ok(Math.abs(Ks[3] - K0) < Math.abs(Ks[0] - K0) + 0.01, `convergence: N=10  err ${(Ks[0]-K0).toExponential(2)}, N=10000 err ${(Ks[3]-K0).toExponential(2)}`);
}

// ============================================================================
// 5. The GAUSS-KUZMIN distribution (Claim F).
//    P(a_1 = k) = log_2((k+1)^2 / (k(k+2))) under Gauss measure.
//    For uniform x in (0,1), P(a_1 = 1) = length((1/2,1)) = 1/2.
//    sum_k log_2((k+1)^2 / (k(k+2))) = log_2(prod_k (k+1)^2 / (k(k+2)))
//    = log_2(lim_N (N+1)^2 / (2 * N(N+2) / 1)) = log_2(infinity / ... )
//    Actually telescoping: prod_k=1^N (k+1)^2/(k(k+2)) = (2*3*...*(N+1))^2 / (1*N! * 3*4*...*(N+2))
//    = ((N+1)!/1)^2 / (N! * (N+2)!/2) = ((N+1)! * 2) / (N! * (N+2))
//    = 2*(N+1)/(N+2) -> 2 as N -> infinity. log_2(2) = 1. So sum -> 1.
// ============================================================================
console.log('\n5. Gauss-Kuzmin distribution.');

function gkProb(k) { return Math.log2((k + 1) * (k + 1) / (k * (k + 2))); }

{
  const p1 = gkProb(1), p2 = gkProb(2), p3 = gkProb(3);
  ok(close(p1, 0.41503749927884, 1e-10), `P(a_1=1) = log_2(4/3) = ${p1.toFixed(10)}`);
  ok(close(p2, 0.16992500144231, 1e-10), `P(a_1=2) = log_2(9/8) = ${p2.toFixed(10)}`);
  ok(close(p3, 0.09310940439148, 1e-10), `P(a_1=3) = log_2(16/15) = ${p3.toFixed(10)}`);
  ok(p1 > 0.41, `~41.5% of Gauss-measure samples have a_1 = 1; uniform samples give 50%`);

  // Total probability for k=1..50000 sums to ~1.
  let total = 0;
  for (let k = 1; k <= 50000; k++) total += gkProb(k);
  ok(total > 0.9985 && total < 1.0001, `sum_{k=1}^{50000} GK(k) = ${total.toFixed(6)} (-> 1 as N -> infinity)`);
}

// ============================================================================
// 6. THE FORMULA log K_0 = sum log(k) * log_2((k+1)^2/(k(k+2))) (Claim G).
//    Numerical convergence to log(K_0).
// ============================================================================
console.log('\n6. log K_0 = sum_k log(k) * GK(k).');

function logKhinchinSum(N) {
  let s = 0;
  for (let k = 1; k <= N; k++) s += Math.log(k) * gkProb(k);
  return s;
}

{
  const lk100 = logKhinchinSum(100);
  const lk1000 = logKhinchinSum(1000);
  const lk10000 = logKhinchinSum(10000);
  ok(Math.abs(lk10000 - LOG_K0) < 0.01, `sum to N=10000: log K = ${lk10000.toFixed(6)} (target ${LOG_K0.toFixed(6)})`);
  // This compares finite partial sums; it does not measure a per-real rate.
  const errs = [Math.abs(lk100 - LOG_K0), Math.abs(lk1000 - LOG_K0), Math.abs(lk10000 - LOG_K0)];
  ok(errs[2] < errs[0], `convergence monotone-ish: 100->${errs[0].toExponential(2)}, 1000->${errs[1].toExponential(2)}, 10000->${errs[2].toExponential(2)}`);
}

// ============================================================================
// 7. MONTE CARLO (Claim C): for random uniform reals in (0,1), the running
//    geometric mean of CF coefficients approaches K_0 as the number of
//    coefficients grows.
//
//    This finite simulation does not establish a convergence rate for an
//    individual real. The averaged variables log(a_i) have finite variance.
// ============================================================================
console.log('\n7. Monte Carlo: random reals, geometric mean of CF.');

// PCG-style RNG so the Monte Carlo is reproducible.
function mulberry32(seed) {
  let a = seed >>> 0;
  return function () {
    a = (a + 0x6D2B79F5) >>> 0;
    let t = a;
    t = Math.imul(t ^ (t >>> 15), t | 1);
    t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
    return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
  };
}

// CF of a real in (0,1) using doubles; lossy past about 20-30 terms but
// fine for population statistics. For per-number CF beyond 30 terms we'd
// need arbitrary precision (the page uses a high-precision Stern-Brocot-
// style algorithm; the test here is a population claim, not per-number).
function cfFromDoubleLossy(x, maxTerms) {
  const out = [];
  for (let i = 0; i < maxTerms; i++) {
    if (!isFinite(x) || x <= 0) break;
    const a = Math.floor(x);
    out.push(a);
    x = 1 / (x - a);
    if (x > 1e15) break; // numerical death — stop here
  }
  return out;
}

{
  const rng = mulberry32(0xC0FFEE);
  const M = 5000;        // number of samples
  const K_TERMS = 24;    // CF terms per sample (truncated; doubles only)
  let sumGM = 0;
  let inside = 0;
  for (let m = 0; m < M; m++) {
    const x = rng();
    const cf = cfFromDoubleLossy(x, K_TERMS + 1);
    if (cf.length < K_TERMS + 1) continue;
    const gm = geomMeanCF(cf);
    if (isFinite(gm)) {
      sumGM += gm;
      if (gm > 1 && gm < 50) inside++;
    }
  }
  const meanGM = sumGM / inside;
  // The MEAN of the per-sample GMs (each at 24 terms) lies near K_0, but is
  // a biased estimator of K_0 because the GM at finite n is biased upward
  // for the right-skewed Gauss-Kuzmin distribution. Allow a wide band.
  ok(meanGM > 2.0 && meanGM < 8.0, `mean GM across ${M} samples, 24 CF terms each = ${meanGM.toFixed(3)} (compatible with K_0 ~ ${K0.toFixed(3)})`);
  ok(meanGM > K0 - 1.0, `the empirical sample mean is in the right neighborhood of K_0`);
}

// ============================================================================
// 8. ASYMPTOTIC RATE (sanity check).
//    This one finite sample supplies several prefix means; it proves no
//    asymptotic rate. In particular, it cannot exclude a square-root-n
//    fluctuation scale for the logarithmic average.
// ============================================================================
console.log('\n8. A finite sample of running geometric means.');

{
  // Pull one specific seed and watch the running GM stabilize.
  const rng = mulberry32(0x1234);
  const x = rng();
  const cf = cfFromDoubleLossy(x, 30);
  const gms = [];
  for (let n = 5; n <= cf.length - 1; n += 5) {
    gms.push(geomMeanCF(cf.slice(0, n + 1)));
  }
  ok(gms.length >= 3, `sampled per-prefix GMs: ${gms.map(g => g.toFixed(3)).join(' -> ')}`);
}

// ============================================================================
// 9. THE COMPLETENESS OF DIVERGENCE for e (Claim D, the explicit story).
//    Prove the asymptotic formula: GM(e, after 3k CF terms) ~ ((2k)!! / 1)^(1/(3k))
//    and that this -> infinity. (Pen-and-paper supporting the page's claim.)
// ============================================================================
console.log('\n9. e\'s GM grows -- the structure breaks Khinchin in the diverging direction.');

{
  // For e's CF [2; 1, 2, 1, 1, 4, 1, 1, 6, ...], after 3k coefficients past a_0:
  //   product = 1 * 2k     [k blocks of (1, 2j, 1) contribute 2j each]
  //   GM = (product)^(1/(3k))
  //   For k=1: 2^(1/3) ~ 1.260
  //   For k=2: (2*4)^(1/6) = 8^(1/6) ~ 1.414
  //   For k=10: (2*4*..*20)^(1/30) = (2^10 * 10!)^(1/30)
  for (const k of [1, 2, 5, 10, 20]) {
    let logP = 0;
    for (let j = 1; j <= k; j++) logP += Math.log(2 * j);
    const gm = Math.exp(logP / (3 * k));
    console.log(`     k=${String(k).padStart(2, ' ')}, n=${3 * k}: GM(e) approaches ${gm.toFixed(4)}`);
  }
  const big = Math.exp([...Array(100)].reduce((s, _, j) => s + Math.log(2 * (j + 1)), 0) / 300);
  ok(big > 3.0, `GM(e) after 300 CF terms ~ ${big.toFixed(3)} (continues to grow)`);
  ok(big > K0, `the divergence is real: at 300 terms GM(e) > K_0`);
}

// ============================================================================
// 10. SCOPE NOTES. Pi, ln(2), and gamma remain unresolved. Explicitly
//     constructed continued fractions can have limiting mean K_0. These
//     notes record that scope; the unconditional checks are not proofs.
//     Source: Wieting, A Khinchin Sequence, pp. 1 and 7.
// ============================================================================
console.log('\n10. Scope notes: unresolved presets and explicit constructions.');

ok(true, 'pi:  empirically consistent with K_0; convergence NOT proven');
ok(true, 'ln 2: empirically consistent with K_0; convergence NOT proven');
ok(true, 'gamma (Euler-Mascheroni): empirically consistent; NOT proven');
ok(true, 'scope note: Wieting proves convergence to K_0 for the explicit sequence Z2; pi remains unresolved');

// ============================================================================
// 11. THE FORMULA in disguise: integral form (informational).
//     log K_0 = (1 / log 2) * integral_0^1 log(floor(1/x)) / (1+x) dx.
//     Numerical Simpson check.
// ============================================================================
console.log('\n11. Integral form of log K_0.');

{
  // Integrate log(floor(1/x)) / (1+x) dx over [0, 1] — but the integrand has
  // a 1/x-type singularity at x->0 (where floor(1/x) blows up). Use a
  // refined Simpson on [eps, 1] plus correction for the tail.
  function integrand(x) { return Math.log(Math.floor(1 / x)) / (1 + x); }
  function simpson(f, a, b, n) {
    const h = (b - a) / n; let s = f(a) + f(b);
    for (let i = 1; i < n; i++) s += (i % 2 ? 4 : 2) * f(a + i * h);
    return (h / 3) * s;
  }
  // Adaptive: piecewise Simpson on [1/N, 1] for large N, sum partial tails.
  let logK = 0;
  const N = 200000;
  // Direct sum: for each k, integrate over (1/(k+1), 1/k] where floor(1/x)=k.
  // log K_0 = (1 / log 2) * sum_{k=1}^infty log(k) * (log((k+1)/k) - log((k+2)/(k+1)))
  //         = (1 / log 2) * sum_{k=1}^infty log(k) * log((k+1)^2 / (k(k+2)))
  // - so the integral form REDUCES to the GK sum (Claim G). Verify equivalence.
  for (let k = 1; k <= N; k++) {
    logK += Math.log(k) * (Math.log((k + 1) / k) - Math.log((k + 2) / (k + 1)));
  }
  logK /= Math.log(2);
  // log_2((k+1)^2 / (k(k+2))) = log_2((k+1)/k) - log_2((k+2)/(k+1)).
  ok(Math.abs(logK - LOG_K0) < 0.005, `integral form (via direct interval sum, N=${N}): log K = ${logK.toFixed(6)} (target ${LOG_K0.toFixed(6)})`);
}

// ============================================================================
// 12. CONVERGENTS for the BROWSER instrument: the page draws live convergents
//     p_n/q_n of the CF for an entered number. We verify the recurrence
//     against textbook values for pi.
// ============================================================================
console.log('\n12. Convergents recurrence (for the page\'s live readout).');

function convergents(cf) {
  // Standard recurrence: h_{-1}=1, h_0=a_0, k_{-1}=0, k_0=1.
  //   h_n = a_n * h_{n-1} + h_{n-2}
  //   k_n = a_n * k_{n-1} + k_{n-2}
  // All BigInt to keep p_n/q_n exact.
  let h0 = 1n, h1 = BigInt(cf[0]);
  let k0 = 0n, k1 = 1n;
  const out = [[BigInt(cf[0]), 1n]];
  for (let i = 1; i < cf.length; i++) {
    const a = BigInt(cf[i]);
    const h = a * h1 + h0; const k = a * k1 + k0;
    out.push([h, k]); h0 = h1; h1 = h; k0 = k1; k1 = k;
  }
  return out;
}

{
  // pi's leading convergents: 3, 22/7, 333/106, 355/113, 103993/33102, ...
  // (OEIS: A002485 / A002486.)
  const cv = convergents(CF_PI.slice(0, 6));
  ok(cv[0][0] === 3n && cv[0][1] === 1n, `pi convergent 1: 3/1`);
  ok(cv[1][0] === 22n && cv[1][1] === 7n, `pi convergent 2: 22/7 (Archimedes)`);
  ok(cv[2][0] === 333n && cv[2][1] === 106n, `pi convergent 3: 333/106`);
  ok(cv[3][0] === 355n && cv[3][1] === 113n, `pi convergent 4: 355/113 (Zu Chongzhi, 5th c.)`);
  ok(cv[4][0] === 103993n && cv[4][1] === 33102n, `pi convergent 5: 103993/33102`);
}

// ============================================================================
// REPORT
// ============================================================================
console.log(`\n${fails === 0 ? 'ALL PASS' : 'FAIL'} -- ${checks} checks, ${fails} failures`);
process.exit(fails === 0 ? 0 : 1);
