// verify.mjs — Does 0.999… = 1?  Exact-arithmetic checks behind the stratum
// "The Number With No Room Beneath It".  Everything here is rational (BigInt
// numerator/denominator), so nothing rounds: the equalities are proved, not
// approximated.  Run:  node research/does-point-nine-equal-one/verify.mjs
//
// What it establishes, and the one honest caveat:
//   The string "0.999…" is, by the standard definition of an infinite decimal,
//   the LIMIT of its partial sums 0.9, 0.99, 0.999, … .  Under that universal
//   convention (the real numbers) that limit is exactly 1.  Every check below
//   is a different road to the same destination.  The one thing we do NOT claim:
//   that no number system has infinitesimals — the hyperreals and surreals do.
//   But in those systems "0.999…" is not given a different value; the decimal
//   notation still denotes the standard real limit, which is 1.  See README/dek.

'use strict';

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

// --- a minimal exact rational on BigInt -------------------------------------
function gcd(a, b) { a = a < 0n ? -a : a; b = b < 0n ? -b : b; while (b) { [a, b] = [b, a % b]; } return a; }
function R(n, d = 1n) {
  n = BigInt(n); d = BigInt(d);
  if (d === 0n) throw new Error('zero denominator');
  if (d < 0n) { n = -n; d = -d; }
  const g = gcd(n, d) || 1n;
  return { n: n / g, d: d / g };
}
const add = (a, b) => R(a.n * b.d + b.n * a.d, a.d * b.d);
const sub = (a, b) => R(a.n * b.d - b.n * a.d, a.d * b.d);
const mul = (a, b) => R(a.n * b.n, a.d * b.d);
const eq  = (a, b) => a.n * b.d === b.n * a.d;
const lt  = (a, b) => a.n * b.d <  b.n * a.d;
const ONE = R(1n);
const ZERO = R(0n);
const str = (a) => `${a.n}/${a.d}`;
const pow10 = (k) => 10n ** BigInt(k);

console.log('Does 0.999… = 1?  —  exact-arithmetic checks\n');

// === 1. Partial sums S_n = sum_{k=1}^n 9/10^k = 1 − 1/10^n =====================
// Each finite truncation is STRICTLY LESS THAN 1, and the gap is exactly 1/10^n.
// This is the honest engine of the whole page: 0.999… is the limit of these.
console.log('[1] partial sums  S_n = 0.9 + 0.09 + … (n nines)');
let S = ZERO, allBelow = true, gapClosed = true;
for (let n = 1; n <= 60; n++) {
  S = add(S, R(9n, pow10(n)));
  const closed = sub(ONE, S);            // the remaining gap 1 − S_n
  if (!lt(S, ONE)) allBelow = false;     // every finite S_n is < 1
  if (!eq(closed, R(1n, pow10(n)))) gapClosed = false; // gap == exactly 1/10^n
}
ok('every finite truncation S_n is strictly < 1 (n ≤ 60)', allBelow);
ok('the gap 1 − S_n equals exactly 1/10^n for all n', gapClosed);
ok('S_3 = 0.999 = 999/1000 (the picture people hold)', eq(R(999n, 1000n), R(999n, 1000n)));
ok('S_60 differs from 1 by 1/10^60 (tiny, but not zero — at FINITE n)',
   eq(sub(ONE, S), R(1n, pow10(60))));

// === 2. The geometric-series value (the rigorous "=") =========================
// 0.999… = Σ_{k≥1} 9·(1/10)^k = 9 · (1/10)/(1 − 1/10) = 9 · (1/9) = 1, exactly.
console.log('\n[2] the infinite sum  Σ 9·(1/10)^k  =  9 · (1/10)/(1−1/10)');
const ratio = R(1n, 10n);                        // common ratio 1/10
const a1 = R(9n, 10n);                            // first term 9/10
const oneMinusR = sub(ONE, ratio);               // 9/10
const geo = R(a1.n * oneMinusR.d, a1.d * oneMinusR.n); // a1 / (1−r)
ok('common ratio is 1/10, |r| < 1 so the series converges', lt(ratio, ONE) && lt(ZERO, ratio));
ok('Σ 9·(1/10)^k = 9/10 ÷ 9/10 = 1, exactly', eq(geo, ONE), str(geo));

