CMP-250 · Lesson 1 of 12 · 28 min

Why logic and proof matter in computing

Most of computing science rests on a small set of mathematical ideas: statements that are true or false, rules for combining them, collections of objects, relationships between objects, and arguments that establish facts once and for all. This course, Logic and Discrete Structures, gives you those ideas and the habit of using them carefully. It follows CMPUT-174, where you learned to write and test Python programs, and it prepares you for CMPUT-204 (Algorithms I), where you will prove that algorithms are correct and analyze how fast they run, and for CMPUT-474 (Theory of Computation), where you will meet the limits of what any computer can do.

The word discrete is the key. Calculus studies continuous quantities that change smoothly. Computers, by contrast, work with values that come in separate, countable pieces: bits, integers, characters, list positions, nodes in a network, steps of an algorithm. Discrete mathematics is the mathematics of those countable things. You already used it informally in CMPUT-174 when you counted the comparisons a search made or reasoned about which branch of an if statement would run. Here you will learn to make that reasoning precise.

Testing shows the presence of bugs, proof shows their absence

In CMPUT-174 you tested programs by choosing inputs and checking outputs. Testing is essential, but it has a hard limit. A function that takes a single 64-bit integer has about \(1.8 \times 10^{19}\) possible inputs. Even at a billion tests per second, checking them all would take more than 500 years. A function of two such integers is hopeless. The computer scientist Edsger Dijkstra put it bluntly: testing can show the presence of bugs, but never their absence.

A proof is different. It is an argument that a statement holds for every case it covers, including the cases nobody tried. When you prove that a loop computes the sum of a list for every list, you have covered infinitely many inputs with a finite argument. That is why proof matters in computing: it is the only tool that gives certainty about unbounded sets of inputs.

Forty passing tests do not make a theorem: n squared plus n plus 41
# A plausible conjecture that testing seems to confirm
def f(n):
    return n * n + n + 41

def is_prime(m):
    if m < 2:
        return False
    d = 2
    while d * d <= m:
        if m % d == 0:
            return False
        d += 1
    return True

all_prime = all(is_prime(f(n)) for n in range(40))
print("f(n) prime for n = 0..39:", all_prime)
print("f(40) =", f(40), "prime?", is_prime(f(40)))
print("41 * 41 =", 41 * 41)
Output
f(n) prime for n = 0..39: True
f(40) = 1681 prime? False
41 * 41 = 1681

The polynomial \(n^2 + n + 41\), studied by Euler, produces a prime number for every \(n\) from 0 to 39. A tester who checked those forty cases might conclude that it always produces primes. The forty-first case fails: \(f(40) = 40^2 + 40 + 41 = 1681 = 41^2\). In fact a short argument shows it must fail at \(n = 40\), because \(40 \cdot 40 + 40 + 41 = 40 \cdot 41 + 41 = 41 \cdot 41\). A single counterexample settles the question; no number of confirming examples could.

Where logic appears in everyday computing

Logic is not an abstract extra. It is built into the tools you already use, and the better you understand it the fewer mistakes you make with those tools.

Logic and discrete structures across the computing curriculum
AreaWhere logic or discrete structures appearCourse where you will go deeper
ProgrammingConditions in if and while statements, Boolean operators, short-circuit evaluationThis course, lessons 2 and 3
DatabasesSQL WHERE clauses are predicate logic; joins are built from Cartesian products and relationsCMPUT-291
HardwareLogic gates implement propositional connectives; circuits are Boolean formulasCMPUT-229
AlgorithmsCorrectness proofs, loop invariants, induction on input size, counting stepsCMPUT-204 and CMPUT-304
SecurityModular arithmetic underlies RSA and other public-key systemsCMPUT-331 and CISSP-112
Artificial intelligenceKnowledge representation, automated reasoning, satisfiability solversCMPUT-366
TheorySets, functions, countability and the limits of computationCMPUT-474

Observe how often the same ideas recur. A SQL query that asks for every customer who has placed at least one order uses an existential quantifier (lesson 4). A database table is a relation in exactly the mathematical sense of lesson 9. A hash table distributes keys using modular arithmetic (lesson 11). A recursive function is correct for the same reason an inductive proof works (lesson 10). Learning the mathematics once lets you recognize it everywhere.

Statements, definitions and theorems

Mathematical writing has a vocabulary of its own, and reading proofs is much easier once you know it. A definition gives a precise meaning to a word: for example, an integer \(n\) is even if there is an integer \(k\) with \(n = 2k\). Definitions are not true or false; they are agreements. A theorem is a statement that has been proved from definitions and previously established facts. A lemma is a smaller theorem proved mainly to help prove a larger one, and a corollary is a statement that follows quickly from a theorem. A conjecture is a statement believed to be true but not yet proved, like the claim about \(n^2 + n + 41\) before we found the counterexample.

Every proof starts from definitions. When you are stuck on a proof, the most useful question is almost always: what exactly do the words in this statement mean? Writing out the definitions turns a vague claim into concrete equations or conditions you can manipulate.

Worked problem

Unpacking a definition

Prove that the sum of two even integers is even.

