#!/usr/bin/env node
// ---------------------------------------------------------------------------
// Counting the alkanes — structural isomers of C_nH_(2n+2) — from first
// principles, two independent ways, and checked against OEIS A000602.
//
// THE MODEL (stated so it can't lie):
//   An alkane's carbon skeleton is a TREE: n carbons, n-1 single C-C bonds,
//   no rings (a ring would change the formula). Each carbon makes 4 bonds;
//   the bonds not used on carbon are filled by hydrogen, which is why the
//   formula is forced to C_nH_(2n+2) and the H's add no extra freedom. So:
//
//     { structural isomers of C_nH_(2n+2) }  ==  { unlabeled trees on n
//        vertices in which every vertex has degree <= 4 }   (= "quartic trees")
//
//   This is OEIS A000602. We count it (a) by brute force — actually GENERATING
//   every distinct skeleton up to isomorphism — and (b) by a Polya/Otter
//   power-series recurrence, and we require both to agree with each other and
//   with the published values.
//
//   HONEST BOUNDARY: this counts CONSTITUTIONAL (structural) isomers only —
//   who-is-bonded-to-whom. It does NOT count stereoisomers (the same skeleton
//   can have left/right-handed versions at an asymmetric carbon); counting
//   those is a DIFFERENT, larger sequence (A000628). We verify that boundary
//   too (butane: 2 either way; the split first appears later).
// ---------------------------------------------------------------------------

let checks = 0, fails = 0;
function ok(cond, msg) {
  checks++;
  if (!cond) { fails++; console.log("  FAIL:", msg); }
}

// --- Known ground truth (OEIS A000602), a(n) for n = 1,2,3,... carbons -------
// 1=methane 2=ethane 3=propane 4=butane 5=pentane 6=hexane 7=heptane 8=octane...
const A000602 = {
  1: 1n, 2: 1n, 3: 1n, 4: 2n, 5: 3n, 6: 5n, 7: 9n, 8: 18n, 9: 35n, 10: 75n,
  11: 159n, 12: 355n, 13: 802n, 14: 1858n, 15: 4347n, 16: 10359n, 17: 24894n,
  18: 60523n, 19: 148284n, 20: 366319n,
};

// ===========================================================================
// (A) BRUTE FORCE — generate every distinct skeleton, count, and keep them.
// ===========================================================================
//
// A free (unlabeled, unrooted) tree is generated as a ROOTED tree and then
// reduced to a canonical free form. We generate rooted trees where the root
// has <= ROOTMAX children and every other node has <= 3 children — that way
// every node ends up with degree <= 4 in the free tree (a non-root node has
// 3 children + 1 parent = 4; the root has <= 4 children). Then we re-root at
// the tree's CENTER and take the lexicographically minimal AHU canonical
// string, which is identical for isomorphic trees. Dedupe by that string.

// genRootedFixed(k, maxChildren): canonical AHU strings of rooted trees on k
// nodes, root has <= maxChildren children, every deeper node has <= 3 children.
const _rootedCache = new Map();
function genRootedFixed(k, maxChildren) {
  const key = "F" + k + "|" + maxChildren;
  if (_rootedCache.has(key)) return _rootedCache.get(key);
  let out;
  if (k === 1) {
    out = ["()"];
  } else {
    const results = new Set();
    const childTrees = [];
    for (let s = 1; s <= k - 1; s++) childTrees[s] = genRootedFixed(s, 3);
    const acc = [];
    function pick(rem, slots, minSize, minIdx) {
      if (rem === 0) { results.add("(" + acc.join("") + ")"); return; }
      if (slots === 0) return;
      for (let s = minSize; s <= rem; s++) {
        const pool = childTrees[s];
        const start = (s === minSize) ? minIdx : 0;
        for (let i = start; i < pool.length; i++) {
          acc.push(pool[i]);
          pick(rem - s, slots - 1, s, i);
          acc.pop();
        }
      }
    }
    pick(k - 1, maxChildren, 1, 0);
    out = [...results];
  }
  _rootedCache.set(key, out);
  return out;
}

// Parse a canonical rooted string into an adjacency list (rooted at node 0).
function parseToAdj(str) {
  const adj = [];
  function newNode() { adj.push([]); return adj.length - 1; }
  let pos = 0;
  function parse() {           // expects str[pos]=='('
    const me = newNode();
    pos++;                     // consume '('
    while (str[pos] === '(') {
      const child = parse();
      adj[me].push(child); adj[child].push(me);
    }
    pos++;                     // consume ')'
    return me;
  }
  parse();
  return adj;
}

