Module contents
Lesson 18 of 22Core 110 min

Satisfiability: CNF, the Tseitin transformation and problem encodings

SAT as a problem and modeling language: certificates, linear-size Tseitin conversion to CNF, encodings of practical problems (coloring, Sudoku, bounded-horizon planning), cardinality constraints, the polynomial cases 2-SAT and Horn-SAT, and bounded verification of programs and circuits. This bridges to the SAT and SMT solvers of m10.

After this lesson you can

  • Explain SAT, its certificates, and the relation between validity and unsatisfiability.
  • Apply the Tseitin transformation and prove that it preserves satisfiability with linear size.
  • Encode combinatorial problems in CNF with efficient cardinality constraints.
  • Solve 2-SAT with an implication graph and Horn-SAT with unit propagation.
  • Formulate circuit equivalence and bounded program verification as SAT instances.

Before you start

Motivation: one solver, many problems

A SAT solver does one thing: it receives a list of clauses over Boolean variables and returns an assignment satisfying them all, or reports that none exists. This seems modest. But that one question, well formulated, answers many others:

  • Planning. Is there a sequence of at most 20 actions taking a robotic warehouse from its initial state to its goal? Use a variable for every fact and action at every time, and clauses saying what each action requires and changes.
  • Hardware verification. After optimizing a multiplier, does it still compute the same result as the original for all 21282^{128} possible inputs? Ask whether an input exists on which they differ.
  • Finding software bugs. Can this loop, executed at most 50 times, overflow an index? Tools such as CBMC translate C programs into formulas and ask the solver for an execution violating the assertion.
  • Package dependencies. Choosing compatible versions of hundreds of packages means satisfying constraints such as “if I install A 2.1, I need B ≥ 1.4 and not C.” DNF and zypper’s dependency resolver, libsolv, is a SAT solver.
  • Mathematics. In 2016 Heule, Kullmann, and Marek used a solver to prove that the integers from 1 to 7825 cannot be colored in two colors without a monochromatic Pythagorean triple, while those up to 7824 can. The unsatisfiability certificate occupied about 200 TB (Heule, Kullmann and Marek, 2016).

There are direct connections to what you will build later. Formal verification of ReLU neural networks is formulated as SAT, SMT, or integer programming (covered in m30), and language-model agents increasingly delegate to an exact solver when an answer must be correct and checkable, such as an executable verifier.

In every case the human work is modeling: choose variables with precise meanings and write constraints as clauses so every solution corresponds to an answer and every answer to a solution. This lesson covers exactly that: what the problem is, how to convert any formula or circuit to CNF without size explosion, how to encode combinatorial problems and cardinality constraints, which cases are solvable in linear time, and how SAT verifies hardware and software. The next lesson, resolution and DPLL, opens the solver’s box.

The SAT problem

Recall conjunctive normal form from lesson 1: a literal is a variable xx or its negation ¬x\lnot x; a clause is a disjunction of literals, treated as a set; a CNF is a conjunction of clauses, treated as a set of clauses. An assignment α:{x1,…,xn}→{0,1}\alpha: \{x_1, \dots, x_n\} \to \{0, 1\} satisfies a clause if it makes at least one literal true, and satisfies the CNF if it satisfies every clause.

Three observations establish the setting.

A model is a cheap certificate. Checking that α\alpha satisfies FF costs O(∣F∣)\bigO(\abs{F}), where ∣F∣\abs{F} is the total number of literal occurrences: scan each clause until a true literal is found. Finding a model can be hard; verifying one is not. Thus a solver reporting “satisfiable” need not be trusted: it gives the assignment and you check it.

No short unsatisfiability certificates are known. To convince you there is no model, the solver cannot show an assignment. It can give a proof (a resolution refutation, covered next lesson, or its industrial version, DRAT proofs), but no proof system is known in which every unsatisfiable formula has a polynomial-size proof: existence of one is equivalent to NP=coNP\text{NP} = \text{coNP} (Cook and Reckhow, 1979). The 200 TB Pythagorean certificate is not anomalous: in the worst case that is to be expected.

Validity and consequence reduce to unsatisfiability. By lesson 1, φ\varphi is valid if and only if ¬φ\lnot\varphi is unsatisfiable, and Γ⊨φ\Gamma \models \varphi if and only if Γ∪{¬φ}\Gamma \cup \{\lnot\varphi\} is unsatisfiable. Thus a SAT solver is also a prover: negate a claim and ask for a model; if none exists, it is proved.

The DIMACS format

Solvers read the same text format, DIMACS CNF. Variables are integers 1,…,n1, \dots, n; literal xix_i is written i and ¬xi\lnot x_i, -i; each clause is a line ending in 0; header p cnf n m declares nn variables and mm clauses, and lines starting with c are comments.

c (p ∨ ¬q) ∧ (q ∨ r) ∧ (¬p ∨ ¬r) ∧ (q ∨ ¬r)
p cnf 3 4
1 -2 0
2 3 0
-1 -3 0
2 -3 0

A solver responds s SATISFIABLE followed by v 1 2 -3 0 (model p=q=1p = q = 1, r=0r = 0), or s UNSATISFIABLE. The simplicity is deliberate: anything you want solved must reach this form, and the rest of the lesson covers how to get there correctly.

The hard and the easy

The proof of the Cook–Levin theorem and the theory of NP-completeness are in m08. Two practical consequences matter here. First, no polynomial-time algorithm is expected for SAT in general, and the best known worst-case algorithms for 3-SAT remain exponential (on the order of 1.3n1.3^n). Second, more surprisingly, modern solvers (CDCL, covered in conflict analysis) routinely solve industrial instances with hundreds of thousands of variables. Worst cases exist, but structured problems rarely are worst cases. Below are two islands without this difficulty: 2-SAT and Horn-SAT are decided in linear time.

Tseitin transformation: CNF without explosion

Almost nothing arrives in CNF. A circuit, a specification, a program condition: all are arbitrary formulas. Lesson 1’s conversion using De Morgan’s laws and distributivity produces an equivalent CNF, but there you proved (x1∧y1)∨⋯∨(xn∧yn)(x_1 \land y_1) \lor \cdots \lor (x_n \land y_n) has no equivalent CNF with fewer than 2n2^n clauses. Parity x1⊕⋯⊕xnx_1 \oplus \cdots \oplus x_n is worse: every equivalent CNF needs its 2n−12^{n-1} clauses of nn literals, one for each even-parity assignment it must exclude (any clause with fewer than nn literals would also exclude odd-parity assignments).

The way out is to give up equivalence and retain what SAT needs. G. S. Tseitin’s idea (1968) is to give each subformula a name: a new variable gg per binary connective, with a few clauses forcing gg to equal the subformula.

For an AND gate, g↔(a∧b)g \leftrightarrow (a \land b) decomposes into two implications, each already nearly in CNF:

g→(a∧b)  ≡  (¬g∨a)∧(¬g∨b),(a∧b)→g  ≡  (¬a∨¬b∨g).g \to (a \land b) \;\equiv\; (\lnot g \lor a) \land (\lnot g \lor b), \qquad (a \land b) \to g \;\equiv\; (\lnot a \lor \lnot b \lor g).

The other connectives follow similarly:

GateClauses for g→defg \to \text{def}Clauses for def→g\text{def} \to g
g↔(a∧b)g \leftrightarrow (a \land b)(¬g∨a)(\lnot g \lor a), (¬g∨b)(\lnot g \lor b)(g∨¬a∨¬b)(g \lor \lnot a \lor \lnot b)
g↔(a∨b)g \leftrightarrow (a \lor b)(¬g∨a∨b)(\lnot g \lor a \lor b)(g∨¬a)(g \lor \lnot a), (g∨¬b)(g \lor \lnot b)
g↔(a⊕b)g \leftrightarrow (a \oplus b)(¬g∨a∨b)(\lnot g \lor a \lor b), (¬g∨¬a∨¬b)(\lnot g \lor \lnot a \lor \lnot b)(g∨¬a∨b)(g \lor \lnot a \lor b), (g∨a∨¬b)(g \lor a \lor \lnot b)
g↔(a→b)g \leftrightarrow (a \to b)(¬g∨¬a∨b)(\lnot g \lor \lnot a \lor b)(g∨a)(g \lor a), (g∨¬b)(g \lor \lnot b)

Negation needs no variable: ¬a\lnot a is already a literal, so a negated subformula is represented by its gate’s negated literal. Finally add the unit clause containing the root variable, requiring the entire formula to be true.

InteractiveTseitin gate by gate
root
sab∧g₁∧g₂∨g₃
Finally, unit clause g3g_{3} requires the root to be true. Each clause has at most 3 literals and there are at most 4 per gate: the size is linear in φ\varphi.
Accumulated CNF (10 clauses)
(¬g1∨s)(\lnot g_{1} \lor s)(¬g1∨a)(\lnot g_{1} \lor a)(g1∨¬s∨¬a)(g_{1} \lor \lnot s \lor \lnot a)(¬g2∨¬s)(\lnot g_{2} \lor \lnot s)(¬g2∨b)(\lnot g_{2} \lor b)(g2∨s∨¬b)(g_{2} \lor s \lor \lnot b)(¬g3∨g1∨g2)(\lnot g_{3} \lor g_{1} \lor g_{2})(g3∨¬g1)(g_{3} \lor \lnot g_{1})(g3∨¬g2)(g_{3} \lor \lnot g_{2})g3g_{3}
Family
10
  • CNF by distribution
  • Tseitin
  • Plaisted-Greenbaum
n=10n = 10: distribution 512 clauses; Tseitin 37; Plaisted-Greenbaum 35.
  • encoded gate (its color marks its clauses)
  • current gate
  • root: unit clause