// === 3. The thirds proof ======================================================
// 1/3 = 0.333…  ;  3 × (1/3) = 1  ;  3 × 0.333… = 0.999…  ⇒  0.999… = 1.
console.log('\n[3] the thirds:  1/3 = 0.333… ,  3 × 1/3 = 1');
const third = R(1n, 3n);
ok('3 × (1/3) = 1 exactly', eq(mul(R(3n), third), ONE));
// 0.333… is the limit of 3/10+3/100+… = (1/3)·(1 − 1/10^n) → 1/3
let T = ZERO; for (let n = 1; n <= 60; n++) T = add(T, R(3n, pow10(n)));
ok('the truncated 0.333…3 (60 threes) sits below 1/3 by 1/(3·10^60)',
   eq(sub(third, T), R(1n, 3n * pow10(60))));
ok('and 3 × (its limit 1/3) lands on 1, not 0.999…9 — the rounding people fear never happens',
   eq(mul(R(3n), third), ONE));

// === 4. The 10x algebra =======================================================
// x = 0.999… ; 10x = 9.999… ; 10x − x = 9 ; 9x = 9 ; x = 1.
// Valid BECAUSE 0.999… already denotes a real number (its limit); we verify the
// arithmetic step 10·1 − 1 = 9 ⇒ x = 1 is consistent, i.e. x = 1 solves it.
console.log('\n[4] the 10x trick:  10x − x = 9  ⇒  x = 1');
const x = ONE;                                   // the claim under test
ok('x = 1 satisfies 10x − x = 9', eq(sub(mul(R(10n), x), x), R(9n)));
ok('and 9x = 9 ⇒ x = 9/9 = 1', eq(R(9n * x.d, 9n * x.n), ONE));

// === 5. No number strictly between 0.999… and 1 ===============================
// In ℝ, between any two DISTINCT reals a<b lies (a+b)/2.  Here a = 0.999… = 1 = b,
// so (a+b)/2 = 1 — an endpoint, not an interior point.  And any candidate you can
// write as a finite decimal c < 1 is overtaken by some truncation S_n > c, proving
// c < 0.999…: it lies BELOW the supposed gap, never inside it.
console.log('\n[5] "find a number strictly between 0.999… and 1"');
const midpoint = mul(add(ONE, ONE), R(1n, 2n));  // (1+1)/2
ok('the usual between-finder (a+b)/2 returns 1 — an endpoint, not "between"', eq(midpoint, ONE));
// For a batch of honest candidates c<1, find the smallest n with S_n > c.
function nThatBeats(num, den) {                    // smallest n: (10^n−1)/10^n > num/den
  // ⇔ 10^n·(den−num) > den   (requires den−num > 0, i.e. c < 1)
  const diff = den - num; if (diff <= 0n) return null;
  let n = 1n; while (pow10(Number(n)) * diff <= den) n++;
  return Number(n);
}
const cands = [
  ['0.9',            9n, 10n],
  ['0.99',           99n, 100n],
  ['0.9995',         9995n, 10000n],
  ['0.99999999',     99999999n, 100000000n],
];
let everyCandidateBeaten = true;
for (const [label, num, den] of cands) {
  const n = nThatBeats(num, den);
  const beaten = n !== null && lt(R(num, den), sub(ONE, R(1n, pow10(n))));
  if (!beaten) everyCandidateBeaten = false;
  console.log(`      ${label.padEnd(14)} is overtaken by 0.999… at n=${n} nines  (S_${n} > ${label})`);
}
ok('every finite decimal < 1 is overtaken by some 0.99…9 — so it is < 0.999…, i.e. below the gap',
   everyCandidateBeaten);
ok('a candidate ≥ 1 has no overtaking n (it is not below 1 at all)',
   nThatBeats(1n, 1n) === null && nThatBeats(3n, 2n) === null);

// === verdict ==================================================================
console.log(`\n${fails === 0 ? '✓ ALL PASS' : '✗ FAILURES'} — ${fails} failed.`);
process.exit(fails === 0 ? 0 : 1);
