Foundations to FrontierPart II: FoundationsBezhig

C04: Logic, sets, relations, and constructing proofs

5 exercises, each with a complete solution. 1 figure. 1 code listing.

On this page
  1. A. Prerequisites and observable goals
  2. B. The central question: what would make this claim true or false?
  3. C. Quantifiers and their order
  4. D. How to build a proof
  5. E. Relations organize objects into classes and orders
  6. F. Finite logic checking is useful within a stated boundary
  7. G. Independent practice
  8. H. Complete solutions: C04
  9. I. Retention and readiness

A. Prerequisites and observable goals#

Before

C01 state and Boolean values; algebra and function notation.

After

Translate quantified claims, negate them correctly, construct direct and contrapositive proofs, find counterexamples, and distinguish a finite test from a general argument.

Level: Degree core.

B. The central question: what would make this claim true or false?#

A proof is a logically justified argument from stated assumptions to a conclusion. It is not a longer example or a report that code passed tests. Before proving a claim, identify its domain, quantifiers, and conditions. “This search works” is too vague. “For every finite nondecreasing integer sequence and every integer target, this function returns the first qualifying index or the length” is a proposition with a testable meaning and a possible proof structure.

A proposition has a truth value. The operators ¬\neg, ∧\land, and ∨\lor mean not, and, and inclusive or. An implication P⇒QP\Rightarrow Q is false only when PP is true and QQ is false. When PP is false, the implication is true in classical propositional logic; it does not assert that PP occurs or causes QQ. An equivalence P⇔QP\Leftrightarrow Q requires both directions. Proving one implication does not establish the converse.

C. Quantifiers and their order#

∀x∈D P(x)\forall x\in D\,P(x) means every element of the specified domain satisfies the predicate. ∃x∈D P(x)\exists x\in D\,P(x) means at least one witness exists. Negation changes both the quantifier and predicate:

¬(∀x P(x))≡∃x ¬P(x),¬(∃x P(x))≡∀x ¬P(x).\neg(\forall x\,P(x))\equiv\exists x\,\neg P(x),\qquad \neg(\exists x\,P(x))\equiv\forall x\,\neg P(x).

Thus disproving a universal claim needs one valid counterexample, whereas proving it needs a general argument covering the entire domain. Testing a million cases can reveal a counterexample but cannot by itself prove a claim over all integers.

The claims ∀x ∃y (y>x)\forall x\,\exists y\,(y>x) and ∃y ∀x (y>x)\exists y\,\forall x\,(y>x) over the integers differ. The first is true: choose y=x+1y=x+1 depending on xx. The second asks for one integer greater than every integer, which does not exist. This distinction appears in software contracts: “each request eventually gets some response” is not the same as “there is one fixed response time bound that works for every request.” Additional timing assumptions would be needed for a uniform bound.

Sets collect distinct elements without an intrinsic order. Membership x∈Ax\in A differs from inclusion A⊆BA\subseteq B. Union, intersection, and complement act on sets; complements require a declared universe. De Morgan’s laws, (A∪B)c=Ac∩Bc(A\cup B)^c=A^c\cap B^c and (A∩B)c=Ac∪Bc(A\cap B)^c=A^c\cup B^c, follow by checking membership of an arbitrary element. A list can contain duplicates and preserve order, so it is not interchangeable with a mathematical set.

What makes an implication true or false. Read P⇒QP\Rightarrow Q over a domain as a claim about two sets: it holds when every element with property PP also has property QQ, so the PP region lies inside the QQ region. It fails as soon as one element, a witness, has PP without QQ. Proving it takes an argument about every element; disproving it takes one witness.

D. How to build a proof#

For a direct proof of P⇒QP\Rightarrow Q, assume PP, unpack its definitions, and derive QQ with justified steps. For a contrapositive proof, prove ¬Q⇒¬P\neg Q\Rightarrow\neg P, which is logically equivalent to the original implication. For a contradiction proof, assume the negation of the desired claim together with the hypotheses and derive an impossibility. These methods are choices of argument organization, not magic words that turn an unsupported calculation into a proof.