Enter φ using ¬ ∧ ∨ ⊕ → ↔ (or ! & | ^ -> <->)
Variables (from φ + gates)3 + 3
Clauses / literals, Tseitin10 / 22
Clauses, CNF by distribution4
Models of φ\varphi4
Models of Tseitin CNF4
Each model of φ\varphi has a unique extension (the gkg_k are determined), so the 4 models correspond one to one.
Choose a formula or write your own. Above is its circuit: leaves are variables, each circle a gate, and a small circle at an input indicates negation. Play it: each gate receives its variable gkg_k and defining clauses, in its color. Check the readouts: full Tseitin CNF has exactly as many models as φ\varphi; enable Plaisted–Greenbaum in the ‘mixed connectives’ example and the model count grows even though the formula remains equisatisfiable. Below, choose a family and raise nn: distribution grows as a line on a logarithmic scale (exponential), Tseitin as an almost flat curve (linear). With the shared subformula, notice a∧ba \land b receives one variable.
Proof

(1) Use structural induction on subformulas, leaves to root. For a variable, ℓx=x\ell_x = x and there is no choice. For ¬ψ\lnot\psi, ℓ¬ψ=¬ℓψ\ell_{\lnot\psi} = \lnot\ell_\psi equals 1−α(ψ)=α(¬ψ)1 - \alpha(\psi) = \alpha(\lnot\psi) by hypothesis. For ψ=ψ1∘ψ2\psi = \psi_1 \circ \psi_2, the defining clauses are equivalent to gψ↔(ℓψ1∘ℓψ2)g_\psi \leftrightarrow (\ell_{\psi_1} \circ \ell_{\psi_2}); since ℓψ1\ell_{\psi_1} and ℓψ2\ell_{\psi_2} already have forced values α(ψ1)\alpha(\psi_1) and α(ψ2)\alpha(\psi_2), the only choice of gψg_\psi satisfying them is α(ψ1)∘α(ψ2)=α(ψ)\alpha(\psi_1) \circ \alpha(\psi_2) = \alpha(\psi). Identical subformulas have the same forced value, so sharing the variable causes no conflict.

(2) Any model β\beta of T(φ)\mathcal{T}(\varphi) satisfies the definitions, so by (1) it equals the extension α^\hat\alpha of its restriction α=β∣vars(φ)\alpha = \beta|_{\text{vars}(\varphi)}, and the root clause says α^(ℓφ)=α(φ)=1\hat\alpha(\ell_\varphi) = \alpha(\varphi) = 1. Conversely, if α⊨φ\alpha \models \varphi, extension α^\hat\alpha satisfies the definitions and α^(ℓφ)=1\hat\alpha(\ell_\varphi) = 1. Correspondence α↦α^\alpha \mapsto \hat\alpha is a bijection between models.

(3) Each binary connective contributes at most 4 clauses of at most 3 literals (the table), and the root contributes one; negations contribute nothing. A traversal of the tree of φ\varphi with a dictionary to detect repeated subformulas constructs everything in linear time.

∎

Three consequences used daily:

  • SAT reduces to 3-SAT in linear time. Every clause of T(φ)\mathcal{T}(\varphi) has at most 3 literals. This is the reduction of SAT to 3-SAT.
  • Circuits translate directly. A Boolean circuit is a DAG of gates: one variable per gate yields a CNF linear in circuit size, which may be exponentially smaller than the equivalent formula tree. Hardware verifiers do this, usually over AND-inverter graphs (AIGs) with shared substructures.
  • Model count is preserved. By (2), counting models of T(φ)\mathcal{T}(\varphi) means counting those of φ\varphi. This underlies model counters used in probabilistic inference.

Plaisted–Greenbaum: half the clauses

If a subformula occurs only under an even number of negations (positive polarity), half gψ→def⁡g_\psi \to \operatorname{def} suffices: the solver may set gψ=0g_\psi = 0 when the subformula is true, but that never helps satisfy the root because φ\varphi is monotone increasing in that subformula. With negative polarity the other half suffices, and with both (under ⊕\oplus or ↔\leftrightarrow) both are required. This is Plaisted and Greenbaum’s encoding (1986). It remains equisatisfiable with fewer clauses, but no longer preserves model count: in the figure, “mixed connectives” goes from 5 models to 7. In practice, the saving in clauses is sometimes offset by worse propagation, and many solvers prefer the full version.

Encoding problems

Encoding a problem in SAT always has three steps: choose variables and their meanings, write each constraint as clauses, and decode the model. Encoding problems in SAT is an art with rules: correctness is proved (each model is a solution and each solution yields a model), and efficiency depends on how much unit propagation deduces from clauses. Every solver repeatedly applies this inference rule between decisions: if all literals of a clause are false except one, the last must be true; if all are false, there is a conflict. The next lesson studies it in depth; here it suffices to know it is cheap and chains.

Graph coloring

To decide whether a graph G=(V,E)G = (V, E) admits a coloring with kk colors, use a variable xv,cx_{v,c} per (vertex, color) pair, meaning “vv has color cc,” and two families:

(xv,1∨⋯∨xv,k)⏟cada veˊrtice tiene alguˊn color∀v∈V,(¬xu,c∨¬xv,c)⏟extremos de distinto color∀{u,v}∈E, ∀c.\underbrace{(x_{v,1} \lor \cdots \lor x_{v,k})}_{\text{cada vértice tiene algún color}} \quad \forall v \in V, \qquad \underbrace{(\lnot x_{u,c} \lor \lnot x_{v,c})}_{\text{extremos de distinto color}} \quad \forall \{u, v\} \in E,\ \forall c.

There are ∣V∣+k∣E∣\abs{V} + k\abs{E} clauses. Notice what is not needed: saying each vertex has at most one color. If a model gives a vertex several colors, keeping any one still satisfies edge clauses, because removing a color cannot create a conflict. Adding that family is not an error, but is redundant. The Petersen graph, for example, gives an unsatisfiable CNF with 2 colors (it has odd cycles) and a satisfiable one with 3.

N queens and Sudoku

To place NN nonattacking queens, xr,cx_{r,c} says “there is a queen in row rr and column cc.” Each row has at least one queen (one NN-literal clause), and each row, column, and diagonal has at most one (one binary clause per pair of squares). Counting, a diagonal of length ℓ\ell contributes (ℓ2)\binom{\ell}{2} pairs, and the staircase identity gives ∑ℓ=1N−1(ℓ2)=(N3)\sum_{\ell=1}^{N-1}\binom{\ell}{2} = \binom{N}{3}, so the total is

N+2N(N2)+2(2(N3)+(N2)),que para N=8 son 8+448+280=736 claˊusulas.N + 2N\binom{N}{2} + 2\Big(2\binom{N}{3} + \binom{N}{2}\Big), \qquad \text{que para } N = 8 \text{ son } 8 + 448 + 280 = 736 \text{ cláusulas.}

Sudoku 9×99\times 9 uses xr,c,vx_{r,c,v}, “cell (r,c)(r, c) contains vv”: 93=7299^3 = 729 variables. There are several candidate families: each cell has at least and at most one value; every row, column, and block contains each value at least and at most once; and clues as unit clauses. Are they all needed? No.

Proof

Fix a row and count in two ways the number PP of (cell, value) pairs in that row with xr,c,v=1x_{r,c,v} = 1. By cells: each of the 9 cells has at least one value, so P≥9P \ge 9. By values: each of the 9 values appears at most once in the row, so P≤9P \le 9. Thus P=9P = 9, and since each cell contributes at least 1 and the total is 9, each contributes exactly 1. By the same equality, each value contributes exactly 1: it appears. This is the pigeonhole principle in both directions. The same argument works for columns and blocks.

∎

The minimal encoding has 81+3⋅81⋅36=882981 + 3 \cdot 81 \cdot 36 = 8829 clauses and the extended encoding, with redundant families, 11 98811\,988. Yet the extended version is often better for the solver: the clause “5 is in some cell of row 3” becomes unit as soon as the other cells are ruled out, directly propagating the rule enthusiasts call “hidden single.” In the minimal version this deduction needs the theorem’s counting argument, which unit propagation cannot perform. General lesson: redundant clauses do not change the solution set, but can greatly change what the solver deduces without search.

InteractiveFrom Sudoku and N queens to CNF
537619598686348317266284195879
Clause families
familytotalwith cellCell: at least one value811Row: each value at most once291672Column: each value at most once291672Block: each value at most once291672Clues (unit clauses)300total8859217
Cell (5,5)(5, 5): x5,5,1∨x5,5,2∨⋯∨x5,5,9x_{5,5,1} \lor x_{5,5,2} \lor \cdots \lor x_{5,5,9}. With value 1, each highlighted cell (i,j)(i, j) contributes ¬x5,5,1∨¬xi,j,1\lnot x_{5,5,1} \lor \lnot x_{i,j,1}.
  • selected cell
  • shares clauses with it
  • value found by solver
Problem
Variables729
Clauses8859
Literals18 255
Select a cell: cells sharing clauses are highlighted and the table breaks down how many clauses in each family mention its variables. Change clues with the keyboard and click ‘Solve’ (Resolver): the module's DPLL returns a solution and checks uniqueness by adding a clause forbidding it. Try the 4×4 ‘many solutions’ and ‘contradictory’ examples. Enable extended encoding and compare counts. For N queens, count solutions with and without symmetry breaking: for N=8N = 8 they go from 92 to 46.

Bounded-horizon planning