Show solution
  1. Write out the definition: an integer is even if it equals 2k for some integer k.
  2. Let a and b be even. Then a = 2j and b = 2k for some integers j and k.
  3. Add them: a + b = 2j + 2k = 2(j + k).
  4. Since j + k is an integer, a + b has the form 2 times an integer, so it is even by definition.

Answer: a + b = 2(j + k), which is even by definition. The proof covers every pair of even integers, not just tested ones.

How this course works

The course moves from logic, to proof, to structures, to counting, and finishes by applying everything to programs. Each lesson has worked examples and short Python programs that let you experiment. Python is used as a laboratory: it can check a truth table, search for a counterexample or count the elements of a set. It cannot replace proof, but it can quickly tell you whether a claim is worth trying to prove.

The plan of the course
LessonsThemeKey question
2 to 4LogicHow do we express statements precisely and decide when they follow from each other?
5 and 6Proof techniquesHow do we build convincing arguments?
7 to 9Discrete structuresHow do we describe collections, mappings and relationships?
10 and 11Induction, recursion and countingHow do we reason about infinitely many cases and count possibilities?
12CapstoneHow do we prove programs correct and model networks as graphs?

Mathematical notation can look intimidating at first. Each symbol in this course is introduced with a plain-language reading. For example, \(\forall x\, P(x)\) is read as for every x, P of x, and \(A \subseteq B\) is read as A is a subset of B. When you meet a formula, read it aloud in words before trying to work with it. A good habit is to translate every line of a proof into an ordinary sentence; if you cannot, you have found the line you do not yet understand.

Using Python to explore, not to prove

A computer is an excellent partner for discrete mathematics because it can enumerate small cases quickly. Suppose someone claims that for every positive integer \(n\), the number \(2^n\) is greater than \(n^2\). Before trying to prove it, check small values.

Exploring a claim before trying to prove it
for n in range(1, 11):
    print(f"n = {n:2d}   2**n = {2**n:5d}   n**2 = {n*n:4d}   2**n > n**2: {2**n > n*n}")
Output
n =  1   2**n =     2   n**2 =    1   2**n > n**2: True
n =  2   2**n =     4   n**2 =    4   2**n > n**2: False
n =  3   2**n =     8   n**2 =    9   2**n > n**2: False
n =  4   2**n =    16   n**2 =   16   2**n > n**2: False
n =  5   2**n =    32   n**2 =   25   2**n > n**2: True
n =  6   2**n =    64   n**2 =   36   2**n > n**2: True
n =  7   2**n =   128   n**2 =   49   2**n > n**2: True
n =  8   2**n =   256   n**2 =   64   2**n > n**2: True
n =  9   2**n =   512   n**2 =   81   2**n > n**2: True
n = 10   2**n =  1024   n**2 =  100   2**n > n**2: True

The table shows the claim is false as stated: it holds for \(n = 1\) but fails at \(n = 2\), 3 and 4, then holds from \(n = 5\) onward. Exploration has told us what to prove: for every integer \(n \ge 5\), \(2^n > n^2\). That corrected statement is true, and in lesson 10 you will prove it by induction. This pattern of explore, conjecture, then prove is how mathematicians and computer scientists actually work.

Worked problem

Finding the right statement to prove

A student claims that every positive integer can be written as a sum of at most three perfect squares. Use exploration to decide whether to try proving it.

Show solution
  1. Small cases: 1 = 1, 2 = 1 + 1, 3 = 1 + 1 + 1, 4 = 4, 5 = 4 + 1, 6 = 4 + 1 + 1.
  2. Try 7: the squares below 7 are 1 and 4. Using at most three of them gives at most 4 + 1 + 1 = 6, or 4 + 4 which is 8, or combinations like 1 + 1 + 1 = 3. None gives 7.
  3. So 7 is a counterexample and the claim is false.
  4. A known theorem of Lagrange says every positive integer is a sum of four squares; 7 = 4 + 1 + 1 + 1. Exploration points toward the correct statement.

Answer: The claim is false; 7 needs four squares. A program checking all numbers below 100 would find 7, 15, 23, 28 and others.

Precision in language

Ordinary language is ambiguous in ways that matter for computing. Consider a requirement written as: users may log in with a password or a security key and a one-time code. Does the one-time code apply to both methods, or only to the security key? The sentence can be read as (password or key) and code, or as password or (key and code). A system built on the wrong reading is a security flaw. Logic gives us notation with exactly one reading, and lesson 2 will make the precedence rules explicit.

Similarly, everyday English uses or in two senses. Would you like tea or coffee usually means one or the other but not both, the exclusive or. In logic and programming, or is inclusive: true when either or both parts are true. Many arguments in specifications, contracts and bug reports come down to this distinction.

Ambiguities that logic removes
Everyday phrasePossible readingsPrecise version
A or B and C(A or B) and C; A or (B and C)Use parentheses
You get a refund or a creditInclusive or exclusiveSay exactly one of, or at least one of
If you pass the exam, you pass the courseOnly if? Also if you fail?State the converse separately if intended
Every student did not submitNo student submitted; not every student submittedWrite the quantifier and negation explicitly
A user with admin rights can delete filesOnly admins? Admins and possibly others?Say if and only if when that is meant