Example: if an integer nn has even square, then nn is even. The contrapositive says an odd integer has odd square. Write an arbitrary odd integer as n=2k+1n=2k+1 for an integer kk. Then n2=4k2+4k+1=2(2k2+2k)+1n^2=4k^2+4k+1=2(2k^2+2k)+1, which is odd by definition. This covers every odd integer, including negative ones. Checking 32=93^2=9 and 52=255^2=25 would only illustrate it.

For a contradiction example, suppose 2=p/q\sqrt2=p/q with coprime integers p,qp,q and q≠0q\ne0. Then p2=2q2p^2=2q^2, so pp is even by the previous result. Write p=2rp=2r to get q2=2r2q^2=2r^2, hence qq is even too. Both being even contradicts coprimality. The argument depends on choosing a reduced fraction; without that condition, discovering a common factor would not contradict the assumption.

E. Relations organize objects into classes and orders#

A binary relation on SS is a subset of S×SS\times S. An equivalence relation is reflexive (x∼xx\sim x), symmetric (x∼yx\sim y implies y∼xy\sim x), and transitive (x∼yx\sim y, y∼zy\sim z imply x∼zx\sim z). It partitions the set into disjoint equivalence classes. Equality modulo m>0m>0, defined by mm dividing a−ba-b, is an example: each integer belongs to exactly one residue class.

A partial order is reflexive, antisymmetric, and transitive. Antisymmetric means x⪯yx\preceq y and y⪯xy\preceq x together imply x=yx=y; it does not mean that reversing every pair makes the relation false. Set inclusion is a partial order, and some sets are incomparable. A total order additionally compares every pair. Sorting and search rely on specific ordering assumptions; a comparator that changes its answer or violates transitivity can invalidate the algorithm’s reasoning.

A function assigns exactly one output in its codomain to each input in its domain. Injectivity means distinct inputs have distinct outputs; surjectivity means every codomain element occurs; bijectivity means both. The chosen codomain matters. The map x↦x2x\mapsto x^2 from R\R to R\R is neither injective nor surjective, but restricted from [0,∞)[0,\infty) to [0,∞)[0,\infty) it is bijective. This revisits calculus inverse-function conditions in a discrete language.

F. Finite logic checking is useful within a stated boundary#

A truth-table checker can enumerate all 2n2^n assignments to nn Boolean names and find an assignment where every premise is true but the conclusion is false. For a fixed finite propositional formula, exhaustive enumeration is complete. It is not a proof method for arbitrary quantified integer claims unless the finite reduction itself is justified. The lab imposes a 16-name bound to keep exhaustive work intentional rather than accidentally exponential.

The invalid inference “P⇒QP\Rightarrow Q; QQ; therefore PP” is called affirming the consequent. Set PP false and QQ true: both premises are true and the conclusion false. The valid inference “P⇒QP\Rightarrow Q; PP; therefore QQ” has no such assignment. Finding the counterexample is more informative than saying the first argument “looks wrong.”

G. Independent practice#

F foundation C standard course work T transfer S optional stretch L runnable lab or project. Attempt the complete set before opening its solutions.

C04.01FSolution

Negate “for every request there exists a response that matches its identifier.” Keep the order of quantifiers explicit. What would a counterexample look like?

C04.02CSolution

Prove that the sum of two odd integers is even. State the domain and use the definition of oddness rather than examples.

C04.03CSolution

On the integers, define a∼ba\sim b when 33 divides a−ba-b. Prove this is an equivalence relation and describe its classes.

C04.04TSolution

A developer claims a comparator is suitable for sorting because it returned consistent answers on ten examples. Explain what properties still need justification. Construct a three-object cyclic ordering that violates transitivity.

C04.05LabSolution

Implement counterexample in logic_lab.py. Enumerate every Boolean assignment to at most 16 distinct names; return an assignment satisfying all premises but falsifying the conclusion, or None if none exists. Check affirming the consequent and modus ponens. Explain exactly what the exhaustive result proves.