The same pattern works for problems with time. A planning problem has facts (the box is in room 2, the arm is free) and actions with preconditions and effects. Fix horizon TT and create variables hf,th_{f,t}, “fact ff is true at time tt,” and ao,ta_{o,t}, “action oo is executed at step tt.” Clauses state: the initial state (units at t=0t = 0), goal (units at t=Tt = T), each action implies its preconditions at tt (¬ao,t∨hf,t\lnot a_{o,t} \lor h_{f,t}) and effects at t+1t + 1 (¬ao,t∨hf,t+1\lnot a_{o,t} \lor h_{f,t+1} for additions, ¬ao,t∨¬hf,t+1\lnot a_{o,t} \lor \lnot h_{f,t+1} for deletions), at most one action per step, and frame axioms: if a fact changes between tt and t+1t + 1, an action changing it was executed. For a fact becoming true, hf,t∨¬hf,t+1∨⋁o lo an˜adeao,th_{f,t} \lor \lnot h_{f,t+1} \lor \bigvee_{o \text{ lo añade}} a_{o,t}, and for one becoming false, ¬hf,t∨hf,t+1∨⋁o lo borraao,t\lnot h_{f,t} \lor h_{f,t+1} \lor \bigvee_{o \text{ lo borra}} a_{o,t}. A model is a plan of at most TT actions (steps without action change nothing); if no model exists, no plan that short exists and one tries T+1T + 1. This is SATPLAN’s idea (Kautz and Selman, 1992), revisited in planning as satisfiability. Forgetting frame axioms is the classic error: without them facts appear and disappear between steps and the solver finds impossible plans.

Breaking symmetries

An encoding is symmetric if some permutation of variables maps models to models. In coloring, permuting the kk colors is such a symmetry: every coloring has k!k! copies. If the instance is satisfiable this matters little, but if unsatisfiable the solver may have to refute each copy separately, multiplying worst-case search by k!k!. The remedy is to add clauses removing copies without eliminating every copy of any solution:

  • In coloring, if KK is a clique, fix its colors: the first vertex of KK takes color 1, the second 2, and so on. Without a known clique, a weaker rule works: vertex ii (in a fixed order) may only use colors 1,…,i1, \dots, i. This is correct because, renaming colors by first occurrence, vertex ii uses at most color number ii.
  • In N queens, use left–right reflection: require the first-row queen in the left half (or center column, if NN is odd). With even NN, no solution is its own reflection, so the solution count is exactly halved.
  • In the pigeonhole problem PHPnn+1\text{PHP}^{n+1}_n (put n+1n + 1 pigeons in nn holes), holes are interchangeable: pigeon ii may only go into holes 1,…,i1, \dots, i.

The effect can be enormous. Pigeonhole is the extreme example: Haken proved in 1985 that every resolution refutation of PHPnn+1\text{PHP}^{n+1}_n has size exponential in nn (a proof complexity result), so no resolution-based solver can do well. With the symmetry breaking above, however, unit propagation refutes it without a single decision: pigeon 1 goes to hole 1, 2 to 2, and n+1n + 1 has nowhere to go. You will measure this below.

Cardinality constraints

“At least one,” “at most one,” and “exactly one” constraints appear in almost every encoding, and the general version, “at most kk of these nn variables,” in planning (at most kk machines at once), configuration, and optimization. Writing them well can determine whether a CNF fits in memory.

At least one is one clause: (x1∨⋯∨xn)(x_1 \lor \cdots \lor x_n). Pairwise at most one consists of (n2)\binom{n}{2} clauses (¬xi∨¬xj)(\lnot x_i \lor \lnot x_j): quadratic, with no fresh variables and the best possible propagation (as soon as one xix_i is true, all others become false). For at most kk, the direct generalization forbids each subset of k+1k + 1 true variables, with (nk+1)\binom{n}{k+1} clauses: with n=100n = 100 and k=5k = 5 that is 1.2×1091.2 \times 10^{9}.

The clauses read as a unary adder circuit advancing left to right: the counter retains what it had (carry), rises one step when xix_i is true (addition), and the cutoff clause forbids xix_i being true when kk were already true earlier.

InteractiveThe sequential counter
≥ 1≥ 2s₁,₁s₁,₂s₂,₁s₂,₂s₃,₁s₃,₂s₄,₁s₄,₂s₅,₁s₅,₂s₆,₁s₆,₂s₇,₁s₇,₂x₁x₂x₃x₄x₅x₆x₇x₈
  • x true
  • x forced to 0 (bound reached)
  • s forced to 1
  • carry: ¬s(i−1,j) ∨ s(i,j)
  • sum: ¬x(i) ∨ ¬s(i−1,j−1) ∨ s(i,j)
  • violated cutoff
8
2
True / bound kk2 / 2
Counter clauses, 2nk+n−3k−12nk + n - 3k - 133
Auxiliary variables, (n−1)k(n - 1)k14
Without auxiliaries, (nk+1)\binom{n}{k+1} clauses of 3 literals56
All clauses hold: 2 = 2 are true. The bound is reached, and unit propagation forces every other xx to 0 (gray with dashed border): later ones through the cutoff, earlier ones through the sum read backwards.
Click the xix_i to turn them on. Each row of the register is a counter step: si,js_{i,j} lights when at least jj of x1,…,xix_1, \dots, x_i are true, and lit arrows are clauses just used by unit propagation: horizontal for carry, diagonal (and from xix_i) for addition. Initially kk are already true, and the remaining xx variables are gray: propagation forces them to 0. Turn on one extra true variable: the cutoff clause fails exactly at the variable making k+1k + 1. Compare the counter's 2nk+n−3k−12nk + n - 3k - 1 clauses with the (nk+1)\binom{n}{k+1} of the encoding without auxiliaries.
Proof

Write ci=∣{t≤i:xt=1}∣c_i = \abs{\{t \le i : x_t = 1\}}. If cn≤kc_n \le k, extension si,j=[ci≥j]s_{i,j} = [c_i \ge j] satisfies every clause: carry because ci≥ci−1c_i \ge c_{i-1}; addition because xi=1x_i = 1 and ci−1≥j−1c_{i-1} \ge j - 1 give ci≥jc_i \ge j; units ¬s1,j\lnot s_{1,j} because c1≤1c_1 \le 1; and cutoff because xi=1x_i = 1 and ci−1≥kc_{i-1} \ge k would give ci≥k+1c_i \ge k + 1. Conversely, in any model induction on ii proves si,j≥[ci≥j]s_{i,j} \ge [c_i \ge j] (addition and carry clauses push each step upward). If cn≥k+1c_n \ge k + 1, let ii be the position of true variable number k+1k + 1: then ci−1=kc_{i-1} = k, hence si−1,k=1s_{i-1,k} = 1 and xi=1x_i = 1, and the cutoff clause of ii is false. For the second part, let p1<⋯<pkp_1 < \cdots < p_k be positions of true variables. Forward, xpjx_{p_j} and spj−1,j−1s_{p_j-1,j-1} force spj,js_{p_j,j} by addition, and carry copies it rightward; thus st−1,k=1s_{t-1,k} = 1 for every t>pkt > p_k, and cutoff at tt leaves ¬xt\lnot x_t unit. Backward, cutoff at pkp_k gives ¬spk−1,k\lnot s_{p_k-1,k}, carry read backwards (¬si,j⇒¬si−1,j\lnot s_{i,j} \Rightarrow \lnot s_{i-1,j}) takes it leftward, and at each pjp_j addition read backwards (xpj=1x_{p_j} = 1 and spj,j+1=0s_{p_j,j+1} = 0) gives ¬spj−1,j\lnot s_{p_j-1,j}: in total si,j=0s_{i,j} = 0 for every i<pji < p_j. If pj−1<t<pjp_{j-1} < t < p_j (with p0=0p_0 = 0), then st−1,j−1=1s_{t-1,j-1} = 1 and st,j=0s_{t,j} = 0, and the addition clause at (t,j)(t, j), or (¬xt∨st,1)(\lnot x_t \lor s_{t,1}) if j=1j = 1, leaves ¬xt\lnot x_t unit.

∎

The table summarizes cost for “at most one” (k=1k = 1), where the counter has 3n−43n - 4 clauses with n−1n - 1 auxiliaries:

nnpairwise, (n2)\binom{n}{2}counter, 3n−43n - 4
51011
104526
1004950296
1000499 5002996

Below n=6n = 6 pairwise encoding wins, and in practice it is used up to n≈10n \approx 10: binary clauses are cheapest to propagate. Many other encodings trade off clauses, variables, and propagation strength differently (commander, product, binary with ⌈log⁡2n⌉\lceil \log_2 n\rceil auxiliaries, totalizers, sorting networks), and libraries provide them all. “At least kk” is “at most n−kn - k” of the negations, and “exactly kk” is the conjunction of both.

Tractable cases: 2-SAT and Horn-SAT

2-SAT and the implication graph

If every clause has at most two literals, clause (a∨b)(a \lor b) states exactly two implications: ¬a→b\lnot a \to b and ¬b→a\lnot b \to a. This turns the problem into a graph problem.

The graph has a symmetry governing everything: edge u→vu \to v exists if and only if edge ¬v→¬u\lnot v \to \lnot u exists (both come from the same clause). Therefore there is a path u⇝vu \rightsquigarrow v if and only if there is a path ¬v⇝¬u\lnot v \rightsquigarrow \lnot u. Every edge is an implication satisfied by every model: if uu is true in a model, vv is too, and by induction on length the same holds for paths.

Proof

If xx and ¬x\lnot x share a component, paths x⇝¬xx \rightsquigarrow \lnot x and ¬x⇝x\lnot x \rightsquigarrow x exist. In a model with x=1x = 1, the first path forces ¬x=1\lnot x = 1; with x=0x = 0, ¬x=1\lnot x = 1 and the second forces x=1x = 1. There is no model.

