Module contents
Lesson 4 of 22Review 95 min

Proof techniques and natural deduction

Review proof techniques—direct proof, contraposition, contradiction, cases, existence, and counterexample—as goal-oriented strategies. Formalize them as natural deduction rules and state propositional soundness and completeness, bridging proof and truth.

After this lesson you can

  • Choose and apply the right technique for a statement's logical form.
  • Write readable proofs with explicit hypotheses and goals.
  • Construct natural-deduction derivations while managing open and discharged assumptions.
  • Explain propositional soundness and completeness (⊢ versus ⊨).
  • Distinguish constructive and nonconstructive proofs and implications for algorithms.
  • Refute conjectures with minimal counterexamples.

Before you start

Motivation: a proof is an object someone checks

In the first lesson you decided whether Γ⊨φ\Gamma \models \varphi by examining all valuations: a truth table with 2n2^n rows. In the second, quantifiers over infinite domains remove that option: “for every integer nn” cannot be checked case by case. Mathematics replaces exhaustive checking with a finite proof anyone can review step by step without rediscovering it.

The idea of a proof as an object checked by a verifier is more than a formality:

  • Algorithm correctness is proven with loop invariants and variant functions, as in the invariants lesson. A gap can hide exactly the case in which the program fails.
  • Generalization bounds in learning theory, such as the test-set bound, are inequality chains whose steps use techniques from this lesson. Reading a theory paper requires recognizing each step’s strategy and spotting when a step does not follow, practiced in research as gap detection.
  • Proof assistants (Lean, Coq, Isabelle) and systems that search for proofs using neural networks use a small kernel accepting or rejecting each step. To a machine a poorly structured proof is not “almost correct”: it does not compile.

A proof-assistant interface captures the craft. At each point you have hypotheses (what may be used) and a goal (what remains to prove), and each step transforms the pair:

n∈Z,    h:n odd⏟hypotheses    ⊢    n2 odd⏟goal\underbrace{n \in \Z,\;\; h : n \text{ odd}}_{\text{hypotheses}} \;\;\vdash\;\; \underbrace{n^2 \text{ odd}}_{\text{goal}}

The lesson has two halves. First review standard proof techniques (direct, contraposition, contradiction, cases, existence, counterexample) as goal strategies selected by logical form. Then convert them into rules of a formal system, natural deduction, write a checker, and prove the theorem uniting the halves: what can be proven is exactly what is true, ⊢\vdash and ⊨\models coincide.

Logical form dictates strategy

The most useful advice for starting a proof is syntactic rather than mathematical: look at the goal’s main connective. Every connective has a natural proof form saying what can be assumed and what remains. Every connective in a hypothesis also has a natural use. The tables summarize both sides; most mathematics-course proofs combine these rows.

If the goal isStrategyHypothesis gainedRemaining goal
P→QP \to QdirectPPQQ
P→QP \to Qcontrapositive¬Q\lnot Q¬P\lnot P
¬P\lnot Passume the assertionPP⊥\bot
PP (any)contradiction¬P\lnot P⊥\bot
∀x P(x)\forall x\, P(x)fix arbitrary xxxx, nothing moreP(x)P(x)
∃x P(x)\exists x\, P(x)give witness ttP(t)P(t)
P∧QP \land Qtwo goalsPP, then QQ
P∨QP \lor Qchoose a side, or assume ¬P\lnot Pnothing, or ¬P\lnot Pchosen side, or QQ
P↔QP \leftrightarrow Qtwo conditionalsP→QP \to Q and Q→PQ \to P
If a hypothesis isUse it as follows
P∧QP \land Qseparate into PP and QQ
P∨QP \lor Qcases: prove the goal assuming PP, then assuming QQ
P→QP \to Qwith PP (or a proof of it), obtain QQ
∀x P(x)\forall x\, P(x)instantiate at any concrete object: P(t)P(t)
∃x P(x)\exists x\, P(x)introduce a fresh name cc with property P(c)P(c)
¬P\lnot Pderiving PP gives contradiction; or rewrite using negation laws

The ∀\forall and ∃\exists rows are asymmetric. To prove ∀x P(x)\forall x\, P(x) fix an xx about which nothing but its type is known: proving P(x)P(x) without using anything particular about that xx makes the argument universal. To use hypothesis ∃x P(x)\exists x\, P(x) name an existing object, but you cannot choose it: the name must be fresh, distinct from everything already present.

Real proofs are not linear: sometimes a strategy stalls and you backtrack. The first interactive is a small proof assistant with five statements. Some paths close every goal; others stall, and the panel explains why.

InteractiveHypotheses and goal
StatementFor every integer nn: if n2n^2 is even, then nn is even.
Proof state1 goal
Goal 1in progress
  • nnn∈Zn \in \Znew
⊢\vdashn2 even→n evenn^2 \text{ even} \to n \text{ even}
Written proof
  1. Let nn be an arbitrary integer.
Strategies
Available steps
None: choose a strategy here.
Open goals1
Steps taken1
Main strategynone yet
Each strategy button transforms hypotheses and goal as in the table; new hypotheses are highlighted and prose proof writes itself. For ‘If n2n^2 is even, nn is even,’ try direct proof first: it stalls and the apparent witness is circular reasoning. Undo and try contraposition, contradiction, and cases, reading each final comment. Then see divisibility transitivity (where contraposition stalls) and irrational numbers with rational power (where cases prove existence without saying which is the witness).

What you should see:

  • The right strategy depends on information flow. With odd nn, n=2k+1n = 2k + 1 and n2n^2 can be calculated; with even n2n^2 there is no algebraic route to nn. Contraposition reverses calculation direction and makes it easy.
  • Contraposition does not always help. For divisibility transitivity it changes strong hypotheses (∃\exists, which give witnesses for calculation) into weak ones (¬∃\lnot\exists, which do not). Hypothesis form matters as much as goal form.
  • Several strategies may close the same goal at different quality. Contradiction for “even n2n^2 implies even nn” works but disguises contraposition; cases work, but one is trivial and the other contraposition under another name.

Contraposition and contradiction

Contrapositive is not the converse. The converse of P→QP \to Q is Q→PQ \to P, not equivalent: with false PP and true QQ, P→QP \to Q holds and Q→PQ \to P does not. Proving the converse instead is a common mistake; the natural-deduction builder shows no sound rule system permits the conversion.

Informal language mixes two patterns under this name; distinguish them because they become separate rules later:

  • Negation introduction. To prove ¬P\lnot P, assume PP and reach ⊥\bot. No double negation: this defines what refuting PP means.
  • Contradiction proper. To prove PP, assume ¬P\lnot P, reach ⊥\bot, and conclude ¬¬P\lnot\lnot P; the last step from ¬¬P\lnot\lnot P to PP is a classical principle intuitionistic logic rejects.

Irrationality of 2\sqrt 2 is the first type: the claim is a negation, ¬(2∈Q)\lnot(\sqrt 2 \in \Q). It needs a lemma proven in the interactive: if n2n^2 is even, so is nn. Build the proof step by step.

Proof√2 is irrational
Prove: 2\sqrt 2 is not a rational number.
0
The statement is the negation ¬(2∈Q)\lnot(\sqrt 2 \in \Q). You may use the lemma: for every integer nn, if n2n^2 is even, then nn is even.

Step 1 of 4. How do you begin?

The classic proof by contradiction is older still and hides a surprise.