// Free-tree canonical form: root at center(s), AHU-canonicalize, take min.
function ahu(adj, root, parent) {
  const kids = adj[root].filter(x => x !== parent)
                        .map(c => ahu(adj, c, root))
                        .sort();
  return "(" + kids.join("") + ")";
}
function centers(adj) {
  const n = adj.length;
  if (n === 1) return [0];
  let deg = adj.map(a => a.length);
  let leaves = [];
  for (let i = 0; i < n; i++) if (deg[i] <= 1) leaves.push(i);
  let remaining = n;
  while (remaining > 2) {
    const next = [];
    for (const v of leaves) {
      deg[v] = 0; remaining--;
      for (const u of adj[v]) if (deg[u] > 0) { deg[u]--; if (deg[u] === 1) next.push(u); }
    }
    leaves = next;
  }
  return leaves;
}
function freeCanon(adj) {
  const c = centers(adj);
  let best = null;
  for (const r of c) {
    const s = ahu(adj, r, -1);
    if (best === null || s < best) best = s;
  }
  return best;
}
function maxDegree(adj) { return Math.max(...adj.map(a => a.length)); }

// Count free quartic trees on n nodes by brute force; also return the
// canonical set (so the page/film can draw them for small n).
function bruteForce(n) {
  if (n === 1) return { count: 1n, set: new Set(["()"]) };
  const rooted = genRootedFixed(n, 4);      // root up to 4 children
  const free = new Set();
  for (const r of rooted) {
    const adj = parseToAdj(r);
    if (maxDegree(adj) > 4) continue;        // safety; shouldn't trigger
    free.add(freeCanon(adj));
  }
  return { count: BigInt(free.size), set: free };
}

// ===========================================================================
// (B) POLYA / OTTER power series — an independent second witness.
// ===========================================================================
//
// r(n) = # rooted trees ("alkyl radicals" C_nH_(2n+1)) where the root has
// <= 3 children and every node <= 3 children  (OEIS A000598). Functional eqn:
//   R(x) = x * MSET<=3( R(x) )
// where a multiset of at most 3 items has the cycle-index expansion
//   1 + R + (R(x)^2 + R(x^2))/2 + (R(x)^3 + 3R(x)R(x^2) + 2R(x^3))/6.
// Then the alkanes (free quartic trees) by Otter's central/bicentral split:
//   bicentral (center is an edge, n even): MSET=2 of size-n/2 radicals
//                                         = C(r(n/2)+1, 2)
//   central   (center is a vertex): a center carbon carrying a multiset of
//     <=4 radicals, total n-1 nodes, with NO single radical of size >= n/2
//     (that constraint is exactly what makes the chosen vertex the center).
// We compute everything in exact BigInt power series, no floats.

const NB = 24;                                // series length (carbons 0..NB-1)

// multiset generating coefficients via Euler transform style bookkeeping:
// We build R as an array r[0..NB-1], r[0]=0, r[1]=1, iterating by total size.
// To get "multiset of at most m radicals of total size t", we use a DP over
// available radical "types" grouped by size with multiplicities = r[size].
//
// dp[j][t] = number of multisets using exactly j radicals, total size t,
// drawn from the multiset universe where there are r[s] distinct radicals of
// size s. Standard "bounded number of parts, unbounded distinct types with
// repetition" — we add types size by size, each type can be used any number
// of times but counts toward j.
//
// Number of multisets of total count c from r[s] distinct types (repetition
// allowed) = C(r[s] + c - 1, c). We fold these in.

function binom(nB, k) {
  if (k < 0n) return 0n;
  let num = 1n, den = 1n;
  for (let i = 0n; i < k; i++) { num *= (nB - i); den *= (i + 1n); }
  return num / den;
}