Now suppose no variable shares a component with its negation. The condensation is a DAG and has a topological order; write τ(ℓ)\tau(\ell) for the position of the component of literal ℓ\ell. If u→vu \to v is an edge, τ(u)≤τ(v)\tau(u) \le \tau(v) (equal if in the same component). Assignment ℓ=1  ⟺  τ(ℓ)>τ(¬ℓ)\ell = 1 \iff \tau(\ell) > \tau(\lnot\ell) is well-defined because τ(x)≠τ(¬x)\tau(x) \ne \tau(\lnot x), and gives opposite values to xx and ¬x\lnot x. It remains to show no edge u→vu \to v has u=1u = 1 and v=0v = 0, equivalent to all clauses being satisfied. Otherwise τ(u)>τ(¬u)\tau(u) > \tau(\lnot u) and τ(v)<τ(¬v)\tau(v) < \tau(\lnot v). The symmetric edge ¬v→¬u\lnot v \to \lnot u gives τ(¬v)≤τ(¬u)\tau(\lnot v) \le \tau(\lnot u), and chaining,

τ(¬u)<τ(u)≤τ(v)<τ(¬v)≤τ(¬u),\tau(\lnot u) < \tau(u) \le \tau(v) < \tau(\lnot v) \le \tau(\lnot u),

a contradiction. Tarjan’s algorithm computes components in O(n+m)\bigO(n + m) and numbers them in reverse topological order, so no separate step is needed for τ\tau.

∎
InteractiveThe 2-SAT implication graph
x₁verdadero¬x₁falsox₂verdadero¬x₂falsox₃verdadero¬x₃falsox₄falso¬x₄verdadero
Cláusulas (cada una, dos aristas)
(¬x1∨x2)(\lnot x_{1} \lor x_{2})(¬x2∨x3)(\lnot x_{2} \lor x_{3})(¬x3∨x1)(\lnot x_{3} \lor x_{1})(x1∨x4)(x_{1} \lor x_{4})(¬x4∨¬x2)(\lnot x_{4} \lor \lnot x_{2})(x1∨x2)(x_{1} \lor x_{2})
Condensation in topological order: {¬x1,¬x2,¬x3,x4}\{\lnot x_{1}, \lnot x_{2}, \lnot x_{3}, x_{4}\} → {x1,x2,x3,¬x4}\{x_{1}, x_{2}, x_{3}, \lnot x_{4}\}
  • component with several literals
  • edge between components
  • cycle x ⇝ ¬x ⇝ x
Clauses / edges6 / 12
Strongly connected components2
Satisfiable. Each xix_i is true if its component comes after that of ¬xi\lnot x_i in topological order: x1=1x_{1} = 1, x2=1x_{2} = 1, x3=1x_{3} = 1, x4=0x_{4} = 0. Check: all 6 clauses hold ✓.
Each literal xix_i is antipodal to ¬xi\lnot x_i, so symmetry u→v  ⟺  ¬v→¬uu \to v \iff \lnot v \to \lnot u appears as central symmetry with arrows reversed. Strongly connected components with more than one literal are filled with color. Hover over a clause to see its two edges and remove it with ✕. In ‘short contradiction’, inspect the highlighted cycle; remove one clause and see the component split and an assignment appear. Enable condensation view: components align topologically and every true literal lies to the right of its negation.

Why does this work with two literals but not three? Resolving two binary clauses, (a∨b)(a \lor b) and (¬b∨c)(\lnot b \lor c), gives another binary clause (a∨c)(a \lor c): it composes implications ¬a→b→c\lnot a \to b \to c. There are O(n2)\bigO(n^2) possible binary clauses, so resolution closure is polynomial, and the graph computes it implicitly. With three-literal clauses, a resolvent of two can have four literals, and that growth opens the door to NP-completeness. The boundary is fine: maximizing the number of satisfied clauses of a 2-CNF (MAX-2-SAT) is already NP-hard.

Horn-SAT and the least model

Horn formulas are the logic of rules: Datalog, Prolog without negation, permission systems (“if you are an editor, you may publish”), and type inference. They are decided by the simplest imaginable algorithm: unit propagation from all false. Start every variable at 0; while a rule or fact has all premises at 1 and its conclusion at 0, set the conclusion to 1. If a constraint ever has all its premises at 1, the formula is unsatisfiable; if the process stops without that, the result is a model.

The proof is the lesson’s last guided exercise. The key idea is that every variable the algorithm sets to 1 is forced: true in every model, by induction on the order in which it is added. This gives both correctness of “unsatisfiable” and minimality. The least model is unique and is the intersection of all models, something absent for general formulas: (p∨q)(p \lor q) has two minimal models, {p}\{p\} and {q}\{q\}. This same structure, extended to arithmetic, gives constrained Horn clauses used to verify programs today.

Bounded verification

Circuit equivalence with a miter

You have two circuits ff and gg with the same inputs x\vb{x} and outputs f1,…,fmf_1, \dots, f_m and g1,…,gmg_1, \dots, g_m: the original and one produced by a synthesis tool, manual optimization, or compiler. Do they compute the same thing? With ∣x∣=128\abs{\vb{x}} = 128 one cannot test all 21282^{128} inputs. The standard construction is the miter: join corresponding outputs with XOR and combine them with OR,

M(x)=⋁i=1m(fi(x)⊕gi(x)),M(\vb{x}) = \bigvee_{i=1}^{m} \big(f_i(\vb{x}) \oplus g_i(\vb{x})\big),

and ask whether T(M)\mathcal{T}(M) is satisfiable. If so, the model contains a concrete input on which the circuits differ: a counterexample that can be simulated and debugged. Otherwise they are equivalent, and the solver’s refutation is the proof. This is the practical version of the question from the BDD lesson; BDDs are canonical but may grow exponentially (multipliers are the typical case), and industry combines both techniques.

InteractiveAre these two circuits equivalent?
referenceoptimized (click a gate)mitera₀b₀a₁b₁XORANDXORANDXORANDORNANDORXNORANDORNOTANDXNORANDXORXORXORXORs₀s₁c₂s₀s₁c₂OR¿= 1?
  • reference adder
  • optimized adder
  • modified gate
  • wire at 1 in the counterexample
Variables in the miter CNF25
Clauses73
Distinguishing inputs (exhaustive count)1 of 16
Above is a reference 2-bit adder; below, an ‘optimized’ one with different structure (NAND and XNOR for sum, majority for carry). Corresponding outputs are compared by XOR and combined in the miter's OR. Click ‘Search with SAT’ (Buscar con SAT): the solver returns an input distinguishing them and the figure simulates it with each wire's value. The initial bug appears in only 1 of 16 inputs: a small random test probably misses it. Try ‘Majority: OR for XOR’: it looks like a bug but is not, and SAT proves it. What about both modifications together? Click optimized gates to change their type and invent your own bugs.

The modification “Majority: OR for XOR” illustrates something common in circuit optimization: in carry c2=a1b1∨c1(a1∨b1)c_2 = a_1 b_1 \lor c_1 (a_1 \lor b_1), a1∨b1a_1 \lor b_1 can be replaced by a1⊕b1a_1 \oplus b_1 without changing the function because the case where they differ (a1=b1=1a_1 = b_1 = 1) is already covered by the first term. Then the two terms are mutually exclusive, so the final OR can be replaced by XOR. Alone, the second change is a bug; together with the first, it is not. Reasoning by hand is fragile; the miter decides it.

Unrolling a system: BMC