Proof

Let N=p1p2⋯pn+1N = p_1 p_2 \cdots p_n + 1. Since N≥2N \ge 2, it has a prime divisor qq (its least divisor greater than 11 is prime). If qq were one of pip_i, it would divide p1⋯pnp_1 \cdots p_n and NN, hence their difference 11: impossible. Thus qq is not on the list. If primes were finite, listing all would yield contradiction.

∎

Surprisingly, read correctly Euclid’s argument is direct and constructive: given any list it builds a new prime (factor NN and take a factor). Contradiction appears only in the last sentence and is dispensable. Two cautions. First, NN need not be prime: 2⋅3⋅5⋅7⋅11⋅13+1=30031=59⋅5092 \cdot 3 \cdot 5 \cdot 7 \cdot 11 \cdot 13 + 1 = 30031 = 59 \cdot 509. Second, presenting a direct argument as contradiction is not logically wrong, but hides algorithmic content.

Cases, existence, and knowing that versus knowing which

The most useful cases come from a known disjunction about the problem. For “3∣n3−n3 \mid n^3 - n” use division remainders n=3kn = 3k, n=3k+1n = 3k + 1, or n=3k+2n = 3k + 2; each calculation closes:

n3−n={3(9k3−k)n=3k,3(9k3+9k2+2k)n=3k+1,3(9k3+18k2+11k+2)n=3k+2.n^3 - n = \begin{cases} 3(9k^3 - k) & n = 3k, \\ 3(9k^3 + 9k^2 + 2k) & n = 3k + 1, \\ 3(9k^3 + 18k^2 + 11k + 2) & n = 3k + 2. \end{cases}

Odd/even cases would not help: cases must address the divisor. With finitely many but many cases, this becomes proof by exhaustion only a computer can traverse. The four-color theorem (Appel and Haken, 1976) was the first famous example; Kepler’s sphere-packing conjecture was settled with a formal proof checked by proof assistants (Hales et al., 2015). Case exhaustiveness is part of the proof and must be justified like any step.

The canonical nonconstructive proof fits in three lines. Build it:

ProofIrrationals with a rational power
Prove: There are irrational numbers aa and bb such that aba^b is rational.
0
You know that 2\sqrt 2 is irrational. You do not (yet) know whether 22\sqrt2^{\sqrt2} is rational.

Step 1 of 4. What strategy do you use?

The difference has practical consequences. A constructive existence proof is an algorithm: Euclid computes a new prime, divisibility transitivity computes quotient kmkm. A nonconstructive proof may give none. An extreme example is g(n)=1g(n) = 1 if Goldbach’s conjecture is true and g(n)=0g(n) = 0 otherwise: it is computable because it is one of two constant functions, yet nobody knows how to write its program. The idea that constructively proving ∃x P(x)\exists x\, P(x) means writing a program returning xx is central to the Curry–Howard correspondence; proof assistants use it to extract programs from proofs.

Counterexamples: why a thousand cases are not proof

By quantifier laws, ¬∀x P(x)≡∃x ¬P(x)\lnot\forall x\, P(x) \equiv \exists x\, \lnot P(x): one case refutes a universal claim. The asymmetry is total. One failure refutes forever; a million successful cases prove nothing about the infinitely many remaining.

Mathematical history is full of conjectures surviving many cases. The second interactive lets you bet against four.

InteractiveCounterexample hunter
ConjectureFor every integer n≥0n \ge 0, n2+n+41n^2 + n + 41 is prime.
no cases
0cases checked
·satisfy the conjecture
¿?unproven
n = 0
?
n = 1
?
n = 2
?
n = 3
?
n = 4
?
n = 5
?
n = 6
?
n = 7
?
n = 8
?
n = 9
?
n = 10
?
n = 11
?
n = 12
?
n = 13
?
n = 14
?
n = 15
?
n = 16
?
n = 17
?
n = 18
?
n = 19
?
n = 20
?
n = 21
?
n = 22
?
n = 23
?
n = 24
?
n = 25
?
n = 26
?
n = 27
?
n = 28
?
n = 29
?
n = 30
?
n = 31
?
n = 32
?
n = 33
?
n = 34
?
n = 35
?
n = 36
?
n = 37
?
n = 38
?
n = 39
?
n = 40
?
n = 41
?
n = 42
?
n = 43
?
n = 44
?
n = 45
?
n = 46
?
n = 47
?
holds counterexample your guess
Your guess n = 12. Press play: each successful case appears to support the conjecture.
12
Consecutive cases checked0
First counterexamplenot yet
Your guessn = 12
Choose a conjecture, bet on its first failure, and play. Each successful case raises the success percentage, which proves nothing: animation stops at the first counterexample. For n2+n+41n^2 + n + 41, inspect what happens after n=40n = 40. Circle points are deliberately irregular: with six equally spaced points, three diagonals meet at the center and one region is lost.

The four conjectures teach different lessons:

  • n2+n+41n^2 + n + 41 gives primes for n=0,1,…,39n = 0, 1, \dots, 39 (Euler, 1772), failing at n=40n = 40 with 41241^2. This is not accidental: if an integer-coefficient polynomial pp equals prime qq at some n0n_0, then q∣p(n0+kq)q \mid p(n_0 + kq) for every kk, because p(n0+kq)≡p(n0)(modq)p(n_0 + kq) \equiv p(n_0) \pmod q; a nonconstant polynomial takes values ±q\pm q only finitely often, so some p(n0+kq)p(n_0 + kq) is composite. No nonconstant integer-coefficient polynomial gives only primes.
  • Fermat numbers Fn=22n+1F_n = 2^{2^n} + 1 are prime for n≤4n \le 4, and Fermat conjectured all were. Euler found factor 641641 of F5=4294967297F_5 = 4294967297 in 1732. Five supporting cases were more wish than evidence.
  • Circle regions follow 1,2,4,8,161, 2, 4, 8, 16 then 3131. The correct formula (n4)+(n2)+1\binom{n}{4} + \binom{n}{2} + 1 matches 2n−12^{n-1} while n≤5n \le 5: initial sequence terms do not determine it.
  • 2p−12^p - 1 for prime pp fails at p=11p = 11. The converse is true: if 2n−12^n - 1 is prime, nn is prime. Confusing a conditional and converse becomes a conjecture.

Some counterexamples are much more elusive. Pólya’s conjecture about sign of Liouville-function sum ∑k≤nλ(k)\sum_{k \le n} \lambda(k) first fails at n=906 150 257n = 906\,150\,257. Mertens’s conjecture was refuted in 1985 (Odlyzko and te Riele) without exhibiting a counterexample: one was proven to exist nonconstructively, and none has been calculated. No amount of computer checking would convert those conjectures into theorems.

Natural deduction: strategies as rules

So far techniques were informal: Spanish sentences accepted by a human reader. For a machine to check a proof, or to prove things about proofs, a formal system is needed. Gerhard Gentzen and Stanisław Jaśkowski independently proposed one in 1934 that imitates mathematical reasoning rather than reducing it to few axioms: natural deduction.

Rules are precisely the strategy-table rows. Box rules (→I and ¬I) open and discharge assumptions; in Fitch style an assumption heads a box and its discharging rule follows the box’s last line.

ConnectiveIntroduction (how to prove)Elimination (how to use)Informal technique
∧\landφψφ∧ψ\dfrac{\varphi \quad \psi}{\varphi \land \psi}φ∧ψφφ∧ψψ\dfrac{\varphi \land \psi}{\varphi} \quad \dfrac{\varphi \land \psi}{\psi}two goals; separate
∨\lorφφ∨ψψφ∨ψ\dfrac{\varphi}{\varphi \lor \psi} \quad \dfrac{\psi}{\varphi \lor \psi}φ∨ψφ→χψ→χχ\dfrac{\varphi \lor \psi \quad \varphi \to \chi \quad \psi \to \chi}{\chi}choose a side; cases
→\toφ  ⋯  ψφ→ψ\dfrac{\boxed{\varphi \;\cdots\; \psi}}{\varphi \to \psi}φφ→ψψ\dfrac{\varphi \quad \varphi \to \psi}{\psi}direct; modus ponens
¬\lnotφ  ⋯  ⊥¬φ\dfrac{\boxed{\varphi \;\cdots\; \bot}}{\lnot\varphi}φ¬φ⊥\dfrac{\varphi \quad \lnot\varphi}{\bot}assume and refute
⊥\bot⊥φ\dfrac{\bot}{\varphi}anything from contradiction
classical¬¬φφ\dfrac{\lnot\lnot\varphi}{\varphi}contradiction

Three comments. First, our ∨\lorE cites two conditionals instead of two boxes; it is equivalent to textbooks’ two-box version because each box is precisely a →I subproof, and lets only →I and ¬I close boxes, simplifying the checker. Second, contraposition needs no separate rule because it is a derivable theorem. Third, classical ¬¬\lnot\lnotE is the only rule not read as “one connective, one strategy.” Without it there is intuitionistic logic, where neither p∨¬pp \lor \lnot p nor ¬¬p→p\lnot\lnot p \to p is provable; with it, classical truth-table logic.

Here is a Fitch-style derivation of contraposition, ⊢(p→q)→(¬q→¬p)\vdash (p \to q) \to (\lnot q \to \lnot p):

1  ∣  p→qsup2  ∣  ∣  ¬qsup3  ∣  ∣  ∣  psup4  ∣  ∣  ∣  q→E 3,15  ∣  ∣  ∣  ⊥¬E 4,26  ∣  ∣  ¬p¬I 3-57  ∣  ¬q→¬p→I 2-68(p→q)→(¬q→¬p)→I 1-7\begin{array}{rlll} 1 & \;\big|\; p \to q & & \text{sup} \\ 2 & \;\big|\;\big|\; \lnot q & & \text{sup} \\ 3 & \;\big|\;\big|\;\big|\; p & & \text{sup} \\ 4 & \;\big|\;\big|\;\big|\; q & & {\to}\mathrm{E}\ 3, 1 \\ 5 & \;\big|\;\big|\;\big|\; \bot & & \lnot\mathrm{E}\ 4, 2 \\ 6 & \;\big|\;\big|\; \lnot p & & \lnot\mathrm{I}\ 3\text{-}5 \\ 7 & \;\big|\; \lnot q \to \lnot p & & {\to}\mathrm{I}\ 2\text{-}6 \\ 8 & (p \to q) \to (\lnot q \to \lnot p) & & {\to}\mathrm{I}\ 1\text{-}7 \end{array}

And as a tree, with assumptions as leaves: each leaf [φ]k[\varphi]^k is discharged by the rule marked kk.

[¬q]2[p]1[p→q]3q →E⊥ ¬E¬p ¬I1¬q→¬p →I2(p→q)→(¬q→¬p) →I3\dfrac{\dfrac{\dfrac{\dfrac{[\lnot q]^2 \qquad \dfrac{[p]^1 \qquad [p \to q]^3}{q}\,{\to}\mathrm{E}}{\bot}\,\lnot\mathrm{E}}{\lnot p}\,\lnot\mathrm{I}^1}{\lnot q \to \lnot p}\,{\to}\mathrm{I}^2}{(p \to q) \to (\lnot q \to \lnot p)}\,{\to}\mathrm{I}^3

Both notations describe the same object. Fitch is more compact (a multiply cited line is written once) and used by checkers; trees show dependencies because leaves are assumptions. Build them yourself.

InteractiveNatural deduction builder
View
Prove (the truth table confirms this is a logical consequence)⊢  (p→q)→(¬q→¬p)\vdash\; (p \to q) \to (\lnot q \to \lnot p)
Proof3 open assumptions
1p→qp \to qassumptionopen
2¬q\lnot qassumptionopen
3ppassumptionopen
4qq→E 3, 1
5next line, inside 3 boxes
Lines 4Open assumptions 1, 2, 3
Rules
Introduce
Eliminate
Other
φ¬φ⊥  ¬E\dfrac{\varphi \qquad \lnot\varphi}{\bot}\;\lnot\mathrm{E}
A formula and its negation yield a contradiction, ⊥\bot.
Fill the slots with proof lines.
The proof starts halfway: three open assumptions in red and line 4 from →E. Complete the selected ¬E rule by tapping or dragging lines 4 and 2 into its slots; then close all three boxes with ¬I, →I, and →I and watch assumptions become discharged. Try citing a line from a closed box or applying →E backward: the rejection explains why. Tap any line to see its assumptions and truth-table-check that it follows. Then switch to tree view and try ‘The converse’: the panel explains why searching is futile.

What you should see:

  • Every box is a scope. While an assumption is open, everything derived depends on it; after →I or ¬I discharges it, box lines become unavailable. Programmers recognize local-variable scope: a parameter exists only inside its function, and →I is literally the λ\lambda abstraction creating that function. See Curry–Howard.
  • Read strategy bottom up. To prove a conditional assume its antecedent and close with →I; for negation assume the assertion and seek ⊥\bot. Introduction rules build the goal, elimination rules consume hypotheses, and a good proof meets in the middle.
  • Each line follows from its open assumptions. Tap any line: the truth table always confirms Γ,open assumptions⊨line\Gamma, \text{open assumptions} \models \text{line}. This observation as a theorem is system soundness.
  • Excluded middle needs the classical rule. The solution for ⊢p∨¬p\vdash p \lor \lnot p uses ¬¬\lnot\lnotE; the others do not. De Morgan one way, ¬p∧¬q⊢¬(p∨q)\lnot p \land \lnot q \vdash \lnot(p \lor q), and the other, ¬(p∨q)⊢¬p∧¬q\lnot(p \lor q) \vdash \lnot p \land \lnot q, are intuitionistically valid.

Soundness and completeness: the bridge between ⊢ and ⊨

There are two notions of “follows.” One is semantic: Γ⊨φ\Gamma \models \varphi, logical consequence, defined using valuations and silent about reasoning. The other is syntactic: Γ⊢φ\Gamma \vdash \varphi, a derivation exists, a finite object checked without considering truth values. Their coincidence is not obvious and gives meaning to everything above.

Proof

Take a Fitch derivation with lines φ1,…,φm=φ\varphi_1, \dots, \varphi_m = \varphi, premises in Γ\Gamma, and no box open at the end. For each line nn, let AnA_n be assumptions of boxes containing it (open at that point). By strong induction on nn prove invariant

Γ∪An⊨φn.\Gamma \cup A_n \models \varphi_n .

Two facts apply throughout. Monotonicity: if Δ⊨ψ\Delta \models \psi and Δ⊆Δ′\Delta \subseteq \Delta', then Δ′⊨ψ\Delta' \models \psi. Accessibility: a line k<nk < n citable at line nn is in no closed box, so all its boxes remain open at nn: Ak⊆AnA_k \subseteq A_n, and induction plus monotonicity give Γ∪An⊨φk\Gamma \cup A_n \models \varphi_k.

  • Premise: φn∈Γ\varphi_n \in \Gamma. Assumption: φn∈An\varphi_n \in A_n. Both trivial. Copy: accessibility.
  • →E: cite ψ\psi and ψ→φn\psi \to \varphi_n, consequences of Γ∪An\Gamma \cup A_n. Every valuation satisfying Γ∪An\Gamma \cup A_n makes both ψ\psi and ψ→φn\psi \to \varphi_n true, hence φn\varphi_n. Likewise ∧I, ∧E, ∨I, ¬E (ψ\psi and ¬ψ\lnot\psi are not simultaneously true, so no valuation satisfies Γ∪An\Gamma \cup A_n and ⊥\bot follows trivially), ⊥E for the same reason, and ¬¬E because ¬¬ψ\lnot\lnot\psi and ψ\psi have identical tables.
  • ∨E: with ψ∨θ\psi \lor \theta, ψ→φn\psi \to \varphi_n, and θ→φn\theta \to \varphi_n true, either ψ\psi or θ\theta is true, so in either case φn\varphi_n is too.
  • →I: line nn is ψ→χ\psi \to \chi and closes the box from lines ii to n−1n - 1, with φi=ψ\varphi_i = \psi and φn−1=χ\varphi_{n-1} = \chi. That box is open at line n−1n - 1, so An−1=An∪{ψ}A_{n-1} = A_n \cup \{\psi\}, and induction gives Γ∪An∪{ψ}⊨χ\Gamma \cup A_n \cup \{\psi\} \models \chi. By semantic deduction, Γ∪An⊨ψ→χ\Gamma \cup A_n \models \psi \to \chi. ¬I is the same with χ=⊥\chi = \bot: if Γ∪An∪{ψ}⊨⊥\Gamma \cup A_n \cup \{\psi\} \models \bot, no valuation of Γ∪An\Gamma \cup A_n makes ψ\psi true, so all make ¬ψ\lnot\psi true.

At the last line no box is open, Am=∅A_m = \varnothing, and the invariant says Γ⊨φ\Gamma \models \varphi.

∎

→I is the only delicate case and explains why discharge matters. If a line could cite assumption ψ\psi after its box closed, the invariant would break: that line would depend on ψ\psi, but ψ∉An\psi \notin A_n. This is precisely the error the lab checker must detect, requested by the coding exercise.

Soundness has a practical consequence already seen: to show Γ⊬φ\Gamma \nvdash \varphi no need to test every derivation; one valuation making premises true and φ\varphi false suffices. Thus p→q⊬q→pp \to q \nvdash q \to p (with p=0p = 0, q=1q = 1), and the system is consistent: ⊬⊥\nvdash \bot, since no valuation makes ⊥\bot true.

Proof

Sketch, Kalmár’s version. It suffices to consider Γ=∅\Gamma = \varnothing: if {γ1,…,γk}⊨φ\{\gamma_1, \dots, \gamma_k\} \models \varphi, then ⊨γ1→(γ2→⋯→φ)\models \gamma_1 \to (\gamma_2 \to \cdots \to \varphi) by semantic deduction, and a derivation of that tautology yields one of φ\varphi from Γ\Gamma by applying →E kk times.

Let φ\varphi be a tautology with variables p1,…,pnp_1, \dots, p_n. For each valuation vv, write piv=pip_i^v = p_i if v(pi)=1v(p_i) = 1 and piv=¬pip_i^v = \lnot p_i if v(pi)=0v(p_i) = 0, likewise for any formula ψ\psi: ψv=ψ\psi^v = \psi if v(ψ)=1v(\psi) = 1 and ¬ψ\lnot\psi otherwise.

  1. Kalmár’s lemma: p1v,…,pnv⊢ψvp_1^v, \dots, p_n^v \vdash \psi^v for every formula ψ\psi on those variables. Prove by induction on ψ\psi‘s construction; each case is a small fixed derivation. For instance, if ψ=α→β\psi = \alpha \to \beta with v(α)=1v(\alpha) = 1 and v(β)=0v(\beta) = 0, from α\alpha and ¬β\lnot\beta derive ¬(α→β)\lnot(\alpha \to \beta) by assuming α→β\alpha \to \beta, obtaining β\beta by →E and ⊥\bot by ¬E, then closing with ¬I.
  2. Since φ\varphi is tautological, φv=φ\varphi^v = \varphi for all valuations: p1v,…,pnv⊢φp_1^v, \dots, p_n^v \vdash \varphi for all 2n2^n.
  3. Eliminate assumptions one by one. Combine two derivations differing only in pnp_n versus ¬pn\lnot p_n using ⊢pn∨¬pn\vdash p_n \lor \lnot p_n (excluded middle, needing the classical rule) and ∨E. After nn rounds ⊢φ\vdash \varphi remains.
∎

Three caveats for specialists:

  • Completeness does not mean short proofs. Kalmár’s is of order 2n2^n, like the truth table. Whether any propositional proof system has polynomial-size proofs for every tautology is an open problem equivalent to NP=coNP\mathsf{NP} = \mathsf{coNP} (Cook and Reckhow, 1979): the subject of proof complexity, and why proving a formula has no SAT solution can be very expensive.
  • First order is also complete (Gödel, 1929): every first-order logical consequence has a derivation. But no truth table decides ⊨\models, and first-order consequence is undecidable: derivations can be enumerated, but if none exists the search does not terminate.
  • Do not confuse completeness with Gödel’s incompleteness theorems (1931). These concern theories (axiom sets like arithmetic’s), not logical calculus: no consistent, recursively axiomatizable, sufficiently expressive theory proves all arithmetic truths.

Implementation: a proof checker

Write the core of a propositional proof assistant from scratch: a checker accepting or rejecting Fitch proofs line by line. The first cell is a compact version of the first lesson’s engine: tuple formulas, parser with standard precedence, minimal-parenthesis printer, and truth-table consequence.

[ ]Formulas: syntax, semantics and logical consequenceBrowser
import itertools, re

# Fórmulas como tuplas: ("var", "p"), ("bot",), ("not", A), ("and", A, B), ("or", A, B), ("imp", A, B)
BOT = ("bot",)
ALIAS = {"->": "→", "~": "¬", "&": "∧", "|": "∨"}
TOKEN = re.compile(r"\s*(->|→|¬|~|∧|&|∨|\||⊥|\(|\)|[a-z][a-z0-9]*)")

def parse(s):
    """Precedencia: ¬ > ∧ > ∨ > →. El condicional asocia por la derecha: p → q → r es p → (q → r)."""
    toks, pos = [], 0
    s = s.strip()
    while pos < len(s):
        m = TOKEN.match(s, pos)
        if not m:
            raise SyntaxError(f"no entiendo {s[pos:]!r}")
        toks.append(ALIAS.get(m.group(1), m.group(1)))
        pos = m.end()
    toks.append(None)
    i = 0

    def peek():
        return toks[i]

    def eat(t=None):
        nonlocal i
        tok = toks[i]
        if t is not None and tok != t:
            raise SyntaxError(f"esperaba {t!r} y encontré {tok!r}")
        i += 1
        return tok

    def imp():
        a = disj()
        if peek() == "→":
            eat()
            return ("imp", a, imp())
        return a

    def disj():
        a = conj()
        while peek() == "∨":
            eat()
            a = ("or", a, conj())
        return a

    def conj():
        a = unary()
        while peek() == "∧":
            eat()
            a = ("and", a, unary())
        return a

    def unary():
        t = eat()
        if t == "¬":
            return ("not", unary())
        if t == "⊥":
            return BOT
        if t == "(":
            a = imp()
            eat(")")
            return a
        if t and t[0].isalpha():
            return ("var", t)
        raise SyntaxError(f"fórmula incompleta en {s!r}")

    f = imp()
    if peek() is not None:
        raise SyntaxError(f"sobra {peek()!r} en {s!r}")
    return f

PREC = {"imp": 1, "or": 2, "and": 3}
SYM = {"imp": "→", "or": "∨", "and": "∧"}

def show(f, need=0):
    """Escribe f con los paréntesis mínimos (need: precedencia mínima que el contexto admite sin paréntesis)."""
    k = f[0]
    if k == "var":
        return f[1]
    if k == "bot":
        return "⊥"
    if k == "not":
        return "¬" + show(f[1], 4)
    p = PREC[k]
    s = f"{show(f[1], p + 1)} {SYM[k]} {show(f[2], p if k == 'imp' else p + 1)}"
    return f"({s})" if p < need else s

def variables(f, acc=None):
    acc = set() if acc is None else acc
    if f[0] == "var":
        acc.add(f[1])
    for g in f[1:]:
        if isinstance(g, tuple):
            variables(g, acc)
    return acc

def value(f, v):
    """Semántica veritativa: v asigna True/False a cada variable."""
    k = f[0]
    if k == "var":
        return v[f[1]]
    if k == "bot":
        return False
    if k == "not":
        return not value(f[1], v)
    a, b = value(f[1], v), value(f[2], v)
    return {"and": a and b, "or": a or b, "imp": (not a) or b}[k]

def entails(premises, phi):
    """Γ ⊨ φ por tabla de verdad. Devuelve (True, None) o (False, valoración que lo refuta)."""
    names = sorted(set().union(variables(phi), *[variables(g) for g in premises]))
    for bits in itertools.product([False, True], repeat=len(names)):
        v = dict(zip(names, bits))
        if all(value(g, v) for g in premises) and not value(phi, v):
            return False, {x: int(b) for x, b in v.items()}
    return True, None

for s in ["p -> q -> r", "(p -> q) -> r", "~(p | q) -> ~p & ~q", "p & (q & r)", "¬¬p ∨ ⊥"]:
    print(f"{s:22s} ->  {show(parse(s))}")
print(entails([parse("p -> q"), parse("~q")], parse("~p")))
print(entails([parse("p -> q"), parse("q")], parse("p")))

The last two lines are modus tollens, valid, and affirming the consequent, invalid: the table returns countermodel p=0p = 0, q=1q = 1.

Now the checker. A proof is a list of lines (fórmula, regla, *citas), numbered from 1. Class Fitch maintains the open-box stack and closed-box list; get checks scope, rejecting citations of closed-box lines; each rule checks its schema before modifying anything and raises ProofError with an explanation on failure. innermost requires a box rule to cite the innermost box ending immediately before; discharge closes it.

[ ]The checker: boxes, scope and rulesBrowser
class ProofError(Exception):
    pass

class Fitch:
    """Demostración al estilo Fitch que se comprueba línea a línea (las líneas se numeran desde 1)."""

    def __init__(self, premises=()):
        self.premises = [parse(p) if isinstance(p, str) else p for p in premises]
        self.lines, self.just, self.depth = [], [], []
        self.open = []      # pila de cajas abiertas: número de la línea de su suposición
        self.closed = []    # cajas ya cerradas, como (i, j): sus líneas no se pueden volver a citar

    def get(self, k):
        """Fórmula de la línea k, si es accesible desde la línea que se está escribiendo."""
        n = len(self.lines) + 1
        if not 1 <= k < n:
            raise ProofError(f"cita la línea {k}, que no existe antes de la {n}")
        for i, j in self.closed:
            if i <= k <= j:
                raise ProofError(f"cita la línea {k}, de la caja {i}..{j}, que ya está cerrada")
        return self.lines[k - 1]

    def innermost(self, i, j):
        """La caja citada debe ser la más interna y acabar justo en la línea anterior."""
        n = len(self.lines) + 1
        if not self.open:
            raise ProofError("no hay ninguna caja abierta")
        if (i, j) != (self.open[-1], n - 1):
            raise ProofError(f"debe citar la caja más interna, {self.open[-1]}..{n - 1}")
        return self.lines[i - 1], self.lines[j - 1]

    def discharge(self):
        """Cierra la caja más interna: su suposición queda descargada."""
        i = self.open.pop()
        self.closed.append((i, len(self.lines)))

    def add(self, f, rule, *refs):
        f = parse(f) if isinstance(f, str) else f
        if rule not in RULES:
            raise ProofError(f"regla desconocida {rule!r}")
        RULES[rule](self, f, *refs)          # lanza ProofError si el paso no es válido
        self.lines.append(f)
        sep = "-" if rule in ("→I", "¬I") else ", "          # las reglas de caja citan un rango i-j
        self.just.append(rule + (" " + sep.join(map(str, refs)) if refs else ""))
        self.depth.append(len(self.open))

def need(cond, msg):
    if not cond:
        raise ProofError(msg)

def r_premisa(P, f):
    need(not P.open and f in P.premises, "no es una de las premisas (o está dentro de una caja)")

def r_sup(P, f):
    P.open.append(len(P.lines) + 1)          # abre una caja; su suposición es esta línea

def r_copia(P, f, a):
    need(P.get(a) == f, "copia una fórmula distinta")

def r_and_i(P, f, a, b):
    need(f == ("and", P.get(a), P.get(b)), "∧I: la conclusión debe ser (línea a) ∧ (línea b)")

def r_and_e(side):
    def rule(P, f, a):
        g = P.get(a)
        need(g[0] == "and", f"∧E: la línea {a} no es una conjunción")
        need(f == g[side], "∧E: la conclusión no es ese miembro de la conjunción")
    return rule

def r_or_i(side):
    def rule(P, f, a):
        need(f[0] == "or" and f[side] == P.get(a), f"∨I: la conclusión debe ser una disyunción con la línea {a} como miembro")
    return rule

def r_or_e(P, f, a, b, c):
    d, g, h = P.get(a), P.get(b), P.get(c)
    need(d[0] == "or", f"∨E: la línea {a} no es una disyunción")
    need(g == ("imp", d[1], f) and h == ("imp", d[2], f), "∨E: hacen falta φ → χ y ψ → χ para cada miembro de φ ∨ ψ")

def r_imp_e(P, f, a, b):
    g, h = P.get(a), P.get(b)
    need(h[0] == "imp", f"→E: la línea {b} no es un condicional")
    need(h[1] == g, f"→E: el antecedente de la línea {b} no es la línea {a}")
    need(h[2] == f, "→E: la conclusión debe ser el consecuente")

def r_not_i(P, f, i, j):
    phi, last = P.innermost(i, j)
    need(last == BOT, "¬I: la caja tiene que terminar en ⊥")
    need(f == ("not", phi), "¬I: la conclusión debe ser la negación de la suposición")
    P.discharge()

def r_not_e(P, f, a, b):
    need(f == BOT and P.get(b) == ("not", P.get(a)), "¬E: hacen falta φ y ¬φ, y se concluye ⊥")

def r_bot_e(P, f, a):
    need(P.get(a) == BOT, f"⊥E: la línea {a} no es ⊥")

def r_dne(P, f, a):
    need(P.get(a) == ("not", ("not", f)), "¬¬E: la línea citada debe ser ¬¬φ")

RULES = {"premisa": r_premisa, "sup": r_sup, "copia": r_copia,
         "∧I": r_and_i, "∧E1": r_and_e(1), "∧E2": r_and_e(2), "∨I1": r_or_i(1), "∨I2": r_or_i(2), "∨E": r_or_e,
         "→E": r_imp_e, "¬I": r_not_i, "¬E": r_not_e, "⊥E": r_bot_e, "¬¬E": r_dne}

def check(proof, premises=(), goal=None):
    """Comprueba una demostración entera. Devuelve (True, P) o (False, mensaje con la línea que falla)."""
    P = Fitch(premises)
    for n, (f, rule, *refs) in enumerate(proof, start=1):
        try:
            P.add(f, rule, *refs)
        except ProofError as e:
            return False, f"línea {n} ({show(parse(f) if isinstance(f, str) else f)}): {e}"
    if P.open:
        return False, f"quedan suposiciones abiertas en las líneas {P.open}"
    if goal is not None and (not P.lines or P.lines[-1] != parse(goal)):
        return False, "la última línea no es el objetivo"
    return True, P

def show_proof(P):
    for n, (f, j, d) in enumerate(zip(P.lines, P.just, P.depth), start=1):
        print(f"{n:>3}  {'│ ' * d}{show(f):<{24 - 2 * d}}  {j}")

→I is missing. It is the most important rule and you implement it in the coding exercise; here a hidden cell loads it so the rest works. With the complete checker, check the builder’s three derivations and three flawed proofs.

[ ]Handwritten proofs, good and badBrowser
contrarreciproco = [
    ("p -> q", "sup"),
    ("~q", "sup"),
    ("p", "sup"),
    ("q", "→E", 3, 1),
    ("⊥", "¬E", 4, 2),
    ("~p", "¬I", 3, 5),
    ("~q -> ~p", "→I", 2, 6),
    ("(p -> q) -> (~q -> ~p)", "→I", 1, 7),
]
de_morgan = [                                   # ¬p ∧ ¬q ⊢ ¬(p ∨ q)
    ("~p & ~q", "premisa"),
    ("p | q", "sup"),
    ("p", "sup"),
    ("~p", "∧E1", 1),
    ("⊥", "¬E", 3, 4),
    ("p -> ⊥", "→I", 3, 5),
    ("q", "sup"),
    ("~q", "∧E2", 1),
    ("⊥", "¬E", 7, 8),
    ("q -> ⊥", "→I", 7, 9),
    ("⊥", "∨E", 2, 6, 10),
    ("~(p | q)", "¬I", 2, 11),
]
tercero_excluido = [                            # ⊢ p ∨ ¬p, que necesita la regla clásica ¬¬E
    ("~(p | ~p)", "sup"),
    ("p", "sup"),
    ("p | ~p", "∨I1", 2),
    ("⊥", "¬E", 3, 1),
    ("~p", "¬I", 2, 4),
    ("p | ~p", "∨I2", 5),
    ("⊥", "¬E", 6, 1),
    ("~~(p | ~p)", "¬I", 1, 7),
    ("p | ~p", "¬¬E", 8),
]
casos = [
    ("contrarrecíproco", contrarreciproco, [], "(p -> q) -> (~q -> ~p)"),
    ("De Morgan", de_morgan, ["~p & ~q"], "~(p | q)"),
    ("tercero excluido", tercero_excluido, [], "p | ~p"),
]
for nombre, prueba, prem, goal in casos:
    ok, P = check(prueba, prem, goal)
    print(f"── {nombre}: {'correcta' if ok else P}")
show_proof(check(contrarreciproco, [], None)[1])

print("\nTres demostraciones defectuosas:")
afirmar_consecuente = [("p -> q", "premisa"), ("q", "premisa"), ("p", "→E", 2, 1)]
fuera_de_la_caja = [("q", "sup"), ("q -> q", "→I", 1, 1), ("q", "copia", 1)]
caja_sin_cerrar = [("p", "sup"), ("p | q", "∨I1", 1)]
for prueba, prem in [(afirmar_consecuente, ["p -> q", "q"]), (fuera_de_la_caja, []), (caja_sin_cerrar, [])]:
    print("  ", check(prueba, prem)[1])

The flawed proofs fail differently: the first affirms the consequent (from qq and p→qp \to q one cannot infer pp); the second uses assumption qq after discharge and would otherwise “prove” qq without premises; the third leaves an assumption open, proving p⊢p∨qp \vdash p \lor q, not ⊢p∨q\vdash p \lor q.

Soundness checked empirically

Soundness says each line follows logically from premises and assumptions open at that point. Using the first cell’s semantic engine, audit accepted proofs line by line. To avoid relying on a few handwritten proofs, generate thousands randomly: a generator proposes random steps and the checker decides which remain. If a checker bug admits an invalid step, the audit finds a countermodel.

[ ]Semantic audit and random proofsBrowser
import random

def audit(P):
    """Corrección línea a línea: premisas + suposiciones abiertas en la línea n ⊨ fórmula de la línea n."""
    stack, bad = [], []
    for n, (f, j) in enumerate(zip(P.lines, P.just), start=1):
        rule = j.split()[0]
        if rule in ("→I", "¬I"):
            stack.pop()                          # esta línea ya está fuera de la caja
        if rule == "sup":
            stack.append(f)
        ok, v = entails(P.premises + stack, f)
        if not ok:
            bad.append((n, show(f), v))
    return bad

for nombre, prueba, prem, goal in casos:
    print(f"{nombre:17s} líneas con Γ + abiertas ⊭ línea: {audit(check(prueba, prem, goal)[1])}")

ATOMS = [parse(x) for x in ["p", "q", "r", "~p", "p -> q", "q | r", "~(p & q)", "⊥"]]

def random_proof(rnd, steps=14):
    """Genera una demostración al azar: propone pasos y se queda con los que el verificador acepta."""
    P = Fitch(rnd.sample(ATOMS[:7], 2))
    for g in P.premises:
        P.add(g, "premisa")
    for _ in range(steps):
        n = len(P.lines)
        acc = [k for k in range(1, n + 1) if not any(i <= k <= j for i, j in P.closed)]
        a, b, c = (rnd.choice(acc) for _ in range(3))
        fa, fb = P.lines[a - 1], P.lines[b - 1]
        r = rnd.choice(["sup", "sup", "→I", "¬I", "∧I", "∧E1", "∧E2", "∨I1", "∨I2", "→E", "¬E", "⊥E", "¬¬E", "∨E"])
        try:
            if r == "sup":
                P.add(rnd.choice(ATOMS), "sup")
            elif r in ("→I", "¬I") and P.open:
                i = P.open[-1]
                f = ("imp", P.lines[i - 1], P.lines[-1]) if r == "→I" else ("not", P.lines[i - 1])
                P.add(f, r, i, n)
            elif r == "∧I":
                P.add(("and", fa, fb), r, a, b)
            elif r in ("∧E1", "∧E2") and fa[0] == "and":
                P.add(fa[1 if r == "∧E1" else 2], r, a)
            elif r in ("∨I1", "∨I2"):
                o = rnd.choice(ATOMS)
                P.add(("or", fa, o) if r == "∨I1" else ("or", o, fa), r, a)
            elif r == "→E" and fb[0] == "imp":
                P.add(fb[2], r, a, b)
            elif r == "¬E":
                P.add(BOT, r, a, b)
            elif r == "⊥E":
                P.add(rnd.choice(ATOMS), r, a)
            elif r == "¬¬E" and fa[0] == "not" and fa[1][0] == "not":
                P.add(fa[1][1], r, a)
            elif r == "∨E" and fa[0] == "or" and fb[0] == "imp":
                P.add(fb[2], r, a, b, c)
        except ProofError:
            pass                                  # paso rechazado: se descarta
    return P

def fuzz(n_proofs=1500, seed=0):
    rnd = random.Random(seed)
    lines = 0
    for _ in range(n_proofs):
        P = random_proof(rnd)
        lines += len(P.lines)
        bad = audit(P)
        if bad:
            return lines, bad[0], P
    return lines, None, None

lines, bad, _ = fuzz()
print(f"\nCorrección empírica: {lines} líneas de 1500 demostraciones aleatorias, contraejemplos: {bad}")

# Un verificador con un fallo: →I que no descarga la suposición
def imp_i_sin_descarga(P, f, i, j):
    phi, psi = P.innermost(i, j)
    need(f == ("imp", phi, psi), "→I: conclusión incorrecta")
    P.open.pop()                                  # cierra la caja... pero no la marca como cerrada

RULES["→I"], correcta = imp_i_sin_descarga, RULES["→I"]
ok, P = check(fuera_de_la_caja, [], "q")
print("\nCon el fallo, «⊢ q» se acepta:", ok, "| auditoría:", audit(P) if ok else P)
lines, bad, P = fuzz()
print(f"El fuzzing lo encuentra tras {lines} líneas: línea {bad[0]}, {bad[1]}, valoración {bad[2]}")
RULES["→I"] = correcta

With the correct checker over eleven thousand generated lines pass audit: each follows from its premises and open assumptions, the soundness invariant checked in thousands of instances. Then introduce a subtle realistic bug: →I pops the box stack but does not mark the box closed, leaving lines citable. The faulty checker accepts ⊢q\vdash q, and the audit points to the line following from nothing (qq false under q=0q = 0). The random generator finds its own counterexample in a few dozen lines. The practical lesson: a faulty checker is exposed not by good proofs but bad ones it accepts, hence testing against semantics.

The professional version: solvers and proof assistants

To decide Γ⊨φ\Gamma \models \varphi in practice, do not write truth tables: ask a solver whether Γ∪{¬φ}\Gamma \cup \{\lnot\varphi\} is satisfiable, and consequence holds exactly when it is not. SymPy provides this (entails), converting to conjunctive normal form and using a DPLL-like algorithm. Check agreement with our table on random formulas.

[ ]Logical consequence with SymPyBrowser
import sympy as sp
from sympy.logic.inference import entails as sp_entails, satisfiable

def to_sympy(f, env):
    k = f[0]
    if k == "var":
        return env.setdefault(f[1], sp.Symbol(f[1]))
    if k == "bot":
        return sp.false
    if k == "not":
        return sp.Not(to_sympy(f[1], env))
    a, b = to_sympy(f[1], env), to_sympy(f[2], env)
    return {"and": sp.And, "or": sp.Or, "imp": sp.Implies}[k](a, b)

env = {}
gamma = [to_sympy(parse(s), env) for s in ["p -> q", "q -> r"]]
print("sympy: {p → q, q → r} ⊨ p → r:", sp_entails(to_sympy(parse("p -> r"), env), gamma))
print("contramodelo de q → p desde p → q:", satisfiable(sp.And(gamma[0], sp.Not(to_sympy(parse("q -> p"), env)))))

def random_formula(rnd, depth):
    if depth == 0 or rnd.random() < 0.25:
        return rnd.choice([("var", "p"), ("var", "q"), ("var", "r"), BOT])
    k = rnd.choice(["not", "and", "or", "imp"])
    if k == "not":
        return ("not", random_formula(rnd, depth - 1))
    return (k, random_formula(rnd, depth - 1), random_formula(rnd, depth - 1))

rnd = random.Random(1)
acuerdos, validas, N = 0, 0, 150
for _ in range(N):
    prem = [random_formula(rnd, 2) for _ in range(2)]
    phi = random_formula(rnd, 3)
    ours = entails(prem, phi)[0]
    theirs = bool(sp_entails(to_sympy(phi, env), [to_sympy(g, env) for g in prem]))
    acuerdos += ours == theirs
    validas += ours
print(f"tabla de verdad frente a sympy: {acuerdos}/{N} coinciden ({validas} consecuencias válidas)")

SymPy answers ⊨\models, not ⊢\vdash: it says whether consequence holds but supplies no independently checkable derivation. A SAT solver reporting “unsatisfiable” can instead produce a checkable certificate, the idea of resolution. For the derivation itself use a proof assistant. In Lean 4 contraposition is written:

example (p q : Prop) : (p → q) → (¬q → ¬p) := by
  intro hpq hnq hp      -- tres suposiciones: tres →I (las cajas 1, 2 y 3)
  exact hnq (hpq hp)    -- hpq hp : q por →E; hnq aplicado a q da False (¬E)

Each tactic is a table rule. intro opens an assumption discharged at the end (→I and ¬I, because in Lean ¬q\lnot q is defined as q→⊥q \to \bot); applying a function to an argument is →E. Lean’s state between tactics is the first interactive’s hypothesis–goal panel. The design matches our lab: a small kernel checks proof terms, so trusting a thousand-line proof requires trusting only that kernel, not the tactics that generated it. This is developed in proof assistants, and enables a language model to propose proofs: the checker decides.

Common mistakes

Exercises

ProofIf n² is even, n is even
Prove: For every integer nn, if n2n^2 is even, then nn is even.
0
Fix an arbitrary integer nn. Every integer is even or odd, and not both.

Step 1 of 3. Which strategy and assumption do you choose?

ProofSquares modulo 4
Prove: For every integer nn, n2 mod 4∈{0,1}n^2 \bmod 4 \in \{0, 1\}.
0
Fix an arbitrary integer nn.

Step 1 of 3. What is the most economical case split?

Proof√p is irrational for every prime p
Prove: If pp is prime, p\sqrt p is irrational.
0
Adapt the proof for 2\sqrt 2. You may use Euclid's lemma: if a prime pp divides xyxy, then p∣xp \mid x or p∣yp \mid y.

Step 1 of 4. Begin as with 2\sqrt 2. What equation do you obtain?

QuizA proof that 2 = 1
Let a=b≠0a = b \neq 0. (1) Multiply by aa: a2=aba^2 = ab. (2) Subtract b2b^2: a2−b2=ab−b2a^2 - b^2 = ab - b^2. (3) Factor: (a+b)(a−b)=b(a−b)(a + b)(a - b) = b(a - b). (4) Cancel (a−b)(a - b): a+b=ba + b = b. (5) Since a=ba = b: 2b=b2b = b, and dividing by bb, 2=12 = 1. Which step is invalid?
QuizA proof chasing its tail
‘Theorem: if n2n^2 is even, nn is even. Proof: (1) Let nn be an integer with n2n^2 even. (2) Then n2=2kn^2 = 2k for some integer kk. (3) Since nn is even, n=2mn = 2m. (4) Thus n2=4m2=2(2m2)n^2 = 4m^2 = 2(2m^2), confirming that n2n^2 is even, as assumed. ∎’ Where is the error?
QuizAn example is not a proof
‘Theorem: for all integers a,b,ca, b, c, if a∣bca \mid bc then a∣ba \mid b or a∣ca \mid c. Proof: with a=3a = 3, b=6b = 6 and c=5c = 5, we have 3∣303 \mid 30 and indeed 3∣63 \mid 6. ∎’ What is wrong?
QuizThe form of a limit
You want to prove lim⁡x→23x=6\lim_{x \to 2} 3x = 6, that is, ∀ε>0  ∃δ>0  ∀x (∣x−2∣<δ→∣3x−6∣<ε)\forall \eps > 0\; \exists \delta > 0\; \forall x\, \big(\abs{x - 2} < \delta \to \abs{3x - 6} < \eps\big). What sequence of strategies does the logical form dictate?
ProofDe Morgan in natural deduction
Prove: ¬(p∨q)⊢¬p∧¬q\lnot(p \lor q) \vdash \lnot p \land \lnot q
0
Line 1: the premise ¬(p∨q)\lnot(p \lor q). The goal is a conjunction.

Step 1 of 4. What strategy does the form of the goal dictate?

ProofThe converse of De Morgan's law
Prove: ¬p∧¬q⊢¬(p∨q)\lnot p \land \lnot q \vdash \lnot(p \lor q)
0
Line 1: the premise ¬p∧¬q\lnot p \land \lnot q. In this system, ∨E cites φ∨ψ\varphi \lor \psi, φ→χ\varphi \to \chi and ψ→χ\psi \to \chi.

Step 1 of 3. The goal is a negation. What do you do?

CodeThe →I rule, with discharge
Complete r_imp_i(P, f, i, j) in this reduced checker (rules: premise, sup, copy, →E and →I). At line n = len(P.lines) + 1, →I cites the box from lines i to j. Check that there is an open box, that the innermost begins at i (P.open[-1] == i) and ends immediately before (j == n - 1), and that f == imp(línea i, línea j); if anything fails, raise ProofError. If all is correct, discharge the assumption: remove the box from P.open and add (i, j) to P.closed so its lines cannot be cited again. Formulas are tuples: ('var', 'p'), imp(a, b) = ('imp', a, b).
class ProofError(Exception):
  pass

def imp(a, b):
  return ("imp", a, b)

class Fitch:
  def __init__(self, premises=()):
      self.premises = list(premises)
      self.lines = []      # fórmulas, línea n en self.lines[n - 1]
      self.open = []       # pila de cajas abiertas: número de línea de cada suposición
      self.closed = []     # cajas cerradas (i, j): sus líneas ya no se pueden citar

  def get(self, k):
      n = len(self.lines) + 1
      if not 1 <= k < n:
          raise ProofError(f"la línea {k} no existe antes de la {n}")
      for i, j in self.closed:
          if i <= k <= j:
              raise ProofError(f"la línea {k} está en la caja cerrada {i}..{j}")
      return self.lines[k - 1]

  def add(self, f, rule, *refs):
      RULES[rule](self, f, *refs)
      self.lines.append(f)

def r_premisa(P, f):
  if P.open or f not in P.premises:
      raise ProofError("no es una premisa")

def r_sup(P, f):
  P.open.append(len(P.lines) + 1)

def r_copia(P, f, a):
  if P.get(a) != f:
      raise ProofError("copia una fórmula distinta")

def r_imp_e(P, f, a, b):
  if P.get(b) != imp(P.get(a), f):
      raise ProofError("→E mal aplicada")

def r_imp_i(P, f, i, j):
  """→I en la línea n = len(P.lines) + 1, citando la caja i..j.
  Comprueba que (i, j) es la caja más interna y abierta, que termina justo antes (j = n - 1)
  y que f es imp(línea i, línea j); si algo falla, lanza ProofError. Después, descarga la suposición."""
  pass

RULES = {"premisa": r_premisa, "sup": r_sup, "copia": r_copia, "→E": r_imp_e, "→I": r_imp_i}

def check(proof, premises=()):
  """True si la demostración es correcta y no deja suposiciones abiertas."""
  P = Fitch(premises)
  try:
      for f, rule, *refs in proof:
          P.add(f, rule, *refs)
  except ProofError:
      return False
  return not P.open
Shift+Enter to run
QuizAdding a rule
You add the rule ‘from ψ\psi and φ→ψ\varphi \to \psi, conclude φ\varphi’ to the system. What happens to it?
QuizWhich proofs need classical logic?
Which of these proofs in the lesson essentially use a classical principle (excluded middle or the step from ¬¬P\lnot\lnot P to PP)?

More than one answer may be correct.

NumericAnother generous polynomial
The polynomial n2−79n+1601n^2 - 79n + 1601 produces primes for n=0,1,2,…n = 0, 1, 2, \dots for a long time. What is the smallest integer n≥0n \ge 0 for which its value is composite?
NumericTen points on a circle
1010 points are placed on a circle, with no three chords concurrent, and all chords are drawn. Into how many regions is the circle divided?

Summary

Key idea
A proof is a finite object checked step by step: the logical form of the goal and assumptions dictates at each step what may be assumed and what remains to be shown. Natural deduction turns those strategies into introduction and elimination rules with assumptions that are opened and discharged, and soundness and completeness guarantee that what is derivable (⊢\vdash) is exactly what is true in every valuation (⊨\models).
  • Strategies by form: prove P→QP \to Q by assuming PP (directly) or ¬Q\lnot Q (contraposition); ¬P\lnot P by assuming PP and reaching ⊥\bot; ∀\forall by fixing an arbitrary object; ∃\exists by giving a witness. An ∃\exists assumption gives a new name, and a ∨\lor requires reasoning by exhaustive cases.
  • Contradiction versus contraposition: negation introduction (refutation) is intuitionistic; concluding PP from ¬¬P\lnot\lnot P is classical. If the contradiction consists of deriving ¬P\lnot P from ¬Q\lnot Q alone to clash with assumption PP, you have a contrapositive proof.
  • Existence: a constructive proof gives a witness and therefore an algorithm; a nonconstructive one (by cases on an undecided claim or by contradiction) may not. 22\sqrt2^{\sqrt2} is the canonical example.
  • Counterexamples: one suffices to refute a ∀\forall; no finite number of cases proves it (n2+n+41n^2 + n + 41 fails at 4040, F5F_5 has factor 641641, the circle gives 3131).
  • Natural deduction: boxes are scopes; a line in a closed box cannot be cited. The Fitch checker fits in a few dozen lines and is audited against the semantics.
  • Soundness and completeness: ⊢\vdash implies ⊨\models (induction on the derivation, using the deduction theorem in the →I step), and ⊨\models implies ⊢\vdash (Kalmár). A countermodel suffices to refute derivability; the existence of a proof does not mean it is short.