P vs NP: the fewest gates
Easy to check, easy to find? Exact small circuits, proofs that none smaller exists, and the 2026 claims around P vs NP, rerun and read

| 1 | """Boolean circuits over the full binary basis B2: the functions this project tables, the .ckt format, the encoder of |
| 2 | "some circuit of at most S gates computes F" as CNF, and a checker of LRAT proofs that such a CNF is unsatisfiable. |
| 3 | Standard library only, so the check runs in python:3.12-slim with no network. |
| 4 | |
| 5 | Functions, by id: |
| 6 | mod3_<n>_<r> 1 when x1 + ... + xn = r mod 3 shown as MOD3_<n>^<r> |
| 7 | sum<n> the binary representation of x1 + ... + xn, shown as SUM_<n> |
| 8 | least significant bit first, ceil(log2(n + 1)) outputs |
| 9 | maj<n> 1 when more than half of the inputs are 1 shown as MAJ_<n> |
| 10 | thr<k>_<n> 1 when at least k inputs are 1 shown as THR_<n>^<k> |
| 11 | |
| 12 | The .ckt format is circuit_improvement's (Kulikov et al.): a line "n s m"; a line of the n input names; s gate lines |
| 13 | "name a b tttt", where a and b are earlier nodes and tttt the gate's outputs on (a, b) = (0,0), (0,1), (1,0), (1,1); |
| 14 | a line of the m output node names. Any of the 16 binary functions is one gate. |
| 15 | """ |
| 16 | import gzip |
| 17 | import itertools |
| 18 | import re |
| 19 | |
| 20 | MAX_INPUTS = 16 # a truth table of 2^16 rows times a few hundred gates is seconds; past that the check would not end |
| 21 | |
| 22 | |
| 23 | class Wrong(Exception): |
| 24 | """What a route handed in that the check refuses; its text is what the author reads.""" |
| 25 | |
| 26 | |
| 27 | def function(fid): |
| 28 | """(inputs, f) for a function id: f maps a tuple of input bits to the list of output bits.""" |
| 29 | m = re.fullmatch(r"mod3_(\d+)_([012])|sum(\d+)|maj(\d+)|thr(\d+)_(\d+)", fid) |
| 30 | if not m: |
| 31 | raise Wrong(f"{fid}: not a function this project tables (mod3_<n>_<r>, sum<n>, maj<n>, thr<k>_<n>)") |
| 32 | if m[1]: |
| 33 | n, r = int(m[1]), int(m[2]) |
| 34 | f = lambda x: [int(sum(x) % 3 == r)] |
| 35 | elif m[3]: |
| 36 | n = int(m[3]) |
| 37 | f = lambda x: [(sum(x) >> b) & 1 for b in range(n.bit_length())] |
| 38 | elif m[4]: |
| 39 | n = int(m[4]) |
| 40 | f = lambda x: [int(2 * sum(x) > n)] |
| 41 | else: |
| 42 | k, n = int(m[5]), int(m[6]) |
| 43 | f = lambda x: [int(sum(x) >= k)] |
| 44 | if not 2 <= n <= MAX_INPUTS: |
| 45 | raise Wrong(f"{fid}: {n} inputs; this check tables functions of 2 to {MAX_INPUTS} inputs") |
| 46 | return n, f |
| 47 | |
| 48 | |
| 49 | def shown(fid): |
| 50 | """The name a function goes by on the project's board, as the cards write mathematics: MOD3_6^1, SUM_5, SUM_{10}, |
| 51 | MAJ_7, THR_8^4 (a subscript of two digits in braces, so a card sets it whole).""" |
| 52 | m = re.fullmatch(r"mod3_(\d+)_(\d)|sum(\d+)|maj(\d+)|thr(\d+)_(\d+)", fid) |
| 53 | sub = lambda n: n if len(n) == 1 else f"{{{n}}}" |
| 54 | if m[1]: |
| 55 | return f"MOD3_{sub(m[1])}^{m[2]}" |
| 56 | if m[3]: |
| 57 | return f"SUM_{sub(m[3])}" |
| 58 | if m[4]: |
| 59 | return f"MAJ_{sub(m[4])}" |
| 60 | return f"THR_{sub(m[6])}^{sub(m[5])}" |
| 61 | |
| 62 | |
| 63 | def rows(n): |
| 64 | """Every input, as bits x1 .. xn, x1 the most significant bit of the row's number.""" |
| 65 | return [tuple((t >> (n - 1 - i)) & 1 for i in range(n)) for t in range(2 ** n)] |
| 66 | |
| 67 | |
| 68 | def read_ckt(text, where): |
| 69 | """The circuit a .ckt file describes, as (inputs, gates, outputs), or Wrong naming the line to fix.""" |
| 70 | lines = [(i + 1, l.split()) for i, l in enumerate(text.splitlines()) if l.strip() and not l.lstrip().startswith("#")] |
| 71 | if not lines: |
| 72 | raise Wrong(f"{where}: empty") |
| 73 | head = lines[0][1] |
| 74 | if len(head) != 3 or not all(h.isdigit() for h in head): |
| 75 | raise Wrong(f"{where}:{lines[0][0]}: the first line is 'n s m' (inputs, gates, outputs)") |
| 76 | n, s, m = map(int, head) |
| 77 | if len(lines) != 3 + s: |
| 78 | raise Wrong(f"{where}: the header says {s} gates, so {3 + s} lines (header, inputs, gates, outputs); the file has {len(lines)}") |
| 79 | inputs, outputs = lines[1][1], lines[-1][1] |
| 80 | if len(inputs) != n or len(set(inputs)) != n: |
| 81 | raise Wrong(f"{where}:{lines[1][0]}: {n} distinct input names expected") |
| 82 | known, gates = set(inputs), [] |
| 83 | for line, g in lines[2:2 + s]: |
| 84 | if len(g) != 4 or g[1] not in known or g[2] not in known or not re.fullmatch(r"[01]{4}", g[3]) or g[0] in known: |
| 85 | raise Wrong(f"{where}:{line}: a gate is 'name a b tttt', a and b earlier nodes, tttt four bits, the name new") |
| 86 | known.add(g[0]) |
| 87 | gates.append(g) |
| 88 | if len(outputs) != m or set(outputs) - known: |
| 89 | raise Wrong(f"{where}:{lines[-1][0]}: {m} output names expected, each a node of the circuit") |
| 90 | return inputs, gates, outputs |
| 91 | |
| 92 | |
| 93 | def computes(fid, text, where): |
| 94 | """The number of gates of a circuit that computes fid on all 2^n inputs, or Wrong at the first input it gets wrong.""" |
| 95 | n, f = function(fid) |
| 96 | inputs, gates, outputs = read_ckt(text, where) |
| 97 | if len(inputs) != n: |
| 98 | raise Wrong(f"{where}: {shown(fid)} has {n} inputs, the circuit {len(inputs)}") |
| 99 | for x in rows(n): |
| 100 | v = dict(zip(inputs, x)) |
| 101 | for name, a, b, tt in gates: |
| 102 | v[name] = tt[2 * v[a] + v[b]] == "1" |
| 103 | got, want = [int(v[o]) for o in outputs], f(x) |
| 104 | if got != want: |
| 105 | raise Wrong(f"{where}: on input {''.join(map(str, x))} the circuit gives {got}, {shown(fid)} is {want}") |
| 106 | return len(gates) |
| 107 | |
| 108 | |
| 109 | def encode(fid, s): |
| 110 | """The CNF "some circuit of at most s gates over B2 computes fid", as (variables, clauses, names); names holds the |
| 111 | variables a model is read back through (see scripts/circuit.py). The encoding is Kojevnikov, Kulikov and |
| 112 | Yaroslavtsev's (SAT 2009), simplified: gates n .. n+s-1, each reads an ordered pair j < k of earlier nodes and |
| 113 | computes a normal function (0 on (0,0)) that is neither constant 0 nor a projection; v(i, t) is gate i's value on |
| 114 | input t; every output is one gate, compared with the function, negated when the function is 1 on input 0. It is |
| 115 | complete: a circuit can be made normal by pushing negations into later gates and the outputs, constant and |
| 116 | projection gates can be dropped, and a smaller circuit is padded to exactly s gates with unused gates (n >= 2).""" |
| 117 | n, f = function(fid) |
| 118 | if not 1 <= s <= 40: |
| 119 | raise Wrong(f"{shown(fid)}: lower bounds are certified here for at most 40 gates") |
| 120 | table = rows(n) |
| 121 | outs = [f(x) for x in table] |
| 122 | nv = 0 |
| 123 | |
| 124 | def var(): |
| 125 | nonlocal nv |
| 126 | nv += 1 |
| 127 | return nv |
| 128 | |
| 129 | gates = range(n, n + s) |
| 130 | sel = {(i, j, k): var() for i in gates for j, k in itertools.combinations(range(i), 2)} |
| 131 | fun = {(i, a, b): var() for i in gates for a, b in ((0, 1), (1, 0), (1, 1))} |
| 132 | val = {(i, t): var() for i in gates for t in range(len(table))} |
| 133 | out = {(h, i): var() for h in range(len(outs[0])) for i in gates} |
| 134 | cls = [] |
| 135 | |
| 136 | def exactly_one(xs): |
| 137 | cls.append(list(xs)) |
| 138 | cls.extend([-a, -b] for a, b in itertools.combinations(xs, 2)) |
| 139 | |
| 140 | for i in gates: |
| 141 | exactly_one([sel[(i, j, k)] for j, k in itertools.combinations(range(i), 2)]) |
| 142 | f01, f10, f11 = fun[(i, 0, 1)], fun[(i, 1, 0)], fun[(i, 1, 1)] |
| 143 | cls += [[f01, f10, f11], [f01, -f10, -f11], [-f01, f10, -f11]] # not 0000, not 0011, not 0101 |
| 144 | for j, k in itertools.combinations(range(i), 2): |
| 145 | c = sel[(i, j, k)] |
| 146 | for t, x in enumerate(table): |
| 147 | vj = val[(j, t)] if j >= n else bool(x[j]) |
| 148 | vk = val[(k, t)] if k >= n else bool(x[k]) |
| 149 | vi = val[(i, t)] |
| 150 | for a, b in itertools.product((0, 1), repeat=2): |
| 151 | pre, skip = [-c], False |
| 152 | for v, want in ((vj, a), (vk, b)): |
| 153 | if isinstance(v, bool): |
| 154 | skip |= v != bool(want) |
| 155 | else: |
| 156 | pre.append(-v if want else v) |
| 157 | if skip: |
| 158 | continue |
| 159 | if (a, b) == (0, 0): |
| 160 | cls.append(pre + [-vi]) |
| 161 | else: |
| 162 | g = fun[(i, a, b)] |
| 163 | cls.append(pre + [-vi, g]) |
| 164 | cls.append(pre + [vi, -g]) |
| 165 | for h in range(len(outs[0])): |
| 166 | exactly_one([out[(h, i)] for i in gates]) |
| 167 | for i in gates: |
| 168 | for t in range(len(table)): |
| 169 | want = outs[t][h] ^ outs[0][h] |
| 170 | cls.append([-out[(h, i)], val[(i, t)] if want else -val[(i, t)]]) |
| 171 | return nv, cls, {"n": n, "s": s, "sel": sel, "fun": fun, "out": out, "neg": outs[0]} |
| 172 | |
| 173 | |
| 174 | def dimacs(nv, clauses, comment=""): |
| 175 | return f"c {comment}\np cnf {nv} {len(clauses)}\n" + "".join(" ".join(map(str, c)) + " 0\n" for c in clauses) |
| 176 | |
| 177 | |
| 178 | def unsat(clauses, proof, where): |
| 179 | """Check an LRAT proof (Cruz-Filipe, Heule, Hunt, Kaufmann and Schneider-Kamp, 2017) that the clauses are |
| 180 | unsatisfiable: each added clause follows from its hints by unit propagation in the order given; deletions free |
| 181 | clauses. RAT steps (negative hints) are refused rather than checked: CaDiCaL's proofs of these formulas have |
| 182 | none. Returns the number of steps checked, or raises Wrong at the first step that does not check.""" |
| 183 | live = {i + 1: c for i, c in enumerate(clauses)} |
| 184 | steps = 0 |
| 185 | for number, line in enumerate(proof, 1): |
| 186 | parts = line.split() |
| 187 | if not parts or parts[0] == "c": |
| 188 | continue |
| 189 | try: |
| 190 | if parts[1] == "d": |
| 191 | for x in parts[2:-1]: |
| 192 | live.pop(int(x), None) |
| 193 | continue |
| 194 | nums = list(map(int, parts)) |
| 195 | z = nums.index(0, 1) |
| 196 | except ValueError: |
| 197 | raise Wrong(f"{where}:{number}: not an LRAT line") |
| 198 | new, lits, hints = nums[0], nums[1:z], nums[z + 1:-1] |
| 199 | if nums[-1] != 0 or new in live: |
| 200 | raise Wrong(f"{where}:{number}: an added clause needs a new id and a closing 0") |
| 201 | true, conflict = {-l for l in lits}, False # the literals assumed true: the new clause's, negated |
| 202 | for h in hints: |
| 203 | c = live.get(h) |
| 204 | if h < 0 or c is None: |
| 205 | raise Wrong(f"{where}:{number}: hint {h} is {'a RAT hint, which this checker does not take' if h < 0 else 'no live clause'}") |
| 206 | if any(l in true for l in c): |
| 207 | raise Wrong(f"{where}:{number}: hint {h} is satisfied, not unit") |
| 208 | rest = [l for l in c if -l not in true] |
| 209 | if not rest: |
| 210 | conflict = True |
| 211 | break |
| 212 | if len(rest) > 1: |
| 213 | raise Wrong(f"{where}:{number}: hint {h} is not unit") |
| 214 | true.add(rest[0]) |
| 215 | if not conflict: |
| 216 | raise Wrong(f"{where}:{number}: the hints do not reach a conflict") |
| 217 | live[new] = lits |
| 218 | steps += 1 |
| 219 | if not lits: |
| 220 | return steps |
| 221 | raise Wrong(f"{where}: the proof ends without the empty clause") |
| 222 | |
| 223 | |
| 224 | def proof_lines(path): |
| 225 | """The lines of an LRAT proof, plain or gzipped.""" |
| 226 | opener = gzip.open if path.name.endswith(".gz") else open |
| 227 | with opener(path, "rt") as fh: |
| 228 | yield from fh |
| 229 | |
| 230 | |
| 231 | if __name__ == "__main__": |
| 232 | # self-check: a full adder computes sum3 in 5 gates, a wrong one is caught, and "sum2 in 1 gate" has no model the |
| 233 | # encoder misses (two outputs need two gates, so the CNF has a clause set no assignment satisfies trivially) |
| 234 | adder = "3 5 2\nx y z\na x y 0110\nb a z 0110\nc x y 0001\nd a z 0001\ne c d 0111\nb e\n" |
| 235 | assert computes("sum3", adder, "adder") == 5 |
| 236 | try: |
| 237 | computes("sum3", adder.replace("e c d 0111", "e c d 0001"), "bad") |
| 238 | raise AssertionError("a wrong adder passed") |
| 239 | except Wrong as e: |
| 240 | assert "on input" in str(e) |
| 241 | nv, cls, _ = encode("mod3_3_0", 2) |
| 242 | assert nv > 0 and all(cls) |
| 243 | print("circuits.py: self-check passed") |