A system evolving over time (a sequential circuit, a program with a loop, a protocol) is described by a state-variable vector s\vb{s}, initial predicate I(s)I(\vb{s}), transition relation T(s,s′)T(\vb{s}, \vb{s}'), and safety property P(s)P(\vb{s}) that should always hold. Bounded model checking (BMC; Biere, Cimatti, Clarke, and Zhu, 1999) copies state variables k+1k + 1 times and asks about the formula

BMC⁡k=I(s0)∧⋀t=0k−1T(st,st+1)∧⋁t=0k¬P(st).\operatorname{BMC}_k = I(\vb{s}_0) \land \bigwedge_{t=0}^{k-1} T(\vb{s}_t, \vb{s}_{t+1}) \land \bigvee_{t=0}^{k} \lnot P(\vb{s}_t).

It is satisfiable if and only if an execution of at most kk steps violates the property, and the model is that execution step by step. In a program, integer variables are represented as bit vectors (32 Boolean variables per int), each operation as a circuit (adder, comparator), and the loop is unrolled kk times. This is how CBMC and related tools work.

An example you will implement: x = 0; repetir: x = x + 3 with 4-bit x (arithmetic modulo 16) and property x≠7x \ne 7. With k≤12k \le 12, BMC⁡k\operatorname{BMC}_k is unsatisfiable. With k=13k = 13, the solver returns trace 0,3,6,9,12,15,2,5,8,11,14,1,4,70, 3, 6, 9, 12, 15, 2, 5, 8, 11, 14, 1, 4, 7. The bug existed all along, but at 13 steps.

k-induction: the bridge to invariants

The usual way to go from “no bug through kk” to “no bug ever” is induction. A property PP is an inductive invariant if it holds initially and is preserved at every step. Both conditions are SAT questions:

base: I(s)∧¬P(s)  insatisfacible,paso: P(s)∧T(s,s′)∧¬P(s′)  insatisfacible.\text{base: } I(\vb{s}) \land \lnot P(\vb{s}) \ \text{ insatisfacible}, \qquad \text{paso: } P(\vb{s}) \land T(\vb{s}, \vb{s}') \land \lnot P(\vb{s}') \ \text{ insatisfacible}.

The step is checked from any state satisfying PP, not just reachable states. Thus a true property need not be inductive: in x = 0; repetir: x = x + 2, property x≠15x \ne 15 is true (x is always even), but the step fails on unreachable state x=13x = 13, which satisfies PP and goes to 15. This is exactly the problem of strengthening the induction hypothesis: strengthening to “x is even” makes the property inductive.

k-induction (Sheeran, Singh, and Stålmarck, 2000) generalizes the step: if PP holds in kk consecutive states linked by TT, it holds in the next. The base is BMC⁡k−1\operatorname{BMC}_{k-1}. In the example, the step fails for k≤7k \le 7 (with odd chain 1,3,…,13,151, 3, \dots, 13, 15 as an induction counterexample) and holds for k=8k = 8: eight consecutive odd numbers traverse all odd numbers modulo 16, including 15. Thus x≠15x \ne 15 is 8-inductive, proved without inventing an invariant. Requiring path states to be distinct makes k-induction complete for finite systems, though the needed kk can be enormous; current methods such as IC3 (Bradley, 2011) incrementally construct the strengthened invariant with a SAT solver.

Implementation from scratch

Start with infrastructure: a class CNF with variables numbered as in DIMACS, reading and writing that format, a certificate checker, and a function solve delegating to sympy’s DPLL (satisfiable with algorithm="dpll2"). Passing CNF already encoded as integers avoids sympy rebuilding a symbolic expression with thousands of clauses.

[ ]CNF, DIMACS, and certificatesBrowser
from sympy import Symbol
from sympy.logic.inference import satisfiable
from sympy.assumptions.cnf import EncodedCNF

class CNF:
    """CNF con variables 1..n (convenio DIMACS): un literal es +v o -v."""
    def __init__(self):
        self.n = 0
        self.clauses = []
        self.names = {}

    def new_var(self, name=None):
        self.n += 1
        if name is not None:
            self.names[self.n] = name
        return self.n

    def add(self, clause):
        self.clauses.append(list(clause))

    def to_dimacs(self):
        lines = [f"p cnf {self.n} {len(self.clauses)}"]
        lines += [" ".join(map(str, c)) + " 0" for c in self.clauses]
        return "\n".join(lines) + "\n"

    @classmethod
    def from_dimacs(cls, text):
        f, lits = cls(), []
        for line in text.splitlines():
            line = line.strip()
            if not line or line[0] in "c%":
                continue
            if line.startswith("p"):
                f.n = int(line.split()[2])
                continue
            for tok in line.split():
                if tok == "0":
                    f.add(lits)
                    lits = []
                else:
                    lits.append(int(tok))
        return f

    def __repr__(self):
        return f"CNF({self.n} variables, {len(self.clauses)} cláusulas)"

def satisfies(clauses, model):
    """model: conjunto de literales verdaderos. Mira cada literal una vez: tiempo lineal."""
    return all(any(l in model for l in c) for c in clauses)

def solve(cnf):
    """DPLL de sympy (dpll2). Devuelve el modelo como conjunto de literales, o None si es insatisfacible."""
    enc = EncodedCNF([set(c) for c in cnf.clauses], {Symbol(f"v{i}"): i for i in range(1, cnf.n + 1)})
    m = satisfiable(enc, algorithm="dpll2")
    if m is False:
        return None
    return {i if m.get(Symbol(f"v{i}"), False) else -i for i in range(1, cnf.n + 1)}

texto = """c (p ∨ ¬q) ∧ (q ∨ r) ∧ (¬p ∨ ¬r) ∧ (q ∨ ¬r)
p cnf 3 4
1 -2 0
2 3 0
-1 -3 0
2 -3 0
"""
F = CNF.from_dimacs(texto)
print(F, "  ida y vuelta idéntica:", F.to_dimacs() == texto.split("\n", 1)[1])
m = solve(F)
print("modelo:", sorted(m, key=abs), "  ¿certificado válido?", satisfies(F.clauses, m))
print("un certificado falso:", satisfies(F.clauses, {1, -2, 3}))

# validez = insatisfacibilidad de la negación: ((p → q) ∧ (q → r)) → (p → r)
G = CNF()
p, q, r = G.new_var("p"), G.new_var("q"), G.new_var("r")
for c in ([-p, q], [-q, r], [p], [-r]):      # la negación del condicional, ya en CNF
    G.add(c)
print("¿la negación del silogismo tiene modelo?", solve(G))

Hypothetical syllogism is valid because its negation has no model. Now Tseitin on a tuple syntax tree with shared subformulas, and two checks: model count is preserved (by brute force on small instances), and size grows linearly compared with distribution of to_cnf.

[ ]Tseitin transformationBrowser
from itertools import product
from sympy import symbols, Xor
from sympy.logic.boolalg import to_cnf

# cláusulas de definición g ↔ (a op b): tres para AND, OR y →; cuatro para XOR e IFF
GATE = {
    "and": lambda g, a, b: [[-g, a], [-g, b], [g, -a, -b]],
    "or":  lambda g, a, b: [[-g, a, b], [g, -a], [g, -b]],
    "xor": lambda g, a, b: [[-g, a, b], [-g, -a, -b], [g, -a, b], [g, a, -b]],
    "iff": lambda g, a, b: [[-g, -a, b], [-g, a, -b], [g, a, b], [g, -a, -b]],
    "imp": lambda g, a, b: [[-g, -a, b], [g, a], [g, -b]],
}

def tseitin(f):
    """f: árbol ('var', nombre) | ('not', f) | (op, f, g). Devuelve (cnf, {nombre: variable})."""
    cnf, inputs, memo = CNF(), {}, {}
    def lit(e):
        if e[0] == "var":
            if e[1] not in inputs:
                inputs[e[1]] = cnf.new_var(e[1])
            return inputs[e[1]]
        if e[0] == "not":
            return -lit(e[1])                    # la negación no crea variable
        a, b = lit(e[1]), lit(e[2])
        if (e[0], a, b) not in memo:             # subfórmulas idénticas comparten puerta
            g = memo[(e[0], a, b)] = cnf.new_var()
            for c in GATE[e[0]](g, a, b):
                cnf.add(c)
        return memo[(e[0], a, b)]
    cnf.add([lit(f)])                            # la raíz tiene que ser verdadera
    return cnf, inputs

def evaluate(e, env):
    if e[0] == "var":
        return env[e[1]]
    if e[0] == "not":
        return not evaluate(e[1], env)
    a, b = evaluate(e[1], env), evaluate(e[2], env)
    return {"and": a and b, "or": a or b, "xor": a != b, "iff": a == b, "imp": (not a) or b}[e[0]]

def count_models(cnf):
    """Fuerza bruta sobre las 2^n valoraciones: solo para comprobar en pequeño."""
    return sum(all(any((l > 0) == bits[abs(l) - 1] for l in c) for c in cnf.clauses)
               for bits in product([False, True], repeat=cnf.n))

V = lambda s: ("var", s)
ab = ("and", V("a"), V("b"))
ejemplos = {
    "multiplexor": ("or", ("and", V("s"), V("a")), ("and", ("not", V("s")), V("b"))),
    "mezcla": ("or", ("not", ("imp", V("p"), V("q"))), ("iff", V("q"), V("r"))),
    "compartida": ("or", ab, ("and", ("not", ab), V("c"))),
    "insatisfacible": ("and", ("and", ("or", V("a"), V("b")), ("not", V("a"))), ("not", V("b"))),
}
for nombre, f in ejemplos.items():
    cnf, inputs = tseitin(f)
    names = list(inputs)
    modelos_f = sum(evaluate(f, dict(zip(names, bits))) for bits in product([False, True], repeat=len(names)))
    print(f"{nombre:15s} {cnf.n - len(inputs)} puertas, {len(cnf.clauses):2d} cláusulas;"
          f" modelos de φ: {modelos_f}, modelos de la CNF: {count_models(cnf)}")

print("\n  n   to_cnf   Tseitin      (paridad x1 ⊕ ... ⊕ xn)")
for n in (2, 4, 6, 8, 10):
    dist = len(to_cnf(Xor(*symbols(f"x1:{n + 1}"))).args)
    f = V("x1")
    for i in range(2, n + 1):
        f = ("xor", f, V(f"x{i}"))
    print(f"{n:3d} {dist:8d} {len(tseitin(f)[0].clauses):9d}")

In “shared,” subformula a∧ba \land b appears twice and receives one variable: three gates instead of four. The to_cnf column is 2n−12^{n-1}, parity’s lower bound, and Tseitin’s is 4(n−1)+14(n - 1) + 1.

The text’s encodings, with “at most one” by pairs and sequential counter (case k=1k = 1; the general case is an exercise).

[ ]Coloring, N queens, Sudoku, and cardinalityBrowser
import time
from itertools import combinations

def at_least_one(cnf, xs):
    cnf.add(xs)

def at_most_one_pairs(cnf, xs):
    """C(n, 2) cláusulas binarias, sin variables nuevas."""
    for a, b in combinations(xs, 2):
        cnf.add([-a, -b])

def at_most_one_seq(cnf, xs):
    """Contador secuencial con k = 1: 3n − 4 cláusulas y n − 1 auxiliares."""
    n = len(xs)
    if n <= 1:
        return
    s = [cnf.new_var() for _ in range(n - 1)]      # s[i]: «alguna de x_1..x_{i+1} es verdadera»
    cnf.add([-xs[0], s[0]])
    for i in range(1, n - 1):
        cnf.add([-xs[i], s[i]])
        cnf.add([-s[i - 1], s[i]])
        cnf.add([-xs[i], -s[i - 1]])
    cnf.add([-xs[n - 1], -s[n - 2]])

def coloring(n_vertices, edges, k, break_symmetry=False):
    cnf = CNF()
    x = [[cnf.new_var() for _ in range(k)] for _ in range(n_vertices)]
    for v in range(n_vertices):
        at_least_one(cnf, x[v])                     # «a lo sumo un color» sobra
    for u, v in edges:
        for c in range(k):
            cnf.add([-x[u][c], -x[v][c]])
    if break_symmetry:                              # el vértice i solo usa los colores 0..i
        for v in range(n_vertices):
            for c in range(v + 1, k):
                cnf.add([-x[v][c]])
    return cnf, x

petersen = [(i, (i + 1) % 5) for i in range(5)] + [(i, i + 5) for i in range(5)] + [(5 + i, 5 + (i + 2) % 5) for i in range(5)]
for k in (2, 3):
    cnf, x = coloring(10, petersen, k)
    m = solve(cnf)
    if m is None:
        print(f"Petersen con {k} colores: {cnf} -> insatisfacible")
    else:
        col = [min(c for c in range(k) if x[v][c] in m) for v in range(10)]   # si hay varios, vale cualquiera
        print(f"Petersen con {k} colores: {cnf} -> {col}, válida: {all(col[u] != col[v] for u, v in petersen)}")

def queens(N):
    cnf = CNF()
    x = [[cnf.new_var() for _ in range(N)] for _ in range(N)]
    for r in range(N):
        at_least_one(cnf, x[r])
        at_most_one_pairs(cnf, x[r])
    for c in range(N):
        at_most_one_pairs(cnf, [x[r][c] for r in range(N)])
    for d in range(-(N - 1), N):
        at_most_one_pairs(cnf, [x[r][r - d] for r in range(N) if 0 <= r - d < N])
    for s in range(2 * N - 1):
        at_most_one_pairs(cnf, [x[r][s - r] for r in range(N) if 0 <= s - r < N])
    return cnf, x

cnf, x = queens(8)
m = solve(cnf)
print("\n8 reinas:", cnf, " columna de cada fila:", [next(c for c in range(8) if x[r][c] in m) for r in range(8)])

def sudoku(grid, extended=False):
    """grid: 81 caracteres con '.' en las vacías. Codificación mínima o extendida."""
    cnf = CNF()
    x = [[[cnf.new_var() for _ in range(9)] for _ in range(9)] for _ in range(9)]
    groups = [[(r, c) for c in range(9)] for r in range(9)] + [[(r, c) for r in range(9)] for c in range(9)]
    groups += [[(3 * (b // 3) + i // 3, 3 * (b % 3) + i % 3) for i in range(9)] for b in range(9)]
    for r in range(9):
        for c in range(9):
            at_least_one(cnf, x[r][c])
            if extended:
                at_most_one_pairs(cnf, x[r][c])
    for g in groups:
        for v in range(9):
            at_most_one_pairs(cnf, [x[r][c][v] for r, c in g])
            if extended:
                at_least_one(cnf, [x[r][c][v] for r, c in g])
    for i, ch in enumerate(grid):
        if ch != ".":
            cnf.add([x[i // 9][i % 9][int(ch) - 1]])
    return cnf, x

grid = "53..7....6..195....98....6.8...6...34..8.3..17...2...6.6....28....419..5....8..79"
for ext in (False, True):
    cnf, x = sudoku(grid, ext)
    t0 = time.perf_counter()
    m = solve(cnf)
    sol = "".join(str(1 + next(v for v in range(9) if x[r][c][v] in m)) for r in range(9) for c in range(9))
    print(f"Sudoku {'extendido' if ext else 'mínimo   '}: {cnf}, {time.perf_counter() - t0:.2f} s; primera fila {sol[:9]}")

print("\n    n   pares C(n,2)   contador 3n−4")
for n in (5, 10, 50, 100, 1000):
    a, b = CNF(), CNF()
    at_most_one_pairs(a, [a.new_var() for _ in range(n)])
    at_most_one_seq(b, [b.new_var() for _ in range(n)])
    print(f"{n:5d} {len(a.clauses):13d} {len(b.clauses):12d}   (+{b.n - n} auxiliares)")

The counts match the text: 736 clauses for 8 queens and 8829 plus 30 clues for minimal Sudoku. This Sudoku is solved almost entirely by propagation with both encodings.

For 2-SAT first use networkx (components, condensation, and topological order already implemented); the iterative linear from-scratch version is an exercise. Horn-SAT is written in full, with pending-premise counters.

[ ]2-SAT and Horn-SATBrowser
import random
import networkx as nx
from itertools import product

def two_sat_nx(n, clauses):
    """2-SAT con networkx: grafo de implicaciones, condensación y orden topológico."""
    G = nx.DiGraph()
    G.add_nodes_from([l for v in range(1, n + 1) for l in (v, -v)])
    for a, b in clauses:
        G.add_edge(-a, b)
        G.add_edge(-b, a)
    C = nx.condensation(G)                  # DAG de componentes; mapping: literal -> componente
    comp = C.graph["mapping"]
    if any(comp[v] == comp[-v] for v in range(1, n + 1)):
        return None
    rank = {c: i for i, c in enumerate(nx.topological_sort(C))}
    return {v: rank[comp[v]] > rank[comp[-v]] for v in range(1, n + 1)}   # verdadera si va después

def brute(n, clauses):
    return any(all((a > 0) == bits[abs(a) - 1] or (b > 0) == bits[abs(b) - 1] for a, b in clauses)
               for bits in product([False, True], repeat=n))

rng = random.Random(0)
errores = 0
for _ in range(300):
    n = rng.randint(2, 9)
    cl = [tuple(rng.choice([-1, 1]) * rng.randint(1, n) for _ in range(2)) for _ in range(rng.randint(1, 3 * n))]
    m = two_sat_nx(n, cl)
    errores += (m is not None) != brute(n, cl)
    errores += m is not None and not all(m[abs(a)] == (a > 0) or m[abs(b)] == (b > 0) for a, b in cl)
print("2-SAT frente a fuerza bruta en 300 instancias: errores =", errores)

# 2-SAT aleatorio con m = c·n cláusulas: el umbral está en c = 1
n = 400
for c in (0.6, 0.9, 1.0, 1.1, 1.4):
    sat = sum(two_sat_nx(n, [tuple(rng.choice([-1, 1]) * rng.randint(1, n) for _ in range(2)) for _ in range(int(c * n))]) is not None
              for _ in range(20))
    print(f"m/n = {c:.1f}: satisfacibles {sat:2d}/20")

def horn_sat(n, clauses):
    """Propagación unitaria con contadores (Dowling y Gallier), tiempo lineal.
    Devuelve el modelo mínimo (conjunto de variables verdaderas) o None."""
    pending = [sum(1 for l in c if l < 0) for c in clauses]   # premisas todavía no satisfechas
    occurs = {}                                               # variable -> cláusulas donde es premisa
    for i, c in enumerate(clauses):
        for l in c:
            if l < 0:
                occurs.setdefault(-l, []).append(i)
    true, queue = set(), [i for i, k in enumerate(pending) if k == 0]
    while queue:
        i = queue.pop()
        head = [l for l in clauses[i] if l > 0]
        if not head:
            return None                                       # restricción con todas sus premisas ciertas
        if head[0] in true:
            continue
        true.add(head[0])
        for j in occurs.get(head[0], []):
            pending[j] -= 1
            if pending[j] == 0:
                queue.append(j)
    return true

# un sistema de permisos: hechos, reglas y una restricción
nombres = ["admin", "editor", "lector", "borrar", "publicar", "leer", "auditado"]
v = {s: i + 1 for i, s in enumerate(nombres)}
reglas = [[v["editor"]], [-v["admin"], v["editor"]], [-v["editor"], v["lector"]], [-v["editor"], v["publicar"]],
          [-v["admin"], v["borrar"]], [-v["lector"], v["leer"]], [-v["borrar"], v["auditado"]],
          [-v["publicar"], -v["borrar"]]]        # nadie puede publicar y borrar a la vez
print("\nmodelo mínimo:", sorted(nombres[i - 1] for i in horn_sat(len(nombres), reglas)))
print("con el hecho «admin»:", horn_sat(len(nombres), reglas + [[v["admin"]]]))

fallos = 0
for _ in range(300):
    n = rng.randint(2, 8)
    cl = []
    for _ in range(rng.randint(1, 12)):
        body = rng.sample(range(1, n + 1), rng.randint(0, min(3, n)))
        head = [h for h in [rng.randint(1, n)] if h not in body] if rng.random() < 0.8 else []
        cl.append([-b for b in body] + head)
    mm = horn_sat(n, cl)
    modelos = [{i + 1 for i in range(n) if bits[i]} for bits in product([False, True], repeat=n)
               if all(any((l > 0) == bits[abs(l) - 1] for l in c) for c in cl)]
    fallos += (mm is None) != (not modelos) or (mm is not None and (mm not in modelos or not all(mm <= M for M in modelos)))
print("modelo mínimo frente a fuerza bruta en 300 fórmulas de Horn: fallos =", fallos)

The random 2-SAT threshold at m/n=1m/n = 1 is a theorem (Chvátal and Reed, 1992; Goerdt, 1996), and with n=400n = 400 the transition is already clear; the 3-SAT transition around m/n≈4.27m/n \approx 4.27 is harder and is the next lesson’s topic. In the permission system, the least model is exactly what follows from the rules, and the “admin” fact makes the policy inconsistent: an administrator is an editor and can therefore publish, and can also delete.

Now the miter. Construct CNF gate by gate with a subclass of CNF and compare a ripple-carry adder with a Kogge–Stone parallel-prefix adder, the structure processors use so carry need not traverse every bit.

[ ]Adder equivalence with a miterBrowser
import time

class Circuit(CNF):
    """CNF construida puerta a puerta: cada puerta crea su variable y sus cláusulas de Tseitin."""
    def gate(self, op, a, b):
        g = self.new_var()
        for c in GATE[op](g, a, b):
            self.add(c)
        return g
    def AND(self, a, b): return self.gate("and", a, b)
    def OR(self, a, b): return self.gate("or", a, b)
    def XOR(self, a, b): return self.gate("xor", a, b)
    def OR_all(self, xs):
        z = self.new_var()
        self.add([-z] + xs)
        for x in xs:
            self.add([z, -x])
        return z

def ripple_carry(C, a, b):
    s, c = [], None
    for i in range(len(a)):
        p = C.XOR(a[i], b[i])
        if c is None:
            s.append(p)
            c = C.AND(a[i], b[i])
        else:
            s.append(C.XOR(p, c))
            c = C.OR(C.AND(a[i], b[i]), C.AND(p, c))
    return s + [c]

def kogge_stone(C, a, b, bug=None):
    """Prefijos paralelos: (G, P) de bloques cada vez más largos en log2(n) niveles."""
    n = len(a)
    p = [C.XOR(a[i], b[i]) for i in range(n)]
    G, P = [C.AND(a[i], b[i]) for i in range(n)], p[:]
    d = 1
    while d < n:
        G2, P2 = G[:], P[:]
        for i in range(d, n):
            G2[i] = C.OR(G[i], C.AND(P[i], G[i - d]))
            P2[i] = C.OR(P[i], P[i - d]) if bug == (d, i) else C.AND(P[i], P[i - d])   # el fallo
        G, P, d = G2, P2, 2 * d
    return [p[0]] + [C.XOR(p[i], G[i - 1]) for i in range(1, n)] + [G[n - 1]]

def miter(n, bug=None):
    C = Circuit()
    a = [C.new_var(f"a{i}") for i in range(n)]
    b = [C.new_var(f"b{i}") for i in range(n)]
    out1, out2 = ripple_carry(C, a, b), kogge_stone(C, a, b, bug)
    C.add([C.OR_all([C.XOR(u, v) for u, v in zip(out1, out2)])])   # «alguna salida difiere»
    return C, a, b

def ks_int(A, B, n, bug=None):
    """El mismo Kogge-Stone simulado con enteros, para comprobar el contraejemplo por otra vía."""
    p = [(A >> i ^ B >> i) & 1 for i in range(n)]
    G, P, d = [(A >> i & B >> i) & 1 for i in range(n)], p[:], 1
    while d < n:
        G2, P2 = G[:], P[:]
        for i in range(d, n):
            G2[i] = G[i] | (P[i] & G[i - d])
            P2[i] = (P[i] | P[i - d]) if bug == (d, i) else (P[i] & P[i - d])
        G, P, d = G2, P2, 2 * d
    bits = [p[0]] + [p[i] ^ G[i - 1] for i in range(1, n)] + [G[n - 1]]
    return sum(bit << i for i, bit in enumerate(bits))

n = 5
for bug in (None, (1, 2)):
    C, a, b = miter(n, bug)
    t0 = time.perf_counter()
    m = solve(C)
    t = time.perf_counter() - t0
    if m is None:
        print(f"sin fallo: {C} -> insatisfacible en {t:.2f} s: equivalentes para las {4 ** n} entradas")
    else:
        A = sum(1 << i for i, x in enumerate(a) if x in m)
        B = sum(1 << i for i, x in enumerate(b) if x in m)
        print(f"fallo {bug}: {C} -> contraejemplo a = {A}, b = {B} en {t:.2f} s")
        print(f"   simulación: {A} + {B} = {A + B}, el sumador defectuoso da {ks_int(A, B, n, bug)}")
        malas = sum(ks_int(x, y, n, bug) != x + y for x in range(2 ** n) for y in range(2 ** n))
        print(f"   entradas que lo delatan: {malas} de {4 ** n}")

Sympy’s DPLL, without industrial solver heuristics, already takes a fraction of a second for 5 bits, and time grows quickly with bit count. Below, PySAT solves the same 64-bit miter in a couple of seconds, even in the browser.

Finally, BMC and k-induction on the text’s two programs, with 4-bit x. Adding a constant uses a ripple-carry adder in which the constant removes half the gates.

[ ]Bounded verification and k-inductionBrowser
BITS = 4

def add_const(C, x, k):
    """x + k módulo 2^BITS con k constante."""
    out, carry = [], None
    for i in range(BITS):
        if (k >> i) & 1:
            out.append(-x[i] if carry is None else -C.XOR(x[i], carry))
            carry = x[i] if carry is None else C.OR(x[i], carry)
        else:
            out.append(x[i] if carry is None else C.XOR(x[i], carry))
            carry = None if carry is None else C.AND(x[i], carry)
    return out

def equals_const(C, x, k):
    lits = [x[i] if (k >> i) & 1 else -x[i] for i in range(BITS)]
    g = lits[0]
    for l in lits[1:]:
        g = C.AND(g, l)
    return g

def unroll(C, x0, k, step):
    xs = [x0]
    for _ in range(k):
        xs.append(add_const(C, xs[-1], step))
    return xs

def decode(m, xs):
    return [sum(1 << i for i in range(BITS) if x[i] in m) for x in xs]

def bmc(k, step, bad, init=0):
    """¿Hay una ejecución de como mucho k pasos desde x = init que llegue a x = bad?"""
    C = Circuit()
    x0 = [C.new_var() for _ in range(BITS)]
    for i in range(BITS):
        C.add([x0[i] if (init >> i) & 1 else -x0[i]])
    xs = unroll(C, x0, k, step)
    C.add([C.OR_all([equals_const(C, x, bad) for x in xs])])
    m = solve(C)
    return None if m is None else decode(m, xs)

# x = 0; repetir: x = x + 3 (mod 16).  Propiedad: x != 7
for k in (4, 8, 12, 13):
    traza = bmc(k, 3, 7)
    print(f"BMC con k = {k:2d}:", "sin contraejemplo" if traza is None else f"contraejemplo {traza}")

def k_induction_step(k, step, bad):
    """Paso inductivo: k estados buenos consecutivos seguidos de uno malo, desde un estado cualquiera."""
    C = Circuit()
    xs = unroll(C, [C.new_var() for _ in range(BITS)], k, step)
    for x in xs[:-1]:
        C.add([-equals_const(C, x, bad)])
    C.add([equals_const(C, xs[-1], bad)])
    m = solve(C)
    return None if m is None else decode(m, xs)

# x = 0; repetir: x = x + 2.  Propiedad: x != 15 (cierta: x siempre es par)
print()
for k in range(1, 9):
    cti = k_induction_step(k, 2, 15)
    base = bmc(k - 1, 2, 15)
    print(f"k = {k}: base {'falla' if base else 'ok'};",
          "paso inductivo ok: demostrada" if cti is None else f"contraejemplo a la inducción {cti}")

Notice every induction counterexample starts at an odd value: states satisfying the property but unreachable. k-induction rules them out by lengthening the window; strengthening (“x is even”) rules them out at once with k=1k = 1.

The professional version: PySAT

PySAT (Ignatiev, Morgado, and Marques-Silva) provides Python access to industrial CDCL solvers (CaDiCaL, Glucose, MiniSat, and others) and implemented cardinality encodings. It also runs in the browser compiled to WebAssembly, so the following cells are as executable as the previous ones. First, the same miters at scale, and “at most kk” encodings of pysat.card versus the sequential-counter formula.

[ ]PySAT: 64-bit miters and cardinality encodingsBrowser
import time
from pysat.solvers import Solver
from pysat.card import CardEnc, EncType

def run(clauses, name="cadical153", budget=None):
    with Solver(name=name, bootstrap_with=clauses) as s:
        t0 = time.perf_counter()
        if budget is None:
            r = s.solve()
        else:
            s.conf_budget(budget)
            r = s.solve_limited()
        return r, time.perf_counter() - t0, s.accum_stats(), s.get_model() if r else None

for n in (8, 16, 32, 64):
    C, a, b = miter(n)
    r, t, st, _ = run(C.clauses)
    C2, a2, b2 = miter(n, bug=(2, n // 2 + 1))
    r2, t2, st2, model = run(C2.clauses)
    A = sum(1 << i for i, x in enumerate(a2) if model[x - 1] > 0)
    B = sum(1 << i for i, x in enumerate(b2) if model[x - 1] > 0)
    print(f"{n:2d} bits: {C.n:5d} variables, {len(C.clauses):6d} cláusulas; equivalentes: {not r} "
          f"({st['conflicts']} conflictos, {t:.2f} s); con fallo: a + b = {A + B}, sumador {ks_int(A, B, n, (2, n // 2 + 1))}")

print("\n«a lo sumo k» con n = 100: cláusulas según la codificación")
n, lits = 100, list(range(1, 101))
for k in (1, 5, 20):
    row = []
    for nombre, enc in [("pares", EncType.pairwise), ("contador", EncType.seqcounter), ("totalizador", EncType.totalizer),
                        ("red de cardinalidad", EncType.cardnetwrk)]:
        if enc == EncType.pairwise and k > 1:
            continue
        f = CardEnc.atmost(lits=lits, bound=k, top_id=n, encoding=enc)
        row.append(f"{nombre} {len(f.clauses)}")
    print(f"k = {k:2d}: " + ", ".join(row) + f"   (fórmula del contador: {2 * n * k + n - 3 * k - 1})")

The 64-bit miter, with 1665 variables and almost 5000 clauses, is proved unsatisfiable with a few thousand conflicts, and the faulty-adder miter returns a concrete miscomputed sum checkable by hand. For k=1k = 1, PySAT’s seqcounter encoding has exactly the formula’s 3n−43n - 4 clauses; for larger kk, PySAT implements a counter variant with somewhat fewer clauses than Sinz’s. Cardinality networks grow as O(nlog⁡2k)\bigO(n \log^2 k) rather than O(nk)\bigO(nk), so eventually win as kk grows (with n=100n = 100 and k=20k = 20 they already match the counter); the totalizer builds the full unary counter and its size does not depend on kk.

Now symmetry breaking. Measure conflicts rather than time because it is deterministic and machine-independent; use a conflict budget to avoid waiting indefinitely.

[ ]PySAT: the effect of symmetry breakingBrowser
def php(p, h, sym=False):
    """p palomas en h huecos: cada paloma en algún hueco, cada hueco con a lo sumo una paloma."""
    v = lambda i, j: i * h + j + 1
    cl = [[v(i, j) for j in range(h)] for i in range(p)]
    for j in range(h):
        for a_, b_ in combinations(range(p), 2):
            cl.append([-v(a_, j), -v(b_, j)])
    if sym:                                     # los huecos son intercambiables: la paloma i usa los huecos 0..i
        cl += [[-v(i, j)] for i in range(p) for j in range(i + 1, h)]
    return cl

print("palomar PHP(n+1, n): conflictos hasta demostrar la insatisfacibilidad")
for nh in (5, 6, 7, 8):
    r0, _, s0, _ = run(php(nh + 1, nh), budget=100_000)
    r1, _, s1, _ = run(php(nh + 1, nh, sym=True), budget=100_000)
    estado = "insatisfacible" if r0 is False else "sin respuesta"
    print(f"n = {nh}: sin romper la simetría {s0['conflicts']:6d} conflictos ({estado});"
          f"  rompiéndola {s1['conflicts']} conflicto y {s1['decisions']} decisiones")

def mycielski(k):
    """Grafo de Mycielski M_k: sin triángulos y con número cromático k."""
    n, E = 2, [(0, 1)]
    for _ in range(k - 2):
        E = E + [(a_, n + b_) for a_, b_ in E] + [(b_, n + a_) for a_, b_ in E] + [(n + i, 2 * n) for i in range(n)]
        n = 2 * n + 1
    return n, E

nv, E = mycielski(5)
for sym in (False, True):
    cnf, _ = coloring(nv, E, 4, break_symmetry=sym)
    r, t, st, _ = run(cnf.clauses, budget=500_000)
    print(f"Mycielski M5 ({nv} vértices, χ = 5) con 4 colores, simetría {'rota' if sym else 'intacta'}: "
          f"{'insatisfacible' if r is False else 'sin respuesta'} tras {st['conflicts']} conflictos")

With symmetry intact, pigeonhole conflicts multiply six- or sevenfold for each extra hole, the exponential growth predicted by Haken’s theorem; breaking symmetry lets unit propagation reach a contradiction without decisions (the only conflict is the final one). In the triangle-free Mycielski graph (so no large clique can be fixed), the weak rule “vertex ii uses at most ii colors” already reduces conflicts by an order of magnitude.

ToolPurpose
pysat.solvers.SolverCDCL solvers (CaDiCaL, Glucose, MiniSat…), with incremental solving and assumptions
pysat.card, pysat.pbcardinality and pseudo-Boolean constraint encodings
pysat.formula.CNFDIMACS reading and writing
CaDiCaL, Kissat (command line)competition reference solvers over DIMACS files
z3, cvc5SMT: SAT plus theories (arithmetic, bit vectors, arrays); covered in SMT theories
OR-Tools CP-SATconstraint programming and optimization over a SAT core

Common mistakes

Exercises

QuizWhat Tseitin preserves
Why does the Tseitin transformation preserve satisfiability but not logical equivalence?
NumericAt most one, pairwise
How many binary clauses does pairwise ‘at most one’ encoding over 10 variables need?
NumericCounter size
How many clauses does the Sinz sequential counter for ‘at most 3 of 10 variables’ have?
NumericBoard diagonals
In the 8-queens encoding, how many binary clauses do ‘at most one queen per diagonal’ constraints contribute in total across both directions?
NumericTseitin of a parity
How many clauses does full Tseitin transformation of x1⊕x2⊕⋯⊕x10x_1 \oplus x_2 \oplus \cdots \oplus x_{10}, left-associated, produce including the root clause?
QuizRedundant families
In the Sudoku encoding, start with ‘each cell has at least one value’ and ‘each value appears at most once in every row, column, and block.’ What happens if we also remove ‘each cell has at least one value’ and add ‘each cell has at most one value’ instead?
QuizWhat BMC without a counterexample says
A team runs BMC on an elevator controller with k=40k = 40 and gets ‘unsatisfiable’ for the property ‘the door never opens while moving.’ What may they claim?
QuizReading the condensation
In the implication graph of a satisfiable 2-CNF, the component of ¬x3\lnot x_3 precedes that of x3x_3 in the condensation's topological order. What value does the Aspvall, Plass, and Tarjan algorithm assign x3x_3, and why?
ProofTseitin: equisatisfiable and linear
Prove: For every formula φ\varphi with ss binary connectives, T(φ)\mathcal{T}(\varphi) is satisfiable if and only if φ\varphi is, and has at most 4s+14s + 1 clauses.
0
Let DD be the set of defining clauses, so T(φ)=D∧(ℓφ)\mathcal{T}(\varphi) = D \land (\ell_\varphi).

Step 1 of 4. Which auxiliary claim should be proved first?

ProofHorn-SAT and the least model
Prove: Let FF be a Horn CNF. Unit propagation from all false (set to 1 the conclusion of each rule or fact whose premises are already 1 until nothing changes) decides whether FF is satisfiable, and if so, set MM of variables set to 1 is a model contained in every model of FF.
0
Number variables in the order the algorithm sets them to 1: p1,p2,…,prp_1, p_2, \dots, p_r.

Step 1 of 4. Which invariant do you prove first?

CodeAt most k with a sequential counter
Implement at_most_k_seq(n, k), returning (clauses, nvars): the Sinz sequential counter clauses (lists of DIMACS integers) for ‘at most k of x1,…,xnx_1, \dots, x_n’, with original variables numbered 1 through n and auxiliary si,js_{i,j} starting at n + 1, and the total variable count. For 1≤k<n1 \le k < n it must have exactly 2nk+n−3k−12nk + n - 3k - 1 clauses. If k >= n no clauses are needed, and if k == 0, negate them all. Tests enumerate, for n≤8n \le 8, that assignments to xx extending to a model are exactly those with at most k true variables.
def at_most_k_seq(n, k):
  """Cláusulas del contador secuencial de Sinz para «a lo sumo k de x_1..x_n».
  Variables originales 1..n; auxiliares s_{i,j} desde n + 1. Devuelve (cláusulas, número total de variables)."""
  clauses = []
  # tu código: s_{i,j} significa «al menos j verdaderas entre x_1..x_i»
  return clauses, n
Shift+Enter to run
CodeA linear 2-SAT solver
Implement two_sat(n, clauses) for a 2-CNF over x1,…,xnx_1, \dots, x_n, given as a list of pairs (a, b) of DIMACS literals (a unit clause arrives as (a, a)). Return ('SAT', modelo) with Boolean modelo[v] for v = 1..n, or ('UNSAT', v) with a variable v such that xvx_v and ¬xv\lnot x_v lie in the same strongly connected component of the implication graph. Compute components using iterative Tarjan or Kosaraju: tests include a chain of 5000 implications, which would exhaust a recursive stack. Do not use networkx.
def two_sat(n, clauses):
  """clauses: pares (a, b) de literales DIMACS sobre x_1..x_n.
  Devuelve ('SAT', modelo) con modelo[v] in {True, False} para v = 1..n,
  o ('UNSAT', v) con x_v y ¬x_v en la misma componente fuertemente conexa."""
  # 1. grafo de implicaciones: (a ∨ b) da ¬a → b y ¬b → a
  # 2. componentes fuertemente conexas (iterativo: hay instancias de miles de literales)
  # 3. conflicto o asignación según el orden topológico
  return ("SAT", {v: False for v in range(1, n + 1)})
Shift+Enter to run

Summary

Key idea
SAT is a universal modeling language: Tseitin converts any formula or circuit to linear-size CNF without losing or gaining models, and the art is choosing variables and clause families that propagate well in the solver.
  • SAT asks whether a CNF has a model. A model is a certificate checked in linear time; unsatisfiability requires a generally long proof. Validity and consequence reduce to unsatisfiability. SAT and 3-SAT are NP-complete (Cook–Levin).
  • Tseitin gives each gate a variable defined by 3 or 4 clauses: the resulting CNF is equisatisfiable (not equivalent), preserves model count, and has at most 4s+14s + 1 clauses of 3 literals. Plaisted–Greenbaum uses only the needed polarity.
  • Encoding means choosing meaningful variables and writing each constraint as clauses. Some families are redundant (at most one color, at most one value per cell) and can be proved unnecessary, but redundant clauses can greatly improve propagation. Breaking symmetries is essential on unsatisfiable instances.
  • Pairwise “at most one” costs (n2)\binom{n}{2} clauses; Sinz’s sequential counter expresses “at most kk” with 2nk+n−3k−12nk + n - 3k - 1 clauses, (n−1)k(n - 1)k auxiliaries, and complete propagation.
  • 2-SAT is decided in linear time using strongly connected components of the implication graph; Horn-SAT uses unit propagation, which also constructs the least model.
  • A miter turns circuit equivalence into a SAT question whose model is an input distinguishing the circuits. BMC unrolls a system kk steps and finds bugs up to that depth without proving anything beyond it; k-induction, analogous to inductive invariants, closes the proof.