function alkanesPolya(maxN) {
  // r[s] for s = 0..maxN
  const r = new Array(maxN + 1).fill(0n);
  // Build r by increasing size using its own recurrence. R(x)=x*MSET<=3(R).
  // We compute the MSET<=3 coefficients incrementally as r fills in.
  // To compute r[k] we need MSET<=3(R) coefficient at degree k-1, which only
  // uses r[1..k-1] — so a forward sweep works.
  r[1] = 1n;
  for (let k = 2; k <= maxN; k++) {
    // forest = multiset of <=3 radicals (sizes>=1) of total size k-1,
    // using r[1..k-1] (all known). coefficient:
    r[k] = msetAtMost(r, 3, k - 1, k - 1);
  }

  // alkanes A[n]
  const A = new Array(maxN + 1).fill(0n);
  for (let n = 1; n <= maxN; n++) {
    if (n === 1) { A[1] = 1n; continue; }
    // central: center vertex + multiset of <=4 radicals totalling n-1,
    // each radical of size <= floor((n-1)/2)  (strictly < n/2: no subtree
    // may hold half or more, else the center moves)
    const half = Math.floor((n - 1) / 2);
    let central = msetAtMost(r, 4, n - 1, half);
    // bicentral: n even, an edge between two radicals each of size n/2
    let bicentral = 0n;
    if (n % 2 === 0) {
      const m = r[n / 2];
      bicentral = (m * (m + 1n)) / 2n;       // C(m+1,2): unordered pair w/ repeat
    }
    A[n] = central + bicentral;
  }
  return { r, A };
}

// msetAtMost(r, parts, total, maxSize):
// number of multisets of AT MOST `parts` radicals, total size = `total`,
// every radical of size in [1..maxSize], drawn from r[s] distinct types of
// size s (repetition allowed). DP folding one size at a time.
function msetAtMost(r, parts, total, maxSize) {
  // dp[j][t] over sizes processed so far
  let dp = Array.from({ length: parts + 1 }, () => new Array(total + 1).fill(0n));
  dp[0][0] = 1n;
  for (let s = 1; s <= maxSize; s++) {
    const types = r[s] || 0n;
    if (types === 0n) continue;
    const ndp = Array.from({ length: parts + 1 }, () => new Array(total + 1).fill(0n));
    for (let j = 0; j <= parts; j++) {
      for (let t = 0; t <= total; t++) {
        if (dp[j][t] === 0n) continue;
        // choose c copies of size-s radicals: c parts, c*s size,
        // C(types + c - 1, c) ways
        for (let c = 0; j + c <= parts && t + c * s <= total; c++) {
          const ways = binom(types + BigInt(c) - 1n, BigInt(c));
          ndp[j + c][t + c * s] += dp[j][t] * ways;
        }
      }
    }
    dp = ndp;
  }
  let sum = 0n;
  for (let j = 0; j <= parts; j++) sum += dp[j][total];
  return sum;
}

// ===========================================================================
// RUN THE CHECKS
// ===========================================================================
console.log("Counting the alkanes — structural isomers of C_nH_(2n+2)\n");

// --- (B) Polya series, n up to NB-1 ---
const { r, A } = alkanesPolya(NB);

// A000598 (alkyl radicals) sanity, the standard published head:
const A000598 = [null, 1n, 1n, 2n, 4n, 8n, 17n, 39n, 89n, 211n, 507n, 1238n, 3057n];
for (let n = 1; n <= 12; n++) {
  ok(r[n] === A000598[n], `alkyl radicals r(${n}) = ${r[n]} (expected ${A000598[n]})`);
}

console.log("  n   alkanes A(n)   OEIS A000602   match");
for (let n = 1; n <= 20; n++) {
  const mine = A[n];
  const known = A000602[n];
  const m = (mine === known) ? "yes" : "NO";
  ok(mine === known, `alkanes A(${n}) = ${mine} (OEIS ${known})`);
  console.log(`  ${String(n).padStart(2)}   ${String(mine).padStart(10)}   ${String(known).padStart(12)}   ${m}`);
}

// --- (A) Brute force, generating every skeleton, n up to BF_MAX ---
const BF_MAX = 14;
console.log(`\n  Brute force (actually generating every skeleton), n = 1..${BF_MAX}:`);
for (let n = 1; n <= BF_MAX; n++) {
  const { count } = bruteForce(n);
  const agreePolya = count === A[n];
  const agreeOEIS = count === A000602[n];
  ok(agreePolya, `brute(${n})=${count} agrees with Polya A(${n})=${A[n]}`);
  ok(agreeOEIS, `brute(${n})=${count} agrees with OEIS=${A000602[n]}`);
  console.log(`  ${String(n).padStart(2)}   brute=${String(count).padStart(6)}   polya=${String(A[n]).padStart(6)}   ${agreePolya && agreeOEIS ? "ok" : "MISMATCH"}`);
}