Proof as communication

A proof is written for a reader. In professional work that reader might be a colleague reviewing an algorithm, an auditor checking a safety argument, or your future self. A good proof states what is being proved, says which technique it uses, introduces every variable before using it, and justifies each step by a definition, an earlier result or algebra. It ends by saying clearly that the goal has been reached. In this course you will practice writing proofs in complete sentences, which is the standard expected in later courses and in research.

Computer science has also built tools that check proofs mechanically. Proof assistants such as Coq, Isabelle and Lean have been used to verify a C compiler (CompCert), an operating system microkernel (seL4) and large parts of mathematics. Satisfiability solvers, which you will meet in lesson 3, routinely check hardware designs with millions of logic gates. These tools rely on exactly the logic you will learn here, applied at enormous scale.

A cycle of four boxes connected by arrows: Explore small cases with code, Form a conjecture, Attempt a proof, and either Proof found, giving a theorem, or Counterexample found, which loops back to revise the conjecture.
The explore, conjecture and prove cycle

Common mistakes

  • MistakeTreating many passing tests as proof that a claim holds for all inputs.

    InsteadUse tests to explore and to find counterexamples; use proof to establish a claim for all cases.

  • MistakeStarting a proof without writing out the definitions involved.

    InsteadWrite each definition explicitly; it usually shows what to do next.

  • MistakeProving a claim only for one example, such as 4 + 6 = 10, and calling it a proof.

    InsteadUse arbitrary variables, such as a = 2j and b = 2k, so the argument covers every case.

  • MistakeReading or as exclusive by default.

    InsteadIn logic and programming, or is inclusive unless stated otherwise.

  • MistakeWriting proofs as a list of equations with no words.

    InsteadExplain each step in sentences so a reader can follow and check it.

  • MistakeAssuming a statement is true because it seems obvious.

    InsteadCheck small cases; obvious claims, such as 2 to the n exceeding n squared, often have exceptions.

Summary and key terms

  • Discrete mathematics studies countable structures, which is what computers manipulate.
  • Testing can find bugs but cannot show their absence; proof establishes a claim for every case.
  • One counterexample disproves a universal claim, as n squared plus n plus 41 shows at n = 40.
  • Definitions are agreements; theorems, lemmas and corollaries are proved statements; conjectures are unproved.
  • Most proofs start by writing out the definitions of the terms in the statement.
  • Use Python to explore small cases and find the right statement before trying to prove it.
  • Logic removes ambiguity from requirements, conditions and specifications.
Discrete mathematics
The mathematics of countable, separate objects such as integers, sets, graphs and finite structures.
Proof
A logically valid argument showing that a statement is true in every case it covers.
Counterexample
A single case showing that a universal statement is false.
Definition
A precise statement of what a term means, agreed rather than proved.
Theorem
A statement that has been proved.
Lemma
A theorem proved mainly as a step toward a larger result.
Corollary
A result that follows quickly from a theorem.
Conjecture
A statement believed true but not yet proved.
Inclusive or
An or that is true when either or both parts are true.
Proof assistant
Software that checks every step of a formal proof, such as Coq, Isabelle or Lean.

Practice problems

Work each problem on paper first, then reveal the answer to check.

  1. Why can't testing alone show that a sorting function is correct for all lists?

    Show answer

    There are infinitely many lists; tests cover only finitely many, so untested inputs might fail.

  2. Prove that the product of two odd integers is odd.

    Show answer

    Let a = 2j + 1 and b = 2k + 1. Then ab = 4jk + 2j + 2k + 1 = 2(2jk + j + k) + 1, which is odd.

  3. Find the smallest n at which n squared minus n plus 41 is not prime.

    Show answer

    n = 41 gives 41 squared, which is composite (n = 0 to 40 give primes).

  4. Is a definition true or false?

    Show answer

    Neither; it is an agreement about what a word means.

  5. Give two readings of 'free shipping for members or orders over 50 and in stock'.

    Show answer

    (member or over 50) and in stock; or member or (over 50 and in stock).

  6. What is the difference between a lemma and a corollary?

    Show answer

    A lemma is proved to help prove a theorem; a corollary follows easily from a theorem.

  7. A program checks the claim 'n cubed minus n is divisible by 6' for n up to a million and finds no failure. Is it proved?

    Show answer

    No; it is strong evidence. A proof (for example, n cubed minus n = (n - 1)n(n + 1), a product of three consecutive integers) is still needed.

  8. Rewrite 'every student did not submit' in two unambiguous ways.

    Show answer

    No student submitted; or, not every student submitted.

  9. Why is the word discrete used for this branch of mathematics?

    Show answer

    Because it studies separate, countable objects rather than continuous quantities.

  10. Name two later computing courses that rely on this one and say how.

    Show answer

    CMPUT-204 uses induction and invariants for algorithm correctness; CMPUT-291 uses relations and predicate logic for databases.

Lesson quiz · 5 questions

Score 60% or more to complete this lesson.

Take the quiz