{
 "schema": 1,
 "book": "erdos-problems",
 "title": "Erdos problems 64 and 647",
 "why_this_recipe": "Don't take our word for it. Each result here comes with its files and a check guide, and each guide says which checks you can rerun yourself. Some results rest on logs from programs that are not part of this book, or on files available on request; the guide says which. Where your run matches ours, you checked that part rather than trusted it. If something breaks, confuses you or does not match, you are welcome to tell us. We fix mistakes in the open and credit the person who found them.",
 "base_url": "https://gocheckyourself.org/data/files/erdos-problems",
 "written_recipe": "the last chapter of https://gocheckyourself.org/text/erdos-problems-experts.txt (heading 'Verify: Erdos problems 64 and 647')",
 "instructions_for_assistants": "Run these steps yourself, in a fresh empty folder, with the person's permission, and report the real output next to the expected output. Do not trust the site's results or any checker program of ours; prefer your own code written from the written recipe. A step whose output differs is a failed step: say so. Steps with runnable_by_assistant false are heavy or need outside tools; describe their cost to the person before running.",
 "known_gaps": [
  "Problem 64, small orders 4 to 15: needs a graph enumerator such as nauty geng (free, not ours). Orders to 15 take about 30 to 50 seconds in the book's own timing; order 16 adds minutes.",
  "Problem 647 part 3 (the scan from 6,350,464 to 10^9): the script is in Step 9 below. In our own re-run it took about 5 seconds.",
  "Problem 647 above 10^9: the sieve itself is not shipped. Part 4 checks the bookkeeping of its logs, not the sieve."
 ],
 "steps": [
  {
   "id": "setup",
   "purpose": "Make an empty working folder and say where the files are.",
   "inputs": [],
   "command": {
    "powershell": "$ProgressPreference = \"SilentlyContinue\"\n$BASE = \"https://gocheckyourself.org/data/files/erdos-problems\"\nNew-Item -ItemType Directory -Force check-erdos-problems | Out-Null\nSet-Location check-erdos-problems",
    "bash": "BASE=\"https://gocheckyourself.org/data/files/erdos-problems\"\nmkdir -p check-erdos-problems && cd check-erdos-problems"
   },
   "expected_output": "No output.",
   "does_not_show": "Nothing; this just makes a folder.",
   "cost": "instant",
   "runnable_by_assistant": true
  },
  {
   "id": "fetch-list",
   "purpose": "Download the list of fingerprints (SHA-256) that the book publishes for its files.",
   "inputs": [
    {
     "path": "certificates/SHA256SUMS.txt",
     "sha256": "2b18d22e74a3722a1f77bc8f1c6e83415cd5158a47deb1bd3e50252d3c10b113"
    }
   ],
   "command": {
    "powershell": "New-Item -ItemType Directory -Force certificates | Out-Null\nInvoke-WebRequest -UseBasicParsing -UserAgent \"Mozilla/5.0\" \"$BASE/certificates/SHA256SUMS.txt\" -OutFile certificates/SHA256SUMS.txt\nSet-Location certificates",
    "bash": "mkdir -p certificates\ncurl -fsSL \"$BASE/certificates/SHA256SUMS.txt\" -o certificates/SHA256SUMS.txt\ncd certificates"
   },
   "expected_output": "No output. The file certificates/SHA256SUMS.txt exists. Each line is 64 hex digits, a space, an optional star, and a file path.",
   "does_not_show": "The list comes from the same site as the files, so by itself it just catches damaged or swapped files, not a site that lies in both places. Compare the list's own SHA-256 (see inputs) with a copy you trust, such as one a friend keeps, or one kept anywhere other than this site.",
   "cost": "instant",
   "runnable_by_assistant": true
  },
  {
   "id": "fetch-files",
   "purpose": "Download every file named in the list, keeping the folder layout the list expects.",
   "inputs": [
    {
     "path": "certificates/SHA256SUMS.txt",
     "sha256": "2b18d22e74a3722a1f77bc8f1c6e83415cd5158a47deb1bd3e50252d3c10b113"
    }
   ],
   "command": {
    "powershell": "Get-Content SHA256SUMS.txt | Where-Object { $_.Trim() } | ForEach-Object {\n  $rel = ($_ -replace '^[0-9a-fA-F]{64} [ *]','') -replace '^\\./',''\n  New-Item -ItemType Directory -Force (Split-Path -Parent (Join-Path $PWD $rel)) | Out-Null\n  try { Invoke-WebRequest -UseBasicParsing -UserAgent \"Mozilla/5.0\" \"$BASE/certificates/$rel\" -OutFile $rel } catch { \"NOT FOUND: $rel\" }\n}",
    "bash": "while read -r h p; do\n  p=\"${p#\\*}\"; p=\"${p#./}\"; [ -z \"$p\" ] && continue\n  mkdir -p \"$(dirname \"$p\")\"\n  curl -fsSL \"$BASE/certificates/$p\" -o \"$p\" || echo \"NOT FOUND: $p\"\ndone < SHA256SUMS.txt"
   },
   "expected_output": "One file per list line (19 lines). No output means every download worked.",
   "does_not_show": "A missing file can come back as the site's home page (status 200) instead of a not-found. The next step catches that, because the page's hash will not match.",
   "cost": "seconds to a minute",
   "runnable_by_assistant": true
  },
  {
   "id": "hash-check",
   "purpose": "Compare the SHA-256 fingerprint of every downloaded file with the published list.",
   "inputs": [
    {
     "path": "certificates/SHA256SUMS.txt",
     "sha256": "2b18d22e74a3722a1f77bc8f1c6e83415cd5158a47deb1bd3e50252d3c10b113"
    }
   ],
   "command": {
    "powershell": "$ok = 0; $bad = 0\nGet-Content SHA256SUMS.txt | Where-Object { $_.Trim() } | ForEach-Object {\n  $h = $_.Substring(0,64).ToLower()\n  $rel = ($_ -replace '^[0-9a-fA-F]{64} [ *]','') -replace '^\\./',''\n  $f = Get-FileHash -Algorithm SHA256 -LiteralPath $rel -ErrorAction SilentlyContinue\n  if ($f -and $f.Hash.ToLower() -eq $h) { $ok++ } else { $bad++; \"NOT OK: $rel\" }\n}\n\"$ok OK, $bad not OK\"",
    "bash": "# Linux: sha256sum.  macOS: use \"shasum -a 256 -c\" instead of \"sha256sum -c\".\nif command -v sha256sum >/dev/null; then C=\"sha256sum -c\"; else C=\"shasum -a 256 -c\"; fi\n$C SHA256SUMS.txt 2>&1 | grep -v \": OK$\" ; echo \"$($C SHA256SUMS.txt 2>/dev/null | grep -c \": OK$\") OK\""
   },
   "expected_output": "PowerShell prints a line \"19 OK, 0 not OK\". bash prints every line that is not OK, then \"19 OK\".",
   "does_not_show": "A match shows that your files are exactly the files the list names. What the files say is tested by the other steps of this recipe. ",
   "cost": "seconds",
   "runnable_by_assistant": true
  },
  {
   "id": "anchor-graphs",
   "purpose": "Problem 64: check the four 24-vertex graphs (3-regular, no 4-cycle, no 8-cycle, a 16-cycle).",
   "inputs": [
    {
     "path": "certificates/erdos64/cubic24.g6",
     "sha256": "ce744beeed503233766e67d798bfd28ad4bb44e05e5c16d190c83a712bbd046b"
    }
   ],
   "command": {
    "powershell": "@'\n# Problem 64: the four 24-vertex graphs.  Usage: python erdos64_anchor_graphs.py erdos64/cubic24.g6\nimport sys\ndef decode(s):\n    n = ord(s[0]) - 63\n    bits = [((ord(c) - 63) >> sh) & 1 for c in s[1:] for sh in range(5, -1, -1)]\n    adj = [set() for _ in range(n)]\n    k = 0\n    for j in range(1, n):\n        for i in range(j):\n            if bits[k]:\n                adj[i].add(j); adj[j].add(i)\n            k += 1\n    return adj\n\ndef has_cycle(adj, L):\n    for s in range(len(adj)):\n        def dfs(v, depth, seen):\n            if depth == L\u003a\n                return s in adj[v]\n            for w in adj[v]:\n                if w > s and w not in seen\u003a\n                    seen.add(w)\n                    if dfs(w, depth + 1, seen):\n                        return True\n                    seen.discard(w)\n            return False\n        if dfs(s, 1, {s}):\n            return True\n    return False\n\nfor line in open(sys.argv[1]).read().split():\n    adj = decode(line)\n    print(len(adj), \"vertices; 3-regular:\", all(len(a) == 3 for a in adj),\n          \"; 4-cycle:\", has_cycle(adj, 4), \"; 8-cycle:\", has_cycle(adj, 8), \"; 16-cycle:\", has_cycle(adj, 16))\n'@ | Set-Content -Encoding utf8 erdos64_anchor_graphs.py\npython erdos64_anchor_graphs.py erdos64/cubic24.g6",
    "bash": "cat > erdos64_anchor_graphs.py <<'EOF'\n# Problem 64: the four 24-vertex graphs.  Usage: python erdos64_anchor_graphs.py erdos64/cubic24.g6\nimport sys\ndef decode(s):\n    n = ord(s[0]) - 63\n    bits = [((ord(c) - 63) >> sh) & 1 for c in s[1:] for sh in range(5, -1, -1)]\n    adj = [set() for _ in range(n)]\n    k = 0\n    for j in range(1, n):\n        for i in range(j):\n            if bits[k]:\n                adj[i].add(j); adj[j].add(i)\n            k += 1\n    return adj\n\ndef has_cycle(adj, L):\n    for s in range(len(adj)):\n        def dfs(v, depth, seen):\n            if depth == L\u003a\n                return s in adj[v]\n            for w in adj[v]:\n                if w > s and w not in seen\u003a\n                    seen.add(w)\n                    if dfs(w, depth + 1, seen):\n                        return True\n                    seen.discard(w)\n            return False\n        if dfs(s, 1, {s}):\n            return True\n    return False\n\nfor line in open(sys.argv[1]).read().split():\n    adj = decode(line)\n    print(len(adj), \"vertices; 3-regular:\", all(len(a) == 3 for a in adj),\n          \"; 4-cycle:\", has_cycle(adj, 4), \"; 8-cycle:\", has_cycle(adj, 8), \"; 16-cycle:\", has_cycle(adj, 16))\nEOF\npython3 erdos64_anchor_graphs.py erdos64/cubic24.g6"
   },
   "expected_output": "Four lines, each: '24 vertices; 3-regular: True ; 4-cycle: False ; 8-cycle: False ; 16-cycle: True'.",
   "does_not_show": "It does not show anything about graphs on 23 or fewer vertices, nor that there are no other such graphs.",
   "cost": "a few seconds",
   "runnable_by_assistant": true,
   "script_file": "erdos64_anchor_graphs.py"
  },
  {
   "id": "647-part1",
   "purpose": "Problem 647 part 1: recompute the residue classes and compare them with classes_d0.txt.",
   "inputs": [
    {
     "path": "certificates/erdos647/classes_d0.txt",
     "sha256": "86941dca4571c797c958b7f268449c49d1677ea41290482c53b4203bc6b7f5eb"
    }
   ],
   "command": {
    "powershell": "@'\n# Problem 647, part 1: the residue classes. Usage: python erdos647_part1_classes.py erdos647/classes_d0.txt\nimport sys\nM = 2**6 * 3**4 * 5**2 * 7**2          # 6,350,400\nPP = [(2, 6, 64), (3, 4, 81), (5, 2, 25), (7, 2, 49)]   # prime, exponent a, prime power q\n\ndef vp(x, p):\n    e = 0\n    while x % p == 0:\n        x //= p; e += 1\n    return e\n\n# for each prime power and each residue x: for k = 1..64 the pair (exponent+1, t != 0)\ntab = []\nfor p, a, q in PP\u003a\n    rows = []\n    for x in range(q):\n        row = []\n        for k in range(1, 65):\n            t = (x - k) % q\n            row.append((a + 1, 0) if t == 0 else (vp(t, p) + 1, 1))\n        rows.append(row)\n    tab.append(rows)\n\nfound = []\ndef rec(level, prod, allnz, xs):\n    if level == 4:\n        if all(prod[i] * (2 if allnz[i] else 1) <= i + 3 for i in range(64)):   # b <= k + 2\n            found.append(tuple(xs))\n        return\n    for x in range(PP[level][2]):\n        row = tab[level][x]\n        np_ = [prod[i] * row[i][0] for i in range(64)]\n        if any(np_[i] > i + 3 for i in range(64)):      # b never shrinks, so prune\n            continue\n        rec(level + 1, np_, [allnz[i] and row[i][1] for i in range(64)], xs + [x])\nrec(0, [1] * 64, [1] * 64, [])\n\nclasses = sorted(sum(x * (M // q) * pow(M // q, -1, q) for (p, a, q), x in zip(PP, xs)) % M for xs in found)\nshipped = [int(s) for s in open(sys.argv[1]).read().split()]\nprint(\"survivors:\", len(classes))\nprint(\"all multiples of 2520:\", all(c % 2520 == 0 for c in classes))\nprint(\"equal to shipped file:\", classes == shipped)\n'@ | Set-Content -Encoding utf8 erdos647_part1_classes.py\npython erdos647_part1_classes.py erdos647/classes_d0.txt",
    "bash": "cat > erdos647_part1_classes.py <<'EOF'\n# Problem 647, part 1: the residue classes. Usage: python erdos647_part1_classes.py erdos647/classes_d0.txt\nimport sys\nM = 2**6 * 3**4 * 5**2 * 7**2          # 6,350,400\nPP = [(2, 6, 64), (3, 4, 81), (5, 2, 25), (7, 2, 49)]   # prime, exponent a, prime power q\n\ndef vp(x, p):\n    e = 0\n    while x % p == 0:\n        x //= p; e += 1\n    return e\n\n# for each prime power and each residue x: for k = 1..64 the pair (exponent+1, t != 0)\ntab = []\nfor p, a, q in PP\u003a\n    rows = []\n    for x in range(q):\n        row = []\n        for k in range(1, 65):\n            t = (x - k) % q\n            row.append((a + 1, 0) if t == 0 else (vp(t, p) + 1, 1))\n        rows.append(row)\n    tab.append(rows)\n\nfound = []\ndef rec(level, prod, allnz, xs):\n    if level == 4:\n        if all(prod[i] * (2 if allnz[i] else 1) <= i + 3 for i in range(64)):   # b <= k + 2\n            found.append(tuple(xs))\n        return\n    for x in range(PP[level][2]):\n        row = tab[level][x]\n        np_ = [prod[i] * row[i][0] for i in range(64)]\n        if any(np_[i] > i + 3 for i in range(64)):      # b never shrinks, so prune\n            continue\n        rec(level + 1, np_, [allnz[i] and row[i][1] for i in range(64)], xs + [x])\nrec(0, [1] * 64, [1] * 64, [])\n\nclasses = sorted(sum(x * (M // q) * pow(M // q, -1, q) for (p, a, q), x in zip(PP, xs)) % M for xs in found)\nshipped = [int(s) for s in open(sys.argv[1]).read().split()]\nprint(\"survivors:\", len(classes))\nprint(\"all multiples of 2520:\", all(c % 2520 == 0 for c in classes))\nprint(\"equal to shipped file:\", classes == shipped)\nEOF\npython3 erdos647_part1_classes.py erdos647/classes_d0.txt"
   },
   "expected_output": "survivors: 2205\nall multiples of 2520: True\nequal to shipped file: True",
   "does_not_show": "It depends on the residue lemma, whose proof is in the chapter. It does not show the claim above 10^9 by itself.",
   "cost": "about 5 to 30 seconds",
   "runnable_by_assistant": true,
   "script_file": "erdos647_part1_classes.py"
  },
  {
   "id": "647-part2",
   "purpose": "Problem 647 part 2: brute force for n up to 6,350,464.",
   "inputs": [],
   "command": {
    "powershell": "@'\n# Problem 647, part 2: brute force to 6,350,464.  Usage: python erdos647_part2_bruteforce.py\nN = 6350464\nspf = list(range(N + 1))\ni = 2\nwhile i * i <= N\u003a\n    if spf[i] == i\u003a\n        for j in range(i * i, N + 1, i):\n            if spf[j] == j\u003a\n                spf[j] = i\n    i += 1\ntau = [0] * (N + 1)\ntau[1] = 1\nfor m in range(2, N + 1):\n    p = spf[m]; r = m // p; e = 1\n    while r % p == 0:\n        r //= p; e += 1\n    tau[m] = tau[r] * (e + 1)\nsols, mx = [], 0                      # the maximum over no numbers is 0\nfor n in range(1, N + 1):\n    if mx <= n + 2:\n        sols.append(n)\n    mx = max(mx, n + tau[n])\nprint(\"solutions:\", sols)\n'@ | Set-Content -Encoding utf8 erdos647_part2_bruteforce.py\npython erdos647_part2_bruteforce.py",
    "bash": "cat > erdos647_part2_bruteforce.py <<'EOF'\n# Problem 647, part 2: brute force to 6,350,464.  Usage: python erdos647_part2_bruteforce.py\nN = 6350464\nspf = list(range(N + 1))\ni = 2\nwhile i * i <= N\u003a\n    if spf[i] == i\u003a\n        for j in range(i * i, N + 1, i):\n            if spf[j] == j\u003a\n                spf[j] = i\n    i += 1\ntau = [0] * (N + 1)\ntau[1] = 1\nfor m in range(2, N + 1):\n    p = spf[m]; r = m // p; e = 1\n    while r % p == 0:\n        r //= p; e += 1\n    tau[m] = tau[r] * (e + 1)\nsols, mx = [], 0                      # the maximum over no numbers is 0\nfor n in range(1, N + 1):\n    if mx <= n + 2:\n        sols.append(n)\n    mx = max(mx, n + tau[n])\nprint(\"solutions:\", sols)\nEOF\npython3 erdos647_part2_bruteforce.py"
   },
   "expected_output": "solutions: [1, 2, 3, 4, 5, 6, 8, 10, 12, 24]",
   "does_not_show": "It shows the claim just up to 6,350,464 (part 3 of the chapter carries it to 10^9).",
   "cost": "about 10 to 60 seconds, about 1 GB of memory in plain Python lists",
   "runnable_by_assistant": true,
   "script_file": "erdos647_part2_bruteforce.py"
  },
  {
   "id": "647-part4",
   "purpose": "Problem 647 part 4: the bookkeeping of the sieve logs from 10^8 to 10^14.",
   "inputs": [
    {
     "path": "certificates/erdos647/prod_1e8_1e10.txt",
     "sha256": "5ede4baaf2aed587c08998855eff71e714c6cef45bd1b523d61d0e24970d7cb0"
    }
   ],
   "command": {
    "powershell": "@'\n# Problem 647, part 4: the sieve-log bookkeeping.  Usage: python erdos647_part4_logs.py erdos647\nimport os, sys\nM = 6350400\nd = sys.argv[1]\nclasses = [int(s) for s in open(os.path.join(d, \"classes_d0.txt\")).read().split()]\nchunks = {}\nfor fn in sorted(os.listdir(d)):\n    if not fn.startswith(\"prod_\"):\n        continue\n    hdr, done, bad = None, False, False\n    for line in open(os.path.join(d, fn)):\n        if line.startswith(\"# sieve647\"):\n            hdr = dict(kv.split(\"=\", 1) for kv in line.split()[2:])\n        elif line.startswith(\"# DONE\"):\n            done = True\n        elif line.startswith(\"S\"):\n            bad = True\n        elif line.startswith(\"C \"):\n            f = line.split()\n            r, c, s1, s2 = int(f[1]), int(f[3]), int(f[5]), int(f[7])\n            ch = chunks.setdefault((int(hdr[\"nlo\"]), int(hdr[\"nhi\"])), {\"cls\": {}, \"surv\": 0})\n            ch[\"cls\"].setdefault(r, []).append(c)\n            ch[\"surv\"] += s1 + s2\n    assert hdr and done and not bad, fn\nkeys = sorted(chunks)\nprint(\"chunks:\", keys)\nprint(\"contiguous from 10^8+1 to 10^14:\", keys[0][0] == 10**8 + 1 and keys[-1][1] == 10**14 and all(a[1] + 1 == b[0] for a, b in zip(keys, keys[1:])))\ntot = []\nfor lo, hi in keys\u003a\n    ch = chunks[(lo, hi)]\n    assert set(ch[\"cls\"]) == set(classes) and all(len(v) == 1 for v in ch[\"cls\"].values()), \"class coverage\"\n    t = 0\n    for r, v in ch[\"cls\"].items():\n        assert v[0] == (hi - r) // M - (lo - 1 - r) // M, \"count mismatch for class %d\" % r\n        t += v[0]\n    tot.append(t)\nprint(\"candidates per chunk:\", tot)\nprint(\"candidates in all:\", sum(tot))\nprint(\"survivors:\", sum(c[\"surv\"] for c in chunks.values()))\n'@ | Set-Content -Encoding utf8 erdos647_part4_logs.py\npython erdos647_part4_logs.py erdos647",
    "bash": "cat > erdos647_part4_logs.py <<'EOF'\n# Problem 647, part 4: the sieve-log bookkeeping.  Usage: python erdos647_part4_logs.py erdos647\nimport os, sys\nM = 6350400\nd = sys.argv[1]\nclasses = [int(s) for s in open(os.path.join(d, \"classes_d0.txt\")).read().split()]\nchunks = {}\nfor fn in sorted(os.listdir(d)):\n    if not fn.startswith(\"prod_\"):\n        continue\n    hdr, done, bad = None, False, False\n    for line in open(os.path.join(d, fn)):\n        if line.startswith(\"# sieve647\"):\n            hdr = dict(kv.split(\"=\", 1) for kv in line.split()[2:])\n        elif line.startswith(\"# DONE\"):\n            done = True\n        elif line.startswith(\"S\"):\n            bad = True\n        elif line.startswith(\"C \"):\n            f = line.split()\n            r, c, s1, s2 = int(f[1]), int(f[3]), int(f[5]), int(f[7])\n            ch = chunks.setdefault((int(hdr[\"nlo\"]), int(hdr[\"nhi\"])), {\"cls\": {}, \"surv\": 0})\n            ch[\"cls\"].setdefault(r, []).append(c)\n            ch[\"surv\"] += s1 + s2\n    assert hdr and done and not bad, fn\nkeys = sorted(chunks)\nprint(\"chunks:\", keys)\nprint(\"contiguous from 10^8+1 to 10^14:\", keys[0][0] == 10**8 + 1 and keys[-1][1] == 10**14 and all(a[1] + 1 == b[0] for a, b in zip(keys, keys[1:])))\ntot = []\nfor lo, hi in keys\u003a\n    ch = chunks[(lo, hi)]\n    assert set(ch[\"cls\"]) == set(classes) and all(len(v) == 1 for v in ch[\"cls\"].values()), \"class coverage\"\n    t = 0\n    for r, v in ch[\"cls\"].items():\n        assert v[0] == (hi - r) // M - (lo - 1 - r) // M, \"count mismatch for class %d\" % r\n        t += v[0]\n    tot.append(t)\nprint(\"candidates per chunk:\", tot)\nprint(\"candidates in all:\", sum(tot))\nprint(\"survivors:\", sum(c[\"surv\"] for c in chunks.values()))\nEOF\npython3 erdos647_part4_logs.py erdos647"
   },
   "expected_output": "chunks: five pairs from (100000001, 10000000000) to (30000000000001, 100000000000000)\ncontiguous from 10^8+1 to 10^14: True\ncandidates per chunk: [3437500, 343750000, 3125000000, 6944444444, 24305555556]\ncandidates in all: 34722187500\nsurvivors: 0",
   "does_not_show": "It checks the logs' bookkeeping (every class once per chunk, exact counts, no survivors). It does not re-run the sieve, so it does not show that the sieve is right.",
   "cost": "seconds",
   "runnable_by_assistant": true,
   "script_file": "erdos647_part4_logs.py"
  },
  {
   "id": "647-part3",
   "purpose": "Problem 647 part 3: the scan from 6,350,464 to 10^9 (345,017 candidates, each must have a k with tau(n-k) > k+2).",
   "inputs": [
    {
     "path": "certificates/erdos647/classes_d0.txt",
     "sha256": "86941dca4571c797c958b7f268449c49d1677ea41290482c53b4203bc6b7f5eb"
    }
   ],
   "command": {
    "powershell": "@'\n# Problem 647, part 3: for every n in (6,350,464, 10^9] in one of the 2,205 classes, find k with tau(n-k) > k+2.\n# Usage: python erdos647_part3_scan.py erdos647/classes_d0.txt\nimport sys\nM = 6350400\nclasses = [int(s) for s in open(sys.argv[1]).read().split()]\n\ndef primes_upto(n):\n    s = bytearray([1]) * (n + 1); s[0:2] = b\"\\x00\\x00\"\n    for i in range(2, int(n ** 0.5) + 1):\n        if s[i]:\n            s[i * i::i] = bytearray(len(s[i * i::i]))\n    return [i for i in range(n + 1) if s[i]]\n\ndef is_prime(n):                                   # Miller-Rabin, exact for n < 3.3e24\n    if n < 2: return False\n    for p in (2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37):\n        if n % p == 0: return n == p\n    d, s = n - 1, 0\n    while d % 2 == 0: d //= 2; s += 1\n    for a in (2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37):\n        x = pow(a, d, n)\n        if x in (1, n - 1): continue\n        for _ in range(s - 1):\n            x = x * x % n\n            if x == n - 1: break\n        else\u003a\n            return False\n    return True\n\ndef tau_lower(n, primes):\n    \"\"\"exact exponent factors for the listed primes, then 2 for a prime cofactor, 3 for a composite cofactor\"\"\"\n    b = 1\n    for p in primes\u003a\n        if p * p > n: break\n        if n % p == 0:\n            e = 0\n            while n % p == 0: n //= p; e += 1\n            b *= e + 1\n    return b if n == 1 else b * (2 if is_prime(n) else 3)\n\nsmall, large = primes_upto(60), primes_upto(40000)\nlo, hi = 6350464, 10**9\ncand = bad = 0\nfor blk in range(lo // M, hi // M + 1):\n    for c in classes\u003a\n        n = blk * M + c\n        if n <= lo or n > hi: continue\n        cand += 1\n        if not any(tau_lower(n - k, small) > k + 2 for k in range(1, 65)) and \\\n           not any(tau_lower(n - k, large) > k + 2 for k in range(1, 65)):\n            bad += 1\nprint(\"candidates:\", cand)\nprint(\"candidates with no k such that tau(n-k) > k+2:\", bad)\n'@ | Set-Content -Encoding utf8 erdos647_part3_scan.py\npython erdos647_part3_scan.py erdos647/classes_d0.txt",
    "bash": "cat > erdos647_part3_scan.py <<'EOF'\n# Problem 647, part 3: for every n in (6,350,464, 10^9] in one of the 2,205 classes, find k with tau(n-k) > k+2.\n# Usage: python erdos647_part3_scan.py erdos647/classes_d0.txt\nimport sys\nM = 6350400\nclasses = [int(s) for s in open(sys.argv[1]).read().split()]\n\ndef primes_upto(n):\n    s = bytearray([1]) * (n + 1); s[0:2] = b\"\\x00\\x00\"\n    for i in range(2, int(n ** 0.5) + 1):\n        if s[i]:\n            s[i * i::i] = bytearray(len(s[i * i::i]))\n    return [i for i in range(n + 1) if s[i]]\n\ndef is_prime(n):                                   # Miller-Rabin, exact for n < 3.3e24\n    if n < 2: return False\n    for p in (2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37):\n        if n % p == 0: return n == p\n    d, s = n - 1, 0\n    while d % 2 == 0: d //= 2; s += 1\n    for a in (2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37):\n        x = pow(a, d, n)\n        if x in (1, n - 1): continue\n        for _ in range(s - 1):\n            x = x * x % n\n            if x == n - 1: break\n        else\u003a\n            return False\n    return True\n\ndef tau_lower(n, primes):\n    \"\"\"exact exponent factors for the listed primes, then 2 for a prime cofactor, 3 for a composite cofactor\"\"\"\n    b = 1\n    for p in primes\u003a\n        if p * p > n: break\n        if n % p == 0:\n            e = 0\n            while n % p == 0: n //= p; e += 1\n            b *= e + 1\n    return b if n == 1 else b * (2 if is_prime(n) else 3)\n\nsmall, large = primes_upto(60), primes_upto(40000)\nlo, hi = 6350464, 10**9\ncand = bad = 0\nfor blk in range(lo // M, hi // M + 1):\n    for c in classes\u003a\n        n = blk * M + c\n        if n <= lo or n > hi: continue\n        cand += 1\n        if not any(tau_lower(n - k, small) > k + 2 for k in range(1, 65)) and \\\n           not any(tau_lower(n - k, large) > k + 2 for k in range(1, 65)):\n            bad += 1\nprint(\"candidates:\", cand)\nprint(\"candidates with no k such that tau(n-k) > k+2:\", bad)\nEOF\npython3 erdos647_part3_scan.py erdos647/classes_d0.txt"
   },
   "expected_output": "candidates: 345017\ncandidates with no k such that tau(n-k) > k+2: 0",
   "does_not_show": "It depends on the residue lemma (part 1). The chapter's near miss 604517614941240 (fails at k = 14, not before) is a separate check you can add.",
   "cost": "about 5 to 30 seconds",
   "runnable_by_assistant": true,
   "script_file": "erdos647_part3_scan.py"
  },
  {
   "id": "64-logs",
   "purpose": "Problem 64, generator logs: 695 parts for orders 4 to 22, all reporting 0, the order-24 anchor reporting 4.",
   "inputs": [
    {
     "path": "certificates/erdos64/parts_n04-21.txt",
     "sha256": "8e188165fed2df09d815a698389f46b9411ff8da2e542b6bb0f538096fcab7ea"
    },
    {
     "path": "certificates/erdos64/parts_n22.txt",
     "sha256": "6a7e21b4ed7ea31ae8c5c560a5b6a2d3c7619af2e58606905096956340f864e3"
    }
   ],
   "command": {
    "any": "No copy-paste script yet. Write it yourself from the written recipe\u003a\nChapter heading 'Recipe for problem 64: the generator logs'. Each line of the two part files is: part name | the generator's start line | its last line; lines starting with # are comments."
   },
   "expected_output": "695 parts for orders 4 to 22 (184 lines in parts_n04-21.txt, one of them the order-24 anchor, and 512 in parts_n22.txt), every one reporting '0 graphs generated', and the anchor reporting '4 graphs generated'.",
   "does_not_show": "It checks the bookkeeping of the logs: that every part ran to the end and reported nothing. It does not re-run the generator; re-running it (nauty geng, free) is the independent check, and order 22 took many CPU hours.",
   "cost": "under a second",
   "runnable_by_assistant": false
  },
  {
   "id": "64-small-orders",
   "purpose": "Problem 64, small orders: no connected graph with minimum degree 3 and no 4-cycle lacks an 8-cycle, for n = 4 to 15.",
   "inputs": [],
   "command": {
    "any": "No copy-paste script yet. Write it yourself from the written recipe\u003a\nChapter heading 'Recipe for problem 64: the small orders and the 24-vertex graphs'. Needs an enumerator such as nauty geng (free, from its authors)."
   },
   "expected_output": "Nothing left after discarding graphs with an 8-cycle, for n = 4 to 15; sanity counts 0 at order 9, 5 at order 10, then 9, 57, 503, 6059, 91433 for orders 11 to 15.",
   "does_not_show": "It does not cover order 16 or above.",
   "cost": "about 30 to 50 seconds to order 15; order 16 adds minutes (the book's timing)",
   "runnable_by_assistant": false
  },
  {
   "id": "one-byte-change",
   "purpose": "See for yourself that a one-byte change is caught: change one byte in a copy of erdos647/prod_1e8_1e10.txt and look at the fingerprint.",
   "inputs": [
    {
     "path": "certificates/erdos647/prod_1e8_1e10.txt",
     "sha256": "5ede4baaf2aed587c08998855eff71e714c6cef45bd1b523d61d0e24970d7cb0",
     "local": "erdos647/prod_1e8_1e10.txt"
    }
   ],
   "command": {
    "powershell": "python -c \"b=bytearray(open('erdos647/prod_1e8_1e10.txt','rb').read()); b[0]^=1; open('tampered.copy','wb').write(b)\"\n\"published : 5ede4baaf2aed587c08998855eff71e714c6cef45bd1b523d61d0e24970d7cb0\"\n\"your copy : \" + (Get-FileHash -Algorithm SHA256 tampered.copy).Hash.ToLower()",
    "bash": "python3 -c \"b=bytearray(open('erdos647/prod_1e8_1e10.txt','rb').read()); b[0]^=1; open('tampered.copy','wb').write(b)\"\necho \"published : 5ede4baaf2aed587c08998855eff71e714c6cef45bd1b523d61d0e24970d7cb0\"\necho \"your copy : $( (sha256sum tampered.copy 2>/dev/null || shasum -a 256 tampered.copy) | cut -c1-64 )\""
   },
   "expected_output": "Two different 64-digit values; the 'published' value ends 970d7cb0 and your copy's value is different.",
   "does_not_show": "It shows the fingerprint step would notice that change. It says nothing about the file you did not change.",
   "cost": "instant",
   "runnable_by_assistant": true
  }
 ]
}