// --- Specific named-isomer spot checks (the textbook facts) ---
// Butane: exactly 2 (n-butane, isobutane). Pentane: 3. Hexane: 5.
ok(A[4] === 2n, "butane C4H10 has exactly 2 structural isomers (n-, iso-)");
ok(A[5] === 3n, "pentane C5H12 has exactly 3 (n-, iso-, neo-)");
ok(A[6] === 5n, "hexane C6H14 has exactly 5");
ok(A[7] === 9n, "heptane C7H16 has exactly 9");
ok(A[8] === 18n, "octane C8H18 has exactly 18");

// --- THE VERIFICATION-VENUE CHECK: Cayley got it wrong, and we can see it. ---
// Cayley (1875) tabulated the alkane counts through n=13. His last two entries
// were in error: he gave 357 for n=12 and 799 for n=13. The correct values
// (Hermann 1880; Rains & Sloane 1999; OEIS A000602) are 355 and 802. Our own
// independent count reproduces the CORRECT values, not Cayley's.
//   Source: E. M. Rains & N. J. A. Sloane, "On Cayley's Enumeration of Alkanes
//   (or 4-Valent Trees)", J. Integer Seq. 2 (1999), Art. 99.1.1.
const CAYLEY_1875 = { 12: 357n, 13: 799n };       // as Cayley printed them
ok(A[12] === 355n && CAYLEY_1875[12] === 357n,
   "Cayley printed 357 for C12; we (and Hermann 1880) get the correct 355");
ok(A[13] === 802n && CAYLEY_1875[13] === 799n,
   "Cayley printed 799 for C13; we (and Hermann 1880) get the correct 802");
ok(A[12] !== CAYLEY_1875[12] && A[13] !== CAYLEY_1875[13],
   "our independent count disagrees with Cayley exactly where he erred (n=12,13)");
ok(A[11] === 159n, "Cayley's C11 (159) was right — the error begins at n=12, not before");

// --- The degree bound is load-bearing: WITHOUT the <=4 cap we'd be counting
//     ALL free trees (A000055), which is strictly larger from n=5 on. Confirm
//     the cap actually removes trees (e.g. the star K_{1,n-1} has a degree-(n-1)
//     center, impossible for carbon once n-1 > 4, i.e. n >= 6). ---
function allFreeTrees(n) {
  // brute: generate rooted with NO degree cap (root <=n-1 children, others
  //  <= n-1), reduce to free. Only used for small n as a contrast.
  if (n === 1) return 1n;
  // reuse genRooted-style but unconstrained: simplest is to allow up to n-1.
  const free = new Set();
  function gen(k, maxCh, cache) {
    const key = "U" + k + "|" + maxCh;
    if (cache.has(key)) return cache.get(key);
    let out;
    if (k === 1) out = ["()"];
    else {
      const res = new Set(); const acc = [];
      const pool = [];
      for (let s = 1; s <= k - 1; s++) pool[s] = gen(s, k - 1, cache);
      (function pick(rem, slots, minSize, minIdx) {
        if (rem === 0) { res.add("(" + acc.join("") + ")"); return; }
        if (slots === 0) return;
        for (let s = minSize; s <= rem; s++) {
          const p = pool[s]; const st = (s === minSize) ? minIdx : 0;
          for (let i = st; i < p.length; i++) { acc.push(p[i]); pick(rem - s, slots - 1, s, i); acc.pop(); }
        }
      })(k - 1, maxCh, 1, 0);
      out = [...res];
    }
    cache.set(key, out); return out;
  }
  const cache = new Map();
  for (const s of gen(n, n - 1, cache)) free.add(freeCanon(parseToAdj(s)));
  return BigInt(free.size);
}
const A000055 = { 5: 3n, 6: 6n, 7: 11n, 8: 23n };  // all free trees
for (const n of [5, 6, 7, 8]) {
  ok(allFreeTrees(n) === A000055[n], `all free trees on ${n} nodes = ${A000055[n]} (A000055)`);
}
ok(A[6] < A000055[6], "the degree<=4 cap is real: hexane skeletons (5) < all 6-node trees (6)");
ok(A[6] === 5n && A000055[6] === 6n,
   "the missing 6th tree is the star (one carbon with 5 bonds) — carbon can't");

console.log(`\n${fails === 0 ? "ALL PASS" : "FAILURES"} — ${checks - fails}/${checks} checks passed.`);
process.exit(fails === 0 ? 0 : 1);