Optional small hints

C04.01: negate from the outside inward. C04.03: write the three divisibility witnesses separately. C04.04: use a<ba<b, b<cb<c, and c<ac<a.

H. Complete solutions: C04#

Compare the first step where your work differs. A corrected answer is not yet an independent success.

C04.01Show solution

A request with no matching response

Let M(r,s)M(r,s) mean response ss matches request rr. The claim is ∀r ∃s M(r,s)\forall r\,\exists s\,M(r,s). Its negation is ∃r ∀s ¬M(r,s)\exists r\,\forall s\,\neg M(r,s): there is a request for which no response matches. One unmatched request is the counterexample, but establishing it requires the relevant response domain or time/finality assumptions. Merely not having seen a response yet does not establish that none will ever arrive in an asynchronous system.

Back to C04.01
C04.02Show solution

Definitions expose the general structure

Let a=2k+1a=2k+1 and b=2ℓ+1b=2\ell+1 for arbitrary integers k,ℓk,\ell. Then a+b=2k+2ℓ+2=2(k+ℓ+1)a+b=2k+2\ell+2=2(k+\ell+1). Since k+ℓ+1k+\ell+1 is an integer, the sum is even. This is a direct proof over all odd integers; it does not assume they are positive or restrict them to a tested range.

Back to C04.02
C04.03Show solution

Residue classes form a partition

Reflexivity: a−a=0=3⋅0a-a=0=3\cdot0. Symmetry: if a−b=3ka-b=3k, then b−a=3(−k)b-a=3(-k). Transitivity: if a−b=3ka-b=3k and b−c=3ℓb-c=3\ell, then a−c=3(k+ℓ)a-c=3(k+\ell). The classes are integers congruent to 0, 1, or 2 modulo 3. Every integer has exactly one such remainder under Euclidean division, and two different remainder classes cannot overlap. These statements describe an equivalence relation, not an ordering.

Back to C04.03
C04.04Show solution

A cycle defeats a sorted arrangement

A comparator used by a particular sorting interface must satisfy that interface’s ordering contract; a common C++ requirement is strict weak ordering. At minimum, a proposed strict order must not compare an object as less than itself and must be transitive, with compatible equivalence behavior. Define a<ba<b, b<cb<c, and c<ac<a. Transitivity of the first two would require a<ca<c, contradicting the cyclic direction in a strict order. Ten observed comparisons do not cover every triple or prove the relation stable across time. A comparator depending on mutable external state can fail even when its formula once behaved consistently.

Back to C04.04
C04.05Show solution

Reference finite checker

code/solutions/logic_lab.pyPython
"""C04.05: finite propositional entailment, not first-order theorem proving."""
from itertools import product
from collections.abc import Callable

def counterexample(names: list[str], premises: list[Callable],
                   conclusion: Callable) -> dict[str, bool] | None:
    if len(names) != len(set(names)):
        raise ValueError("variable names must be unique")
    if len(names) > 16:
        raise ValueError("educational exhaustive limit: 16 variables")
    for bits in product((False, True), repeat=len(names)):
        env = dict(zip(names, bits))
        if all(p(env) for p in premises) and not conclusion(env):
            return env
    return None

if __name__ == "__main__":
    implication = lambda e: not e["p"] or e["q"]
    print(counterexample(["p", "q"], [implication, lambda e: e["q"]],
                         lambda e: e["p"]))

Each Boolean assignment is visited exactly once by the Cartesian product enumeration. A returned environment is a concrete countermodel. If no countermodel exists, every assignment that satisfies all premises also satisfies the conclusion, so the finite propositional entailment holds. This does not establish real-world truth of the premises, quantify over arbitrary data structures, or solve every program-correctness problem. The domain bound also exposes exponential complexity: adding one name doubles the assignments.

Back to C04.05

I. Retention and readiness#

Retrieve domains and inverse-function restrictions from calculus. Advance when you can negate a quantified statement, name a missing hypothesis, and produce a counterexample to a tempting converse. Do not skip proof practice merely because the corresponding code is easy to run.