Professional Documents
Culture Documents
Discrete Mathematics PDF
Discrete Mathematics PDF
Rafael Pass
Wei-Lung Dustin Tseng
Preface
Discrete mathematics deals with objects that come in discrete bundles, e.g.,
1 or 2 babies. In contrast, continuous mathematics deals with objects that
vary continuously, e.g., 3.42 inches from a wall. Think of digital watches
versus analog watches (ones where the second hand loops around continuously
without stopping).
Why study discrete mathematics in computer science? It does not directly
help us write programs. At the same time, it is the mathematics underlying
almost all of computer science. Here are a few examples:
i
a) Message Routing
b) Social networks
8. Finite automata and regular languages
a) Compilers
Contents iii
3 Number Theory 37
3.1 Divisibility . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
3.2 Modular Arithmetic . . . . . . . . . . . . . . . . . . . . . . . . 41
3.3 Primes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
3.4 The Euler Function . . . . . . . . . . . . . . . . . . . . . . . 52
3.5 Public-Key Cryptosystems and RSA . . . . . . . . . . . . . . . 56
4 Counting 61
4.1 The Product and Sum Rules . . . . . . . . . . . . . . . . . . . 61
4.2 Permutations and Combinations . . . . . . . . . . . . . . . . . 63
4.3 Combinatorial Identities . . . . . . . . . . . . . . . . . . . . . . 65
4.4 Inclusion-Exclusion Principle . . . . . . . . . . . . . . . . . . . 69
4.5 Pigeonhole Principle . . . . . . . . . . . . . . . . . . . . . . . . 72
5 Probability 73
iii
5.1 Probability Spaces . . . . . . . . . . . . . . . . . . . . . . . . . 73
5.2 Conditional Probability and Independence . . . . . . . . . . . . 77
5.3 Random Variables . . . . . . . . . . . . . . . . . . . . . . . . . 85
5.4 Expectatation . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
5.5 Variance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92
6 Logic 95
6.1 Propositional Logic . . . . . . . . . . . . . . . . . . . . . . . . . 95
6.2 Logical Inference . . . . . . . . . . . . . . . . . . . . . . . . . . 100
6.3 First Order Logic . . . . . . . . . . . . . . . . . . . . . . . . . . 105
6.4 Applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108
7 Graphs 109
7.1 Graph Isomorphism . . . . . . . . . . . . . . . . . . . . . . . . 112
7.2 Paths and Cycles . . . . . . . . . . . . . . . . . . . . . . . . . . 115
7.3 Graph Coloring . . . . . . . . . . . . . . . . . . . . . . . . . . . 120
7.4 Random Graphs [Optional] . . . . . . . . . . . . . . . . . . . . 122
1.1 Sets
A set is one of the most fundamental object in mathematics.
Example 1.2. The following notations all refer to the same set:
The last example read as the set of all x such that x is an integer between 1
and 2 (inclusive).
We will encounter the following sets and notations throughout the course:
1
2 sets, functions and relations
Given a collection of objects (a set), we may want to know how large is the
collection:
Given two collections of objects (two sets), we may want to know if they
are equal, or if one collection contains the other. These notions are formalized
as set equality and subsets:
Definition 1.5 (Set equality). Two sets S and T are equal, written as S = T ,
if S and T contains exactly the same elements, i.e., for every x, x S x T .
Example 1.7.
Definition 1.8 (Set operations). Given sets S and T , we define the following
operations:
1.1. SETS 3
Difference. S T = {x | x S, x
/ T }, set of elements in S but not T .
Example 1.9. Let S = {1, 2, 3}, T = {3, 4}, V = {a, b}. Then:
Some set operations can be visualized using Venn diagrams. See Figure
1.1. To give an example of working with these set operations, consider the
following set identity.
Proof. We can visualize the set identity using Venn diagrams (see Figure 1.1b
and 1.1c). To formally prove the identity, we will show both of the following:
S (S T ) (S T ) (1.1)
(S T ) (S T ) S (1.2)
To prove (1.1), consider any element x S. Either x T or x
/ T.
If x S T , then x S
4 sets, functions and relations
U U
S T S T
(a) S T (b) S T
U U
S T S T
(c) S T (d) S
S T
If x S T , then x S.
In computer science, we frequently use the following additional notation
(these notation can be viewed as short hands):
Definition 1.11. Given a set S and a natural number n N,
S n is the set of length n strings (equivalently n-tuples) with alphabet
S. Formally we define it as the product of n copies of S (i.e., S S
S).
S is the set of finite length strings with alphabet S. Formally we
define it as the union of S 0 S 1 S 2 , where S 0 is a set that
contains only one element: the empty string (or the empty tuple ()).
1.2. RELATIONS 5
Commonly seen set includes {0, 1}n as the set of n-bit strings, and {0, 1}
as the set of finite length bit strings. Also observe that |[n]| = n.
Before we end this section, let us revisit our informal definition of sets: an
unordered collection of objects. In 1901, Russel came up with the following
set, known as Russels paradox1 :
S = {x | x
/ x}
That is, S is the set of all sets that dont contain themselves as an element.
This might seem like a natural collection, but is S S? Its not hard to
see that S S S / S. The conclusion today is that S is not a good
collection of objects; it is not a set.
So how will know if {x | x satisfies some condition} is a set? Formally, sets
can be defined axiomatically, where only collections constructed from a careful
list of rules are considered sets. This is outside the scope of this course. We will
take a short cut, and restrict our attention to a well-behaved universe. Let E
be all the objects that we are interested in (numbers, letters, etc.), and let U =
E P(E) P(P(E)), i.e., E, subsets of E and subsets of subsets of E. In fact,
we may extend U with three power set operations, or indeed any finite number
of power set operations. Then, S = {x | x U and some condition holds} is
always a set.
1.2 Relations
Definition 1.12 (Relations). A relation on sets S and T is a subset of S T .
A relation on a single set S is a subset of S S.
Example 1.15.
R is transitive iff in its graph, for any three nodes x, y and z such that
there is an edge from x to y and from y to z, there exist an edge from x
to z.
Proof. The proofs of the first three parts follow directly from the definitions.
The proof of the last bullet relies on induction; we will revisit it later.
Example 1.19. Let R = {(1, 2), (2, 3), (1, 4)} be a relation (say on set Z).
Then (1, 3) R (since (1, 2), (2, 3) R), but (2, 4)
/ R . See Figure 1.2.
Equivalence relations capture the every day notion of being the same or
equal.
1.3. FUNCTIONS 7
2 2
1 3 1 3
4 4
(a) The relation R = {(1, 2), (2, 3), (1, 4)} (b) The relation R , transitive closure of
R
1.3 Functions
Definition 1.23. A function f : S T is a mapping from elements in set
S to elements in set T . Formally, f is a relation on S and T such that for each
s S, there exists a unique t T such that (s, t) R. S is the domain of f ,
and T is the range of f . {y | y = f (x) for some x S} is the image of f .
Example 1.25.
f : N N, f (x) = 2x is injective.
8 sets, functions and relations
f : R+ R+ , f (x) = x2 is injective.
f : R R, f (x) = x2 is not injective since (x)2 = x2 .
Example 1.27.
To intuitively justify Definition 1.30, see Figure 1.3. The next theorem
shows that this definition of cardinality corresponds well with our intuition
for size: if both sets are at least as large as the other, then they have the same
cardinality.
1.4. SET CARDINALITY, REVISITED 9
X Y X Y
(a) An injective function from X to(b) A surjective function from X to
Y. Y.
X Y
(c) A bijective function from X to Y .
Implicitly, we have f (1) = 1/1, f (2) = 1/2, f (3) = 2/1, etc. Clearly, f is a
surjection. See Figure 1.4 for an illustration of f .
Figure 1.4: An infinite table containing all positive rational numbers (with
repetition). The red arrow represents how f traverses this tablehow we
count the rationals.
Now consider s = (1 d11 , 1 d22 , 1 d33 , . . . ), i.e., we are taking the diagonal
of the above table, and flipping all the digits. Then for any n, s is different
from sn in the nth digit. This contradicts the fact that f is a bijection.
Theorem 1.36. The real interval [0, 1] (the set of real numbers between 0 and
1, inclusive) is uncountable.
Proof. We will show that |[0, 1]| |S|, where S is the same set as in the
proof of Theorem 1.35. Treat each s = (d1 , d2 , . . . ) S as the real number
between 0 and 1 with the binary expansion 0.d1 d2 . Note that this does
not establish a bijection; some real numbers have two binary expansions, e.g.,
0.1 = 0.0111 (similarly, in decimal expansion, we have 0.1 = 0.0999 2 ).
We may overcome this annoyance in two ways:
Since each real number can have at most two decimal representations
(most only have one), we can easily extend the above argument to show
that |S| |[0, 2]| (i.e., map [0, 1] to one representation, and [1, 2] to the
other). It remains to show that |[0, 1]| = |[0, 2]| (can you think of a
bijection here?).
The Continuum Hypothesis states that no such set exists. Godel and
Cohen together showed (in 1940 and 1963) that this can neither be proved
nor disproved using the standard axioms underlying mathematics (we will
talk more about axioms when we get to logic).
Chapter 2
13
14 proofs and induction
In their simplest forms, it may seems that a direct proof, a proof by con-
trapositive, and a proof and contradiction may just be restatements of each
other; indeed, one can always phrase a direct proof or a proof by contrapositive
as a proof by contradiction (can you see how?). In more complicated proofs,
however, choosing the right proof technique sometimes simplify or improve
the aesthetics of a proof. Below is an interesting use of proof by contradiction.
Theorem 2.3. 2 is irrational.
Proof by contradiction. Assume for contradiction that 2 is rational. Then
there exists integers p and q, with no common divisors, such that 2 = p/q
(i.e., the reduced fraction). Squaring both sides, we have:
p2
2= 2q 2 = p2
q2
This means p2 is even, and by Claim 2.2 p is even as well. Let us replace p by
2k. The expression becomes:
2q 2 = (2k)2 = 4k 2 q 2 = 2k 2
This time, we conclude that q 2 is even, and so q is even as well. But this leads
to a contradiction, since p and q now shares a common factor of 2.
We end the section with the (simplest form of the) AM-GM inequality.
Note that the proof Theorem 2.4 can be easily turned into a direct proof;
the proof of Theorem 2.3, on the other hand, cannot.
Proof by cases. There are only 6 different values of n. Lets try them all:
n (n + 1)2 2n
0 1 1
1 4 2
2 9 4
3 16 8
4 25 16
5 36 32
When presenting a proof by cases, make sure that all cases are covered! For
some theorems, we only need to construct one case that satisfy the theorem
statement.
Claim 2.7. Show that there exists some n such that (n + 1)2 2n .
16 proofs and induction
Proof by example. n = 6.
The next proof does not explicitly construct the example asked by the
theorem, but proves that such an example exists anyways. These type of
proofs (among others) are non-constructive.
Theorem 2.9. There exists irrational numbers x and y such that xy is ratio-
nal.
Non-constructive proof of existence. We know 2 is irrational from Theorem
2
2.3. Let z = 2 .
If z is rational, then we are done (x = y = 2).
2
If z is irrational, then take x = z = 2 , and y = 2. Then:
y
2 2 2 2 2
x =( 2 ) = 2 = 2 =2
Theorem 2.10. Suppose the game of Chomp is played with rectangular grid
strictly larger than 1 1. Player 1 (the first player) has a winning strategy.
Proof. Consider following first move for player 1: eat the lower right most
block. We have two cases1 :
1
Here we use the well-known fact of 2-player, deterministic, finite-move games without
ties: any move is either a winning move (i.e., there is a strategy following this move that
forces a win), or allows the opponent to follow up with a winning move. See Theorem 2.14
later for a proof of this fact.
2.3. INDUCTION 17
Case 1: There is a winning strategy for player 1 starting with this move.
In this case we are done.
Case 2: There is no winning strategy for player 1 starting with this move.
In this case there is a winning strategy for player 2 following this move.
But this winning strategy for player 2 is also a valid winning strategy
for players 1, since the next move made by player 2 can be mimicked by
player 1 (here we need the fact that the game is symmetric between the
players).
While we have just shown that Player 1 can always win in a game of
Chomp, no constructive strategy for Player 1 has been found for general rect-
angular grids (i.e., you cannot buy a strategy guide in store that tells you how
to win Chomp). For a few specific cases though, we do know good strategies
for Player 1. E.g., given a n n square grid, Player 1 starts by removing a
n 1 n 1 (unique) block, leaving an L-shaped piece of chocolate with two
arms; thereafter, Player 1 simply mirrors Player 2s move, i.e., whenever
Player 2 takes a bite from one of the arms, Player 1 takes the same bite on
the other arm.
A our last example, consider tilling a 8 8 chess board with dominoes
(2 1 pieces), i.e., the whole board should be covered by dominoes without
any dominoes over lapping each other or sticking out.
2.3 Induction
We start with the most basic form of induction: induction over the natural
numbers. Suppose we want to show that a statement is true for all natural
18 proofs and induction
1. First prove that the statement is true for n = 1. This is called the base
case.
2. Next prove that whenever the statement is true for case n, then it is also
true for case n + 1. This is called the inductive step.
The base case shows that the statement is true for n = 1. Then, by repeatedly
applying the inductive step, we see that the statement is true for n = 2, and
then n = 3, and then n = 4, 5, . . . ; we just covered all the natural numbers!
Think of pushing over a long line of dominoes. The induction step is just like
setting up the dominoes; we make sure that if a domino falls, so will the next
one. The base case is then analogous to pushing down the first domino. The
result? All the dominoes fall.
Follow these steps to write an inductive proof:
2. Show that P (base) is true for some appropriate base case. Usually base
is 0 or 1.
3. Show that the inductive step is true, i.e., assume P (n) holds and prove
that P (n + 1) holds as well.
Viola, we have just shown that P (n) holds for all n base. Note that the
base case does not always have to be 0 or 1; we can start by showing that
something is P (n) is true for n = 5; this combined with the inductive step
shows that P (n) is true for all n 5. Lets put our new found power of
inductive proofs to the test!
Proof. Define our induction hypothesis P (n) to be true if for every finite set
S of cardinality |S| = n, |P(S)| = 2n .
Base case: P (0) is true since the only finite set of size 0 is the empty set
, and the power set of the empty set, P() = {}, has cardinality 1.
Inductive Step: Assume P (n) is true; we wish to show that P (n + 1)
is true as well. Consider a finite set S of cardinality n + 1. Pick an element
e S, and consider S 0 = S {e}. By the induction hypothesis, |P(S 0 )| = 2n .
Now consider P(S). Observe that a set in P(S) either contains e or not;
furthermore, there is a one-to-one correspondence between the sets containing
e and the sets not containing e (can you think of the bijection?). We have just
partitioned P(S) into two equal cardinality subsets, one of which is P(S 0 ).
Therefore |P(S)| = 2|P(S)| = 2n+1 .
Claim 2.13. The following two properties of graphs are equivalent (recall that
these are the definitions of transitivity on the graph of a relation):
1. For any three nodes x, y and z such that there is an edge from x to y
and from y to z, there exist an edge from x to z.
2. Whenever there is a path from node x to node y, there is also a direct
edge from x to y.
z be the first node after x on the path. We now have a path of length n from
node z to y, and by the induction hypothesis, a direct edge from z to y. Now
that we have a directly edge from x to z and from z to y, property 1 implies
that there is a direct edge from x to y.
If all these games have a winning strategy for player 24 , then no matter
what move player 1 plays, player 2 has a winning strategy
If one these games have a winning strategy for player 1, then player 1
has a winning strategy (by making the corresponding first move).
In the next example, induction is used to prove only a subset of the theo-
rem to give us a jump start; the theorem can then be completed using other
techniques.
3
By deterministic, we mean the game has no randomness and depends on only on player
moves (e.g., not backgammon). By finite, we mean the game is always ends in some prede-
termined fix number of moves; in chess, even though there are infinite sequences of moves
that avoid both checkmates and stalemates, many draw rules (e.g., cannot have more than
100 consecutive moves without captures or pawn moves) ensures that chess is a finite game.
By perfect information, we mean that both players knows each others past moves (e.g., no
fog of war).
4
By this we mean the player 1 of the n-move game (the next player to move) has a
winning strategy
2.3. INDUCTION 21
n n
!1/n
1X Y
AM(x1 , . . . , xn ) = xi GM(x1 , . . . , xn ) = xi
n
i=1 i=1
Let us first prove the AM-GM inequality for values of n = 2k . Define our
induction hypothesis P (k) to be true if AM-GM holds for n = 2k .
Base case: P (0) (i.e., n = 1) trivially holds, and P (1) (i.e., n = 2) was
shown in Theorem 2.4.
Inductive Step: Assume P (k) is true; we wish to show that P (k + 1) is
true as well. Given a sequence of length 2k+1 , X ~ = (x1 , .., x2k+1 ), we split it
~ k ~
into two sequences X1 = (x1 , . . . , x2 ), X2 = (x2k +1 , x2k +2 , . . . , x2k+1 ). Then:
~ = 1 (AM(X
AM(X) ~ 1 ) + AM(X ~ 2 ))
2
1 ~ 1 ) + GM(X ~ 2 ))
(GM(X by the induction hypothesis P (k)
2
= AM(GM(X ~ 1 ), GM(X ~ 2 ))
GM(GM(X ~ 1 ), GM(X ~ 2 )) by Theorem 2.4, i.e., P (1)
1k 1k 1/2
2k
Y 2 k+1
2Y 2
= xi xi
i=1 i=2k +1
1
k+1
2Y 2k+1
= xi ~
= GM(X)
i=1
We are now ready to show the AM-GM inequality for sequences of all
lengths. Given a sequence X ~ = (x1 , . . . , xn ) where n is not a power of 2,
find the smallest k such that 2k > n. Let = AM(X), ~ and consider a new
sequence
1/2k
Y2k
~ 0 ) = GM(X
AM(X ~ 0 ) = xi
i=1
2k n
k k n
Y Y
2 xi = xi 2
i=1 i=1
Yn
n xi
i=1
n
!1/n
Y
xi ~
= GM(X)
i=1
~
This finishes our proof (recalling that = AM(X)).
Note that for the inductive proof in Theorem 2.15, we needed to show both
base cases P (0) and P (1) to avoid circular arguments, since the inductive step
relies on P (1) to be true.
A common technique in inductive proofs is to define a stronger induction
hypothesis than is needed by the theorem. A stronger induction hypothesis
P (n) sometimes make the induction step simpler, since we would start each
induction step with a stronger premise. As an example, consider the game
of coins on the table. The game is played on a round table between two
players. The players take turns putting on one penny at a time onto the table,
without overlapping with previous pennies; the first player who cannot add
another coin losses.
Theorem 2.16. The first player has a winning strategy in the game of coins
on the table.
Proof. Consider the following strategy for player 1 (the first player). Start
first by putting a penny centered on the table, and in all subsequent moves,
simply mirror player 2s last move (i.e., place a penny diagonally opposite of
player 2s last penny). We prove by induction that player 1 can always put
down a coin, and therefore will win eventually (when the table runs out of
space).
Define the induction hypothesis P (n) to be true if on the nth move of player
1, player 1 can put down a penny according to its strategy, and leave the table
symmetric about the centre (i.e., looks the same if rotated 180 degrees).
2.3. INDUCTION 23
Base case: P (1) holds since player 1 can always start by putting one
penny at the centre of the table, leaving the table symmetric.
Inductive Step: Assume P (n) is true; we wish to show that P (n + 1) is
true as well. By the induction hypothesis, after player 1s nth move, the table
is symmetric. Therefore, if player 2 now puts down a penny, the diagonally
opposite spot must be free of pennies, allowing player 1 to set down a penny as
well. Moreover, after player 1s move, the table is back to being symmetric.
The Towers of Hanoi is a puzzle game where there is threes poles, and a
number of increasingly larger rings that are originally all stacked in order of
size on the first pole, largest at the bottom. The goal of the puzzle is to move
all the rings to another pole (pole 2 or pole 3), with the rule that:
You may only move one ring a time, and it must be the top most ring
in one of the three potential stacks.
Proof. Define the induction hypothesis P (n) to be true if the theorem state-
ment is true for n rings.
Base case: P (1) is clearly true. Just move the ring.
Inductive Step: Assume P (n) is true; we wish to show that P (n + 1)
is true as well. Number the rings 1 to n + 1, from smallest to largest (top to
bottom on the original stack). First move rings 1 to n from pole 1 to pole
2; this takes 2n 1 steps by the induction hypothesis P (n). Now move ring
n + 1 from pole 1 to pole 3. Finally, move rings 1 to n from pole 2 to pole 3;
again, this takes 2n 1 steps by the induction hypothesis P (n). In total we
have used (2n 1) + 1 + (2n 1) = 2n+1 1 moves. (Convince yourself that
this recursive definition of moves will never violate the rule that no ring may
be placed on top of a smaller ring.)
Legends say that such a puzzle was found in a temple with n = 64 rings, left for
the priests to solve. With our solution, that would require 264 1 1.8 1019
moves. Is our solution just silly and takes too many moves?
Proof. Define the induction hypothesis P (n) to be true if the theorem state-
ment is true for n rings.
Base case: P (1) is clearly true. You need to move the ring.
Inductive Step: Assume P (n) is true; we wish to show that P (n + 1) is
true as well. Again we number the rings 1 to n + 1, from smallest to largest
(top to bottom on the original stack). Consider ring n + 1. It needs to be
moved at some point. Without loss of generality, assume its final destination
is pole 3. Let the k th move be the first move where ring n + 1 is moved away
from pole 1 (to pole 2 or 3), and let the k 0th move be the last move where ring
n + 1 is moved to pole 3 (away from pole 1 to pole 2),
Before performing move k, all n other rings must first be moved to the
remaining free pole (pole 3 or 2); by the induction hypothesis P (n), 2n 1
steps are required before move k. Similarly, after performing move k, all n
other rings must be on the remaining free pole (pole 2 or 1); by the induction
hypothesis P (n), 2n 1 steps are required after move k 0 to complete the puzzle.
In the best case where k = k 0 (i.e., they are the same move), we still need at
least (2n 1) + 1 + (2n 1) = 2n+1 1 moves.
Strong Induction
Taking the dominoes analogy one step further, a large domino may require
the combined weight of all the previous toppling over before it topples over as
well. The mathematical equivalent of this idea is strong induction. To prove
that a statement P (n) is true for (a subset of) positive integers, the basic idea
is:
1. First prove that P (n) is true for some base values of n (e.g., n = 1).
These are the base cases.
How many base cases do we need? It roughly depends on the following factors:
What is the theorem? Just like basic induction, if we only need P (n) to
be true for n 5, then we dont need base cases n < 5.
Claim 2.19. Suppose we have an unlimited supply of 3 cent and 5 cent coins.
Then we can pay any amount 8 cents.
Proof. Let P (n) be the true if we can indeed form n cents with 3 cent and 5
cent coins.
Base case: P (8) is true since 3 + 5 = 8.
Inductive Step: Assume P (k) is true for 8 k n; we wish to show
that P (n + 1) is true as well. This seems easy; if P (n 2) is true, then adding
another 3 cent coin gives us P (n + 1). But the induction hypothesis doesnt
necessarily say P (n 2) is true! For (n + 1) 11, the induction hypothesis
does apply (since n 2 8). For n + 1 = 9 or 10, we have to do more work.
Additional base cases: P (9) is true since 3 + 3 + 3 = 9, and P (10) is
true since 5 + 5 = 10.
6
Another example is to revisit Claim 2.19. If we use the same proof to show that P (n) is
true for all n 3, without the additional base cases, the proof will be seemingly correct.
What is the obvious contradiction?
7
Hint: Can you trace the argument when n = 2?
26 proofs and induction
Recurrence Relations
When an inductive definition generates a sequence (e.g., the factorial sequence
is 1, 1, 2, 6, 24, . . . ), we call the definition a recurrence relation. We can gen-
eralize inductive definitions and recurrence relations in a way much like we
generalize inductive proofs with strong induction. For example, consider a
sequence defined by:
a0 = 1; a1 = 2; an = 4an1 4an2
According to the definition, the next few terms in the sequence will be
a2 = 4; a3 = 8
At this point, the sequence looks suspiciously as if an = 2n . Lets prove this
by induction!
Proof. Define P (n) to be true if an = 2n .
Base case: P (0) and P (1) are true since a0 = 1 = 20 , a1 = 2 = 21 .
Inductive Step: Assume P (k) is true for 0 k n; we wish to show
that P (n + 1) is true as well for n + 1 2. We have
an+1 = 4an 4an1
= 4 2n 4 2n1 by P (n) and P (n 1)
= 2n+2 2n+1 = 2n+1
This is exactly P (n + 1).
2.4. INDUCTIVE DEFINITIONS 27
Remember that it is very important to check the all the base cases (espe-
cially since this proof uses strong induction). Let us consider another example:
b0 = 1; b1 = 1; bn = 4bn1 3bn2
From the recurrence part of the definition, its looks like the sequence (bn )n
will eventually out grow the sequence (an )n . Based only on this intuition, let
us conjecture that bn = 3n .
Wow! Was that a lucky guess or what. Let us actually compute a few
terms of (bn )n to make sure. . .
b2 = 4b1 3b0 = 4 3 = 1,
b3 = 4b2 3b1 = 4 3 = 1,
..
. /
Looks like in fact, bn = 1 for all n (as an exercise, prove this by induction).
What went wrong with our earlier proof? Note that P (n 1) is only well
defined if n 1, so the inductive step does not work when we try to show
P (1) (when n = 0). As a result we need an extra base case to handle P (1); a
simple check shows that it is just not true: b1 = 1 6= 31 = 3. (On the other
hand, if we define b00 = 1, b01 = 3, and b0n = 4b0n1 3b0n2 , then we can recycle
our faulty proof and show that b0n = 3n ).
In the examples so far, we guessed at a closed form formula for the se-
quences (an )n and (bn )n , and then proved that our guesses were correct using
induction. For certain recurrence relations, there are direct methods for com-
puting a closed form formula of the sequence.
an+1 = c1 an + c2 an1
= c1 rn + c2 rn1 by P (n 1) and P (n)
n1
=r (c1 r + c2 )
n1
=r r2 since r is a root of f (x)
n+1
=r
Recall that there are two distinct roots, r1 and r2 , so we actually have two
sequences that satisfy the recurrence relation (under proper base cases). In
fact, because the recurrence relation is linear (an depends linearly on an1 and
an2 ), and homogeneous (there is no constant term in the recurrence relation),
any sequence of the form an = r1n + r2n will satisfy the recurrence relation;
(this can be shown using a similar inductive step as above).
Finally, does sequences of the form an = r1n + r2n cover all possible base
cases? The answer is yes. Given any base case a0 = a0 , a1 = a1 , we can solve
for the unique value of and using the linear system:
a0 = r10 + r20 = +
a1 = r11 + r21 = r1 + r2
The studious reader should check that this linear system always has a unique
solution (say, by checking that the determinant of the system is non-zero).
In the case that f (x) has duplicate roots, say when a root r has multiplicity m,
in order to still have a total of k distinct sequences, we associate the following
m sequences with r:
( r0 , r1 , r2 , . . . , rn , . . . )
( 0 r0 , 1 r1 , 2 r2 , . . . , nrn , . . . )
( 02 r0 , 12 r 1 , 22 r 2 , . . . , n2 rn , . . . )
..
.
( 0m1 r0 , 1m1 r1 , 2m1 r2 , . . . , nm1 rn , . . . )
For example, if f (x) has degree 2 and has a unique root r with multiplicity 2,
then the general form solution to the recurrence is
an = rn + nrn
We omit the proof of this general construction. Interestingly, the same tech-
nique is used in many other branches of mathematics (for example, to solve
linear ordinary differential equations).
As an example, let us derive a closed form expression to the famous Fi-
bonacci numbers.
f0 = 0; f1 = 1; fn = fn1 + fn2
Then
!n !n
1 1+ 5 1 1 5
fn = (2.1)
5 2 5 2
Proof. It is probably hard to guess (2.1); we will derive it from scratch. The
characteristic polynomial here is f (x) = x2 (x + 1), which has roots
1+ 5 1 5
,
2 2
This means the Fibonacci sequence can be expressed as
!n !n
1+ 5 1 5
fn = +
2 2
30 proofs and induction
Figure 2.1: Approximating the golden ratio with rectangles whose side lengths
are consecutive elements of the Fibonacci sequence. Do the larger rectangles
look more pleasing than the smaller rectangles to you?
0=+
! !
1+ 5 1 5
1= +
2 2
which solves to = 1/ 5, = 1/ 5.
because the other term approaches zero. This in term implies that
fn+1 1+ 5
lim =
n fn 2
which is the golden ratio. It is widely believed that a rectangle whose ratio
(length divided by width) is golden is pleasing to the eye; as a result, the
golden ratio can be found in many artworks and architectures throughout
history.
2.5. FUN TIDBITS 31
We then conclude that a googol (10100 ) grains of sand is not a heap of sand
(this is more than the number of atoms in the observable universe by some
estimates). What went wrong? The base case and the inductive step is per-
fectly valid! There are many solutions to this paradox, one of which is to
blame it on the vagueness of the word heap; the notion of vagueness is itself
a topic of interest in philosophy.
Alice and Bob to quote is $2. Would you quote $2 (and do you think you are
rational)?
Claim 2.22. All the muddy children says yes in the nth round of questioning
(and not earlier) if and only if there are n muddy children.
Proof Sketch. Since we have not formally defined the framework of knowledge,
we are constrained to an informal proof sketch. Let P (n) be true if the claim
is true for n muddy children.
Base case: We start by showing P (1). If there is only one child that is
muddy, the child sees that everyone else is clean, and can immediately deduces
that he/she must be muddy (in order for there to be someone muddy in the
room). On the other hand, if there are 2 or more muddy children, then all
the muddy children see at least another muddy child, and cannot tell apart
whether some kids are muddy refer to them or the other muddy children in
the room.
Inductive Step: Assume P (k) is true for 0 k n; we wish to show
P (n + 1). Suppose there are exactly n + 1 muddy children. Since there are
more than n muddy children, it follows by the induction hypothesis that that
no one will speak before round n + 1. From the view of the muddy children,
they see n other muddy kids, and know from the start that there are either
n or n + 1 muddy children in total (depending on whether they themselves
are muddy). But, by the induction hypothesis, they know that if there were
n muddy children, then someone would have said yes in round n; since no
one has said anything yet, each muddy child deduces that he/she is indeed
muddy and says yes in round n + 1. Now suppose there are strictly more
than n + 1 muddy children. In this case, everyone sees at least n + 1 muddy
children already. By the induction hypothesis, every children knows from the
2.5. FUN TIDBITS 33
beginning that that no one will speak up in the first n round. Thus in n + 1st
round, they have no more information about who is muddy than when the
father first asked the question, and thus they cannot say yes.
Number Theory
Number theory is the study of numbers (in particular the integers), and is one
of the purest branch of mathematics. Regardless, it has many applications in
computer science, particularly in cryptography, the underlying tools that build
modern services such as secure e-commerce. In this chapter, we will touch on
the very basics of number theory, and put an emphasis on its applications to
cryptography.
3.1 Divisibility
A fundamental relation between two numbers is whether or not one divides
another.
37
38 number theory
Proof. We show only item 1; the other proofs are similar (HW). By definition,
We learn in elementary school that even when integers dont divide evenly,
we can compute the quotient and the remainder.
Theorem 3.5 (Division Algorithm). For any a Z and d N+ , there exist
unique q, r Z s.t. a = dq + r and 0 r < d.
q is called the quotient and denoted by q = a div d.
r is called the remainder and denoted by r = a mod d.
For example, dividing 99 by 10 gives a quotient of q = 99 div 10 = 9 and
remainder of r = 99 mod 10 = 9, satisfying 99 = 10(9) + 9 = 10q + r. On
the other hand, dividing 99 by 9 gives a quotient of q = 99 div 9 = 11 and
remainder of r = 99 mod 9 = 0. Again, we have 99 = 11(9) + 0 = 11q + r.
Onwards to proving the theorem.
Proof. Given a Z and d N+ , let q = ba/dc (the greatest integer a/d),
and let r = a dq. By choice of q and r, we have a = dq + r. We also have
0 r < d, because q is the largest integer such that dq a. It remains to
show uniqueness.
Let q 0 , r0 Z be any other pairs of integers satisfying a = dq 0 + r0 and
0 r0 < d. We would have:
dq + r = dq 0 + r0
d (q q 0 ) = r0 r.
This implies that d|(r0 r). But (d1) r0 r d1 (because 0 r, r0 < d),
and the only number divisible by d between (d 1) and d 1 is 0. Therefore
we must have r0 = r, which in turn implies that q 0 = q.
Example 3.7.
Euclid designed one of the first known algorithms in history (for any prob-
lem) to compute the greatest common divisor:
Example 3.8. Lets trace Euclids algorithm on inputs 414 and 662.
Proof. It is enough to show that the common divisors of a and b are the
same as the common divisors of b and (a mod b). If so, then the two pairs of
numbers must also share the same greatest common divisor.
40 number theory
Proof. This can be shown by induction, using Lemma 3.9 as the inductive
step. (What would be the base case?)
Claim 3.11. For every two recursive calls made by EuclidAlg, the first
argument a is halved.
Theorem 3.13 shows that we can give a certificate for the greatest common
divisor. From Corollary 3.4, we already know that any common divisor of a
and b also divides sa + tb. Thus, if we can identify a common divisor d of
a and b, and show that d = sa + tb for some s and t, this demonstrates d
is in fact the greatest common divisor (d = gcd(a, b)). And there is more
good news! This certificate can be produced by slightly modifying Euclids
algorithm (often called the extended Euclids algorithm); this also constitutes
3.2. MODULAR ARITHMETIC 41
as a constructive proof of Theorem 3.13. We omit the proof here and give an
example instead.
Example 3.14. Suppose we want to find s, t Z such that s(252) + t(198) =
gcd(252, 198) = 18. Run Euclids algorithm, but write out the equation a =
bq + r for each recursive call of EuclidAlg.
a b = (q1 q2 )m m|(a b)
42 number theory
For the only if direction, we start by assuming m|(ab). Using the division
algorithm, let a = q1 m + r1 , b = q2 m + r2 with 0 r1 , r2 < m. Because
m|(a b), we have
m|(q1 m + r1 (q2 m + r2 ))
Since m clearly divides q1 m and q2 m, it follows by Corollary 3.4 that
m|r1 r2
The next theorem shows that addition and multiplication carry over to
the modular world (specifically, addition and multiplication can be computed
before or after computing the remainder).
1. a + c b + d (mod m)
2. ac bd (mod m)
For item 2, using Claim 3.16, we have unique integers r and r0 such that
a = q1 m + r b = q2 m + r
c= q10 m +r 0
d = q20 m + r0
Clever usage of Theorem 3.17 can simplify many modular arithmetic cal-
culations.
3.2. MODULAR ARITHMETIC 43
Example 3.18.
Hashing. The age-old setting that call for hashing is simple. How do we
efficiently retrieve (store/delete) a large number of records? Take for exam-
ple student records, where each record has a unique 10-digit student ID. We
cannot (or do not want) a table of size 1010 to index all the student records
indexed by their ID. The solution? Store the records in an array of size N
where N is a bit bigger than the expected number of students. The record for
student ID is then stored in position h(ID) where h is a hash function that
maps IDs to {1, . . . , N }. One very simple hash-function would be
h(k) = k mod N
If 2 or more errors occur, the errors may cancel out and the check may still
pass; fortunately, more robust solutions exists in the study of error correcting
codes.
Casting out 9s. Observe that a number is congruent to the sum of its digits
modulo 9. (Can you show this? Hint: start by showing 10n 1 (mod 9) for
any n N+ .) The same fact also holds modulo 3. This allows us to check
if the computation is correct by quickly performing the same computation
modulo 9. (Note that incorrect computations might still pass, so this check
only increase our confidence that the computation is correct.)
Choose a modulus m N + ,
a multiplier a 2, 3, . . . , m 1, and
an increment c Zm = {0, 1, . . . , m 1}
(an encryption scheme) so that Alice may scramble her messages to Bob (an
encryption algorithm) in a way that no one except Bob may unscramble it
(a decryption algorithm).
To use a private encryption scheme, Alice and Bob first meet in advance
and run k Gen together to agree on the secret key k. The next time Alice
has a private message m for Bob, she sends c = Enck (m) over the insecure
channel. Once Bob receives the cipher-text c, he decrypts it by running m =
Deck (c) to read the original message.
Proof. Correctness is trivial, since for all alphabets m and all keys k,
Example 3.22 (One-Time Pad). In the one-time pad encryption scheme, the
key is required to be as long as the message. During encryption, the entire key
is used to mask the plain-text, and therefore perfectly hides the plain-text.
Formally, let M = {0, 1}n , K = {0, 1}n , and
Proof. Again correctness is trivial, since for mi {0, 1} and all ki {0, 1},
mi = ((mi + ki ) mod 2 ki ) mod 2 (equivalently, mi = mi ki ki ).
3.3 Primes
Primes are numbers that have the absolute minimum number of divisors; they
are only divisible by themselves and 1. Composite numbers are just numbers
that are not prime. Formally:
Note that the definition of primes and composites exclude the numbers 0
and 1. Also note that, if n is composite, we may assume that there exists
some a such that 1 < a n and a|n. This is because given a divisor d|n
with 1 < d < n, then 1 < n/d < n is also a divisor of n; moreover, one of d or
n/d must be at most n.
48 number theory
Distribution of Primes
How many primes are there? Euclid first showed that there are infinitely many
primes.
Theorem 3.26 (Euclid). There are infinitely many primes.
Proof. Assume the contrary that there exists a finite number of primes p1 , . . . , pn .
Consider q = p1 p2 pn + 1. By assumption, q is not prime. Let a > 1 be the
smallest number that divides q. Then a must be prime (or else it could not
be the smallest, by transitivity of divisibility), i.e., a = pi for some i (since
p1 , . . . , pn are all the primes).
We have pi |q. Since q = p1 p2 pn + 1 and pi clearly divides p1 p2 pn ,
we conclude by Corollary 3.4 that pi |1, a contradiction.
Not only are there infinitely many primes, primes are actually common
(enough).
Theorem 3.27 (Prime Number Theorem). Let (N ) be the number of primes
N . Then
(N )
lim =1
N N/ ln N
We omit the proof, as it is out of the scope of this course. We can interpret
the theorem as follows: there exists (small) constants c1 and c2 such that
c1 N/logN (N ) c2 N/logN
If we consider n-digit numbers, i.e., 0 x < 10n , roughly 10n / log 10n = 10n /n
numbers are prime. In other words, roughly 1/n fraction of n-digit numbers
are prime.
3.3. PRIMES 49
Given that prime numbers are dense (enough), here is a method for finding
a random n-digit prime:
Relative Primality
Primes are numbers that lack divisors. A related notion is relative primality,
where a pair of number lacks common divisors.
sa = 1 tb 1 (mod b)
therefore s = a1 .
50 number theory
Lemma 3.31. If a and b are relatively prime and a|bc, then a|c.
Proof. Because a and b are relatively prime, there exists s and t such that
sa + tb = 1. Multiplying both sides by c gives sac + tbc = c. Since a divides
the left hand side (a divides a and bc), a must also divides the right hand side
(i.e., c).
Proof. We proceed by induction. Let Q P (n) be the statement: For every prime
p, and every sequence a1 , . . . an , if p | ni=1 ai , then there exist some 1 j n
such that p|aj .
Base case: P (1) is trivial (j = 1).
Inductive step: Assuming P (n), we wish Q to show P (n + 1). Consider
some prime p and sequence a1 , .., an+1 s.t. p| n+1 i=1 ai . We split into two cases,
either p | an+1 or gcd(p, an+1 ) = 1 (if the gcd was more than 1 but less than
p, then p would not be a prime).
| an+1 we are immediately done (j = n + 1). Otherwise,
In the case that p Q
by Lemma 3.31, p | ni=1 ai . We can then use the induction hypothesis to
show that there exists 1 j n such that p|aj .
Since 1 < n0 = n/p1 < n, the induction hypothesis shows that the two
factorizations of n0 are actually the same, and so the two factorization
of n are also the same (adding back the terms p1 = qj0 ).
Open Problems
Number theory is a field of study that is rife with (very hard) open problems.
Here is a small sample of open problems regarding primes.
Goldbachs Conjecture, first formulated way back in the 1700s, states
that any positive even integer other than 2 can be expressed as the sum of
two primes. For example 4 = 2 + 2, 6 = 3 + 3, 8 = 3 + 5 and 22 = 5 + 17.
With modern computing power, the conjecture has been verified for all even
integers up to 1017 .
The Twin Prime Conjecture states that there are infinitely pairs of
primes that differ by 2 (called twins). For example, 3 and 5, 5 and 7, 11 and
13 or 41 and 43 are all twin primes. A similar conjecture states that there
are infinitely many safe primes or Sophie-Germain primes pairs of primes
of the form p and 2p + 1 (p is called the Sophie-Germain prime, and 2p + 1 is
called the safe prime). For example, consider 3 and 7, 11 and 23, or 23 and
47. In cryptographic applications, the use of safe primes sometimes provide
more security guarantees.
52 number theory
(n) = n p q + 1 = pq p q + 1 = (p 1)(q 1)
a(n) 1 (mod n)
By Theorem 3.30, X is the set of all numbers that have multiplicative inverses
modulo n; this is useful in the rest of the proof.
We first claim that X = aX (this does indeed hold in the example). We
prove this by showing X aX and aX X.
Knowing aX = X, we have:
Y Y Y
x y ax (mod n)
xX yaX xX
Since each x X has an Q inverse, we can multiply both sides with all those
inverses (i.e., divide by xX s):
Y
1 a (mod n)
xX
If n is not prime, then with some probability, say 1/2, the algorithm
may still output YES incorrectly.
Looking at it from another point of view, if the algorithm ever says n is not
prime, then n is definitely not prime. With such an algorithm, we can ensure
that n is prime with very high probability: run the algorithm 200 times,
and believe n is prime if the output is always YES. If n is prime, we always
correctly conclude that it is indeed prime. If n is composite, then we would
only incorrectly view it as a prime with probability (1/2)200 (which is so small
that is more likely to encounter some sort of hardware error).
How might we design such an algorithm? A first approach, on input n, is to
pick a random number 1 < a < n and output YES if and only if gcd(a, n) = 1.
Certainly if n is prime, the algorithm will always output YES. But if n is not
prime, this algorithm may output YES with much too high probability; in
fact, it outputs YES with probability (n)/n (this can be too large if say
n = pq, and (n) = (p 1)(q 1)).
We can design a similar test relying on Eulers Theorem. On input n, pick a
random 1 < a < n and output YES if and only if an1 1 (mod n). Again, if
n is prime, this test will always output YES. What if n is composite? For most
composite numbers, the test does indeed output YES with sufficiently small
probability. However there are some composites, called Carmichael numbers
or pseudo-primes, on which this test always outputs YES incorrectly (i.e., a
Carmichael number n has the property that for all 1 < a < n, an1 1
(mod n), yet n is not prime).
3.4. THE EULER FUNCTION 55
The takeaway of this section is that primality testing can be done ef-
ficiently, in time polynomial in the length (number of digits) of the input
number n (i.e., in time polynomial in log n).
56 number theory
Correctness of RSA
First and foremost we should verify that all three algorithms, Gen, Enc and
Dec, can be efficiently computed. Gen involves picking two n-bit primes, p and
q, and an exponent e relatively prime to pq; we covered generating random
primes in Section 3.3, and choosing e is simple: just make sure e is not a
multiple of p or q (and a random e would work with very high probability).
Enc and Dec are both modular exponentiations; we covered that in Section 3.4.
Dec additionally requires us to compute d = e1 mod (N ); knowing the
secret-key, which contains the factorization of N , it is easy to compute (N ) =
(p 1)(q 1), and then compute d using the extended GCD algorithm and
Theorem 3.30.
Next, let us verify that decryption is able to recover encrypted messages.
Given a message m satisfying 0 < m < N and gcd(m, N ) = 1, we have:
Dec(Enc(m)) = ((me ) mod N )d mod N
= med mod N
= med mod (N ) mod N by Corollary 3.38
= m1 mod N since d = e1 mod (N )
= m mod N = m
This calculation also shows why the message space is restricted to {m | 0 <
m < N, gcd(m, N ) = 1}: A message m must satisfy gcd(m, N ) = 1 so that we
can apply Eulers Theorem, and m must be in the range 0 < m < N so that
when we recover m mod N , it is actually equal to the original message m.
Security of RSA
Let us informally discuss the security of RSA encryption. What stops Eve
from decrypting Alices messages? The assumption we make is that without
58 number theory
x0 = random seed
xi = ax + c mod M
Padded RSA
We have already discussed why a padded scheme for RSA is necessary for se-
curity. A padded scheme also has another useful feature; it allows us to define
2
In Java M = 248 , so the situation improves a little bit.
3.5. PUBLIC-KEY CRYPTOSYSTEMS AND RSA 59
a message space that does not depend on the choice of the public-key (e.g., it
would be tragic if Alice could not express her love for Bob simply because Bob
chose the wrong key). In real world implementations, designing the padding
scheme is an engineering problem with many practical considerations; here we
give a sample scheme just to illustrate how padding can be done. Given a se-
curity parameter n, a padded RSA public-key encryption scheme can proceed
as follows:
Gen(n) picks two random n-bit primes, p, q > 2n1 , and set N = pq,
and pick a random e such that 1 < e < n, gcd(e, (N )) = 1. The public
key is pk = (N, e), while the secret key is sk = (p, q) (the factorization
of N ). N is called the modulus of the scheme.
RSA signatures
We end the section with another cryptographic application of RSA: digital
signatures. Suppose Alice wants to send Bob a message expressing her love,
I love you, Bob, and Alice is so bold and confident that she is not afraid of
eavesdroppers. However Eve is not just eavesdropping this time, but out to
sabotage the relationship between Alice and Bob. She sees Alices message,
and changes it to I hate you, Bob before it reaches Bob. How can cryptog-
raphy help with this sticky situation? A digital signature allows the sender of
a message to sign it with a signature; when a receiver verifies the signature,
he or she can be sure that the message came from the sender and has not been
tampered.
60 number theory
In the RSA signature scheme, the signer generates keys similar to the RSA
encryption scheme; as usual, the signer keeps the secret-key, and publishes the
public-key. To sign a message m, the signer computes:
m = md mod N
Anyone that receives a message m along with a signature can perform the
following check using the public-key:
?
e mod N = m
The correctness and basic security guarantees of the RSA signature scheme
is the same as the RSA encryption scheme. Just as before though, there are
a few security concerns with the scheme as described.
Consider this attack. By picking the signature first, and computing
m = e anyone can forge a signature, although the message m is most likely
meaningless (what if the attacker gets lucky?). Or suppose Eve collects two
signatures, (m1 , 1 ) and (m2 , 2 ); now she can construct a new signature
(m = m1 m2 mod N, = 1 2 mod N ) (very possible that the new message
m is meaningful). To prevents these two attacks, we modify the signature
scheme to first transform the message using a crazy function H (i.e., m =
H(m)d mod N ).
Another important consideration is how do we sign large messages (e.g.,
lengthy documents)? Certainly we do not want to increase the size of N . If
we apply the same solution as we did for encryption break the message into
chunks and sign each chunk individually then we run into another security
hole. Suppose Alice signed the sentences I love you, Bob and I hate freezing
rain by signing the individual words; then Eve can collect and rearrange these
signatures to produce a signed copy of I hate you, Bob. The solution again
relies on the crazy hash function H: we require H to accept arbitrary large
messages as input, and still output a hash < N . A property that H must
have is collision resistance: it should be hard to find two messages, m1 and
m2 , that hash to the same thing H(m1 ) = H(m2 ) (we wouldnt want I love
you, Bob and I hate you, Bob to share the same signature).
Chapter 4
Counting
Counting is a basic mathematical tool that has uses in the most diverse
circumstances. How much RAM can a 64-bit register address? How many
poker hands form full houses compared to flushes? How many ways can ten
coin tosses end up with four heads? To count, we can always take the time
to enumerate all the possibilities; but even just enumerating all poker hands
is already daunting, let alone all 64-bit addresses. This chapter covers several
techniques that serve as useful short cuts for counting.
Example 4.1. On an 8 8 chess board, how many ways can I place a pawn
and a rook? First I can place the pawn anywhere on the board; there are 64
ways. Then I can place the rook anywhere except where the pawn is; there
are 63 ways. In total, there are 64 63 = 4032 ways.
61
62 counting
Example 4.2. On an 8 8 chess board, how many ways can I place a pawn
and a rook so that the rook does not threaten the pawn? First I can place
the rook anywhere on the board; there are 64 ways. At the point, the rook
takes up on square, and threatens 14 others (7 in its row and 7 in its column).
Therefore I can then place the pawn on any of the 64 14 1 = 49 remaining
squares. In total, there are 64 49 = 3136 ways.
Example 4.4. How many legal configurations are there in the towers of
Hanoi? Each of the n rings can be on one of three poles, giving us 3n config-
urations. Normally we would also need to count the height of a ring relative
to other rings on the same pole, but in the case of the towers of Hanoi, the
rings sharing the same pole must be ordered in a unique fashion: from small
at the top to large at the bottom.
The sum rule is probably even more intuitive than the product rule.
Suppose there are n(A) ways to perform task A, and distinct from these,
there are n(B) ways to perform task B. Then, there are n(A) + n(B) ways
to perform task A or task B. This can generalize to multiple tasks, e.g.,
n(A) + n(B) + n(C) ways to perform task A, B, or C, as long as the distinct
condition holds, e.g., the ways to perform task C are different from the ways
to perform task A or B.
Example 4.5. To fly from Ithaca to Miami you must fly through New York
or Philadelphia. There are 5 such flights a day through New York, and 3 such
flights a day through Philadelphia. How many different flights are there in a
day that can take you from Ithaca to get to Miami? The answer is 5 + 3 = 8.
Example 4.6. How many 4 to 6 digit pin codes are there? By the product
rule, the number of distinct n digit pin codes is 10n (each digit has 10 possi-
bilities). By the sum rule, we have 104 + 105 + 106 number of 4 to 6 digit pin
codes (to state the obvious, we have implicitly used the fact that every 4 digit
pin code is different from every 5 digit pin code).
4.2. PERMUTATIONS AND COMBINATIONS 63
Permutations
Definition 4.7. A permutation of a set A is an ordered arrangement of the
elements in A. An ordered arrangement of just r elements from A is called
an r-permutation of A. For non-negative integers r n, P (n, r) denotes the
number of r-permutations of a set with n elements.
Theorem 4.8.
n!
P (n, r) = n(n 1)(n 2) (n r + 1) = .1
(n r)!
Example 4.9. How many one-to-one functions are there from a set A with
m elements to a set B with n elements? If m > n we know there are no such
one-to-one functions. If m n, then each one-to-one function f from A to
B is a m-permutation of the elements of B: we choose m elements from B
in an ordered manner (e.g., first chosen element is the value of f on the first
element in A). Therefore there are P (n, m) such functions.
Combinations
Let us turn to unordered selections.
1
Recall that 0! = 1.
64 counting
For example, how many ways are there to put two pawns on a 8 8 chess
board? We can select 64 possible squares for the first pawn, and 63 possible
remaining squares for the second pawn. But now we are over counting, e.g.,
choosing squares (b5, c8) is the same as choosing (c8, b5) since the two pawns
are identical. Therefore we divide by 2 to get the correct count: 64 63/2 =
2016. More generally,
Theorem 4.11.
n!
C(n, r) =
(n r)!r!
Proof. Let us express P (n, r) in turns of C(n, r). It must be that P (n, r) =
C(n, r)P (r, r), because to select an r-permutation from n elements, we can
first selected an unordered set of r elements, and then select an ordering of
the r elements. Rearranging the expression gives:
P (n, r) n!/(n r)! n!
C(n, r) = = =
P (r, r) r! (n r)!r!
Example 4.12. How many poker hands (i.e., sets of 5 cards) can be dealt
from a standard deck of 52 cards? Exactly C(52, 5) = 52!/(47!5!).
Example 4.13. How many full houses (3 of a kind and 2 of another) can be
dealt from a standard deck of 52 cards? Recall that we have 13 denominations
(ace to king), and 4 suites (spades, hearts, diamonds and clubs). To count the
number of full houses, we may
Pick 3 cards from this denomination (out of 4 suites): there are C(4, 3) =
4 choices.
Next pick a denomination for the 2 of a kind: there are 12 choices left
(different from the 3 of a kind).
Figure 4.1: Suppose there are 5 balls and 3 urns. Using the delimiter idea,
the first row represents the configuration (1, 3, 1) (1 ball in the first urn, 3
balls in the second , and 1 ball in the third). The second row represents the
configuration (4, 0, 1) (4 balls in the first urn, none in the second, and 1 ball
in the third). In general, we need to choose 2 positions out of 7 as delimiters
(the rest of the positions are the 5 balls).
Example 4.14. How many solutions are there to the equation x+y+z = 100,
if x, y, z N? This is just like having 3 distinguishable urns (x, y and z) and
100 indistinguishable balls, so there are C(102, 2) solutions.
one can also prove these identities by churning out the algebra, but that is
boring. We start with a few simple identities.
Proof. Let us once again count the number of possible subsets of a set of n
elements. We have already seen by induction and by the product rule that
there are 2n such subsets; this is the RHS.
Another way to count is to use the sum rule:
n
X n
X
# of subsets = # of subsets of size k = C(n, k)
k=0 k=0
1 1
1 1
1 1 0 1
2 2 2
1 2 1 = 0 1 2
3 3 3 3
1 3 + 3 1 0 1 2 3
4 4 4 4 4
1 4 6 4 1 0 1 2 3 4
Figure 4.2: Pascals triangle contains the binomial coefficients C(n, k) ordered
as shown in the figure. Each entry in the figure is the sum of the two entries
on top of it (except the entries on the side which are always 1).
Proof. The identity actually gives two ways to count the following problem:
given n people, how many ways are there to pick a committee of any size, and
then pick a chairperson of the committee? The first way to count is:
For committees of size k, there are C(n, k) ways of choosing the com-
mittee, and independently, k ways of choosing a chairperson from the
committee.
n
X
This gives a total of kC(n, k) possibilities; this is the LHS.
k=0
For the remaining n 1 people, each person can either be part of the
committee or not; there are 2n1 possibilities.
Proof. Let M be a set with m elements and N be a set with n elements. Then
the LHS represents the number of possible ways to pick r elements from M
and N together. Equivalently, we can count the same process by splitting into
r cases (the sum rule): let k range from 0 to r, and consider picking r k
elements from M and k elements from M .
The next theorem explains the name binomial coefficients: the combina-
tion function C(n, k) are also the coefficient of powers of the simplest binomial,
(x + y).
Proof. Simply write 2n = (1+1)n and expand using the binomial theorem.
n
X
Corollary 4.23. (1)k+1 C(n, k) = 1.
k=1
4.4. INCLUSION-EXCLUSION PRINCIPLE 69
Example 4.24. How many positive integers 100 are multiples of either 2 or
5? Let A be the set of multiples of 2 and B be the set of multiples of 5. Then
|A| = 50, |B| = 20, and |A B| = 10 (since this is the number of multiples of
10). By the inclusion-exclusion principle, we have 50 + 20 10 = 60 multiples
of either 2 or 5.
70 counting
What if there are more tasks? For three sets, we can still gleam from the
Venn diagram that
|X Y Z| = |X| + |Y | + |Z| |X Y | |X Z| |Y Z| + |X Y Z|
More generally,
Example 4.26. How many onto functions are there from a set A with n
elements to a set B with m n elements? We start by computing the number
of functions that are not onto. Let Ai be the set of functions that miss the ith
element of B (i.e., does not have the ith element of B in its range). m i=1 Ai
is then the set of functions that are not onto. By the inclusion exclusion
principle, we have:
m m
[ X X \
k+1
Ai = (1) Ai
i=1 k=1 I{1,...,m},|I|=k iI
For any k and I with |I| = k, observe that iI Ai is the set of functions that
miss a particular set of k elements, therefore
\
Ai = (m k)n
iI
4.4. INCLUSION-EXCLUSION PRINCIPLE 71
Also observe that there are exactly C(m, k) many different Is of size k. Using
these two facts, we have
[m X m X \
k+1
Ai = (1) Ai
i=1 k=1 I{1,...,m},|I|=k iI
m
X
= (1)k+1 C(m, k)(m k)n
k=1
Finally, to count the number of onto functions, we take all possible functions
(mn many) and subtract that functions that are not onto:
m
X m
X
mn (1)k+1 C(m, k)(m k)n = mn + (1)k C(m, k)(m k)n
k=1 k=1
m
X
= (1)k C(m, k)(m k)n
k=0
number of the second kind, another counting function (similar to C(n, k)) that
is out of the scope of this course.
2
By this we mean hands where at least two cards share the same rank. A slightly more
difficult question (but perhaps more interesting in a casino) is how many hands is better or
equal to a pair? (i.e., a straight does not contain a pair, but is better than a pair.)
72 counting
Proof. Assume the contrary that every pigeon hole contains dn/ke1 < n/k
many pigeons. Then the total number of pigeons among the pigeon holes would
be strictly less than k(n/k) = n, a contradiction.
Probability
73
74 probability
called
P the probability mass function.2 Additionally, f satisfies the property
xS f (x) = 1.
The probability mass function used in the above example has a (popular)
property: it assigns equal probability to all the elements in the sample space.
Proof. Let fPtake on the constant value . First note that 6= 0, because it
would force xS f (x) = 0, violating the definition ofPmass functions.
P Next
note that S cannot be infinite, because it would force xS f (x) = xS =
, again violating the definition of mass functions.
Knowing that S is finite, we can then deduce that:
X X
1= f (x) = = |S|
xS xS
1
|S| =
It follows that the probability of an event E is
X X 1 |E|
Pr[E] = = =
|S| |S|
xE xE
Example 5.6. What is the probability that a random hand of five cards in
poker is a full house? We have previously counted the number of possible five-
card hands and the number of possible full houses (Example 4.12 and 4.13).
Since each hand is equally likely (i.e., we are dealing with an equiprobable
probability space), the probability of a full house is:
Example 5.7. We may have the probability space (N+ , f ) where f (n) = 1/2n .
This corresponds with the following experiment: how many coin tosses does it
take for a head to come up?3 We expect this to be a well-defined probability
space since P
it corresponds to a natural random process. But to make sure, we
verify that nN+ 1/2n = 1.4
Example 5.9. Suppose now we wish to pick the positive integer n with prob-
ability proportional to 1/n. This time we are bound to fail, since the series
1 + 1/2 + 1/3 + diverges (approaches ), and cannot be normalized.
Probabilities
Now that probability spaces are defined, we give a few basic properties of
probability:
Proof. By definition,
X
Pr[A B] = f (x)
xAB
X X
= f (x) + f (x) since A and B are disjoint
xA xB
= Pr[A] + Pr[B]
When events are not disjoint, we instead have the following generalization
of the inclusion-exclusion principle.
Claim 5.12. Given events A and B, Pr[A B] = Pr[A] + Pr[B] Pr[A B].
Similarly, we have
Conditional Probability
Suppose after receiving a random 5-card hand dealt from a standard 52-card
deck, we are told that the hand contains at least a pair (that is, at least
two of the cards have the same rank). How do we calculate the probability
of a full-house given this extra information? Consider the following thought
process:
Start with the original probability space of containing all 5-card hands,
pair or no pair.
Definition 5.14. Let A and B be events, and let Pr[B] 6= 0. The conditional
probability of A, conditioned on B, denoted by Pr[A | B], is defined as
Pr[A B]
Pr[A | B] =
Pr[B]
Pr[A | B] = |A B|/|B|
Example 5.15 (Second Ace Puzzle). Suppose we have a deck of four cards:
{A, 2, A, 2}. After being dealt two random cards, facing down, the
dealer tells us that we have at least one ace in our hand. What is the
probability that our hand has both aces? That is, what is Pr[ two aces |
at least one ace ]?
Because we do not care about the order in which the cards were dealt, we
have an equiprobable space with 6 outcomes:
If we look closely, five of the outcomes contain at least one ace, while only one
outcome has both aces. Therefore Pr[ two aces | at least one ace ] = 1/5.
5.2. CONDITIONAL PROBABILITY AND INDEPENDENCE 79
Now what if the dealer tells us that we have the ace of spades (A) in our
hand? Now Pr[ two aces | has ace of spades ] = 1/3. It might seem strange
that the probability of two aces has gone up; why should finding out the suit
of the ace we have increase our chances? The intuition is that by finding out
the suit of our ace and knowing that the suit is spades, we can eliminate many
more hands that are not two aces.
Example 5.16 (Second-Child Problem). Let us assume that a child is equally
likely to be a boy or a girl. A friend of yours has two children but you dont
know their sexes. Consider the following two cases. A boy walks in the door
and your friend says,
This is my child. (5.4)
Or, a boy walks in the door and your friend says,
This is my older child. (5.5)
What is the probability that both children are boys?
If we order the children by age, we again have a equiprobable probabil-
ity space6 . The four outcomes are { boy-boy, boy-girl, girl-boy, girl-girl }.
Therefore,
Pr[ two boys | (5.4)] = 1/3
Pr[ two boys | (5.5)] = 1/2
Now suppose that we know exactly one of the children plays the cello. If
a boy walks in the door and your friend says,
He is the one who plays the cello.
then we are in same case as (5.5) (instead of ordering by age, we order the
children according to who plays the cello).
One more food for thought. What if we know that at least one of the
children plays the cello? Now what is the probability that both children
are boys, if a boy walks in, and start playing the cello? To calculate this
probability, first we need to enlarge the sample space; each child, in addition
to being a boy or a girl, either plays the cello or does not. Next we need to
specify a probability mass function on this space. This is where we get stuck,
since we need additional information to define the probability mass function.
E.g., what is the probability that both children plays the cello, v.s. only one
child plays the cello?
6
If we do not order the children, then our sample space could be {two boys, one boy
and one girl, two girls}, with probability 1/4, 1/2, and 1/4 respectively. This probability
space is suitable for case (5.4), but not (5.5)
80 probability
Independence
By defining conditional probability, we modeled how the occurrence of one
event can affect the probability of another event. An equally interesting con-
cept is independence, where a set of events do not affect each other.
If there are just two events, A and B, then they are independent if and
only if Pr[A B] = Pr[A] Pr[B]. The following claim gives justification to the
definition of independence.
Claim 5.18. If A and B are independent events and Pr[B] 6= 0, then Pr[A |
B] = Pr[A]. In other words, conditioning on B does not change the probability
of A.
Proof.
The following claim should also hold according to our intuition of inde-
pendence:
Claim 5.19. If A and B are independent events, then A and B are also
independent events. In other words, if A is independent of the occurrence of
B, then it is also independent of the non-occurrence of B.
Proof.
7
A related notion that we do not cover in this class is pair-wise independence. A sequence
of events A1 , . . . , An are pair-wise independent if and only if for every pair of events in the
sequence, Ai1 , Ai2 , we have Pr[Ai1 Ai2 ] = Pr[Ai1 ] Pr[Ai2 ]. Pair-wise independence is
a weaker requirement than (mutual) independence, and is therefore easier to achieve in
applications.
5.2. CONDITIONAL PROBABILITY AND INDEPENDENCE 81
Bayes Rule
Suppose that we have a test against a rare disease that affects only 0.3%
of the population, and that the test is 99% effective (i.e., if a person has the
disease the test says YES with probability 0.99, and otherwise it says NO with
probability 0.99). If a random person in the populous tested positive, what is
the probability that he has the disease? The answer is not 0.99. Indeed, this
is an exercise in conditional probability: what are the chances that a random
person has the rare disease, given the occurrence of the event that he tested
positive?
We start with with some preliminaries.
Claim
S 5.21. Let A1 , . . . , An be disjoint events with non-zero probability such
that i Ai = S (i.e., the events are exhaustive; Pthe events partition the sample
space S). Let B be an event. Then Pr[B] = ni=1 Pr[B | Ai ]P r[Ai ]
Proof. By definition Pr[B | Ai ] = Pr[BAi ]/ Pr[Ai ], and so the RHS evaluates
to
Xn
Pr[B Ai ]
i=1
Since A1 , . . . , An are disjoint it follows that the events B A1 , . . . , B An
are also disjoint. Therefore
n
"n # " n
#
X [ [
Pr[B Ai ] = Pr B Ai = Pr B Ai = Pr [B S] = Pr[B]
i=1 i=1 i=1
82 probability
Theorem 5.22 (Bayes Rule). Let A and B be events with non-zero proba-
bility. Then:
Pr[A | B] Pr[B]
Pr[B | A] =
Pr[A]
Proof. Multiply both sides by Pr[A]. Now by definition of conditional prob,
both sides equal:
Corollary 5.23 (Bayes Rule Expanded). Let A and B be events with non-
zero probability. Then:
Pr[A | B] Pr[B]
Pr[B | A] =
Pr[B] Pr[A | B] + Pr[B] Pr[A | B]
Proof. We apply Claim 5.21, using that B and B are disjoint and B B = S.
We return to our original question of testing for rare diseases. Lets con-
sider the sample space S = {(t, d) | t {0, 1}, d {0, 1}}, where t represents
the outcome of the test on a random person in the populous, and d represents
whether the same person carries the disease or not. Let D be event that a
randomly drawn person has the disease (d = 1), and T be the event that a
randomly drawn person tests positive (t = 1).
We know that Pr[D] = 0.003 (because 0.3% of the population has the dis-
ease). We also know that Pr[T | D] = 0.99 and Pr[T | D] = 0.01 (because the
test is 99% effective). Using Bayes rule, we can now calculate the probability
that a random person, who tested positive, actually has the disease:
Pr[T | D] Pr[D]
Pr[D | T ] =
(Pr[D] Pr[T | D] + Pr[D] Pr[T | D])
.99 .003
= = 0.23
.003 .99 + .997 .01
Notice that 23%, while significant, is a far cry from 99% (the effectiveness
of the test). This final probability can vary if we have a different prior (initial
5.2. CONDITIONAL PROBABILITY AND INDEPENDENCE 83
belief). For example, if a random patient has other medical conditions that
raises the probability of contracting the disease up to 10%, then the final
probability of having the disease, given a positive test, raises to 92%.
Conditional Independence
Bayes rule shows us how to update our beliefs when we receive new infor-
mation. What if we receive multiple signals at once? How do we compute
Pr[A | B1 B2 ]? First we need the notion of conditional independence.
In other words, given that the event A has occurred, then the events B1 , . . . , Bn
are independent.
When there are only two events, B1 and B2 , they are conditionally inde-
pendent given event A if and only if Pr[B1 B2 | A] = Pr[B1 | A] Pr[B2 | A].
The notion of conditional independence is somewhat fickle, illustrated by the
following examples:
a coin at random; let BH be the event that we choose the coin that is
biased towards heads. Next we toss the chosen coin twice; let H1 and
H2 be the event that the first and second coin tosses come up heads,
respectively. Then, given that we chose the coin biased towards heads
(the event BH ), H1 and H2 are independent:
However, H1 and H2 are not independent, since if the first toss came
up heads, it is most likely that we chose the coin that is biased towards
heads, and so the second toss will come up heads as well. Actually
probabilities are:
1 1 1
Pr[H1 ] Pr[H2 ] = = 6= Pr[H1 H2 ] = 0.5(0.992 ) + 0.5(0.012 ) 0.5
2 2 4
Pr[A | B1 B2 ]
Pr[B1 B2 | A] Pr[A]
=
Pr[A] Pr[B1 B2 | A] + Pr[A] Pr[B1 B2 | A]
Pr[B1 | A] Pr[B2 | A] Pr[A]
=
Pr[A] Pr[B1 | A] Pr[B2 | A] + Pr[A] Pr[B1 | A] Pr[B2 | A]
In general, given signals B1 , . . . , Bn that are conditionally independent
given A and conditionally independent given A, we have
" # Q
\ Pr[A] i Pr [Bi | A]
Pr A | Bi = Q Q
i
Pr[A] i Pr [Bi | A] + Pr[A] i Pr Bi | A
5.3. RANDOM VARIABLES 85
5.4 Expectatation
Given a random variable defined on a probability space, what is its average
value? Naturally, we need to weigh things according to the probability that
the random variable takes on each value.
Definition 5.29. Given a random variable X defined over a probability space
(S, f ), we define the expectation of X to be
X X
E[X] = Pr[X = x] x = fX (x) x
x range of X x range of X
Proof.
X
Pr[X = x]g(x)
x range of X
X X
= f (s)g(x)
x range of X s(X=x)
X X
= f (s)g(X(s))
x range of X s(X=x)
X
= f (s)g(X(s)) = E[g(X)]
sS
Example 5.31. Suppose in a game, with probability 1/10 we are paid $10,
and with probability 9/10 we are paid $2. What is our expected payment?
The answer is
1 9
$10 + $2 = $2.80
10 10
Example 5.32. Given a biased coin that ends up heads with probability p,
how many tosses does it take for the coin to show heads, in expectation?
We may consider the state space S = {H, T H, T T H, T T T H, . . . }; these
are possible results of a sequence of coin tosses that ends when we see the first
5.4. EXPECTATATION 89
head. Because each coin toss is independent, we define the probability mass
function to be
the game. After all, except with one chance in a million, you simply lose
a thousand dollars. This example shows how expectation does not capture
all the important features of a random variable, such as how likely does the
random variable end up close to its expectation (in this case, the utility is
either -1000 or two billion, not close to the expectation of 1000 at all).
In other instances, people are risk-seeking. Take yet another game that
takes a dollar to play. This time, with one chance in a billion, the reward is a
million dollars; otherwise there is no reward. The expected utility is
1 1
9
(106 1) + (1 9 )(0 1) = 0.999
10 10
Essentially, to play the game is to throw a dollar away. Would you play the
game? Turns out many people do; this is called a lottery. Many people think
losing a dollar will not change their life at all, but the chance of winning a
million dollars is worth it, even if the chance is tiny. One way to explain this
behavior within the utility framework is to say that perhaps earning or losing
just a dollar is not worth 1 point in utility.
Linearity of Expectation
One nice property of expectation is that the expectation of the sum of random
variables, is the sum of expectations. This can often simplify the calculation
of expectation (or in applications, the estimation of expectation). More gen-
erally,
" n # n
X X
E ai Xi = ai E[Xi ]
i=1 i=1
5.4. EXPECTATATION 91
Proof.
n n
" #
X X X
E ai Xi = f (s) ai Xi (s)
i=1 sS i=1
n
XX
= ai f (s)Xi (s)
sS i=1
Xn X
= ai f (s)Xi (s)
i=1 sS
Xn
= ai E[Xi ]
i=1
Example 5.34. If we make n tosses of a biased coin that ends up heads with
probability p, what is the expected number of heads? Let Xi = 1 if the ith
toss is heads, and Xi = 0 otherwise. Then Xi is an independent Bernoulli
random variable with probability p, and has expectation
E[Xi ] = p 1 + (1 p) 0 = p
Thus if the coin was fair, we would expect (1/2)n, half of the tosses, to be
heads.
Markovs Inequality
The expecting of a non-negative random variable X gives us a (relatively
weak) bound on the probability of X growing too large:
Clearly Y X at all times and so E[Y ] E[X] (easy to verify by the definition
of expectation). Now observe that
E[X] E[Y ] = a Pr[Y = a] + 0 Pr[Y = 0] = a Pr[X a]
Rearranging the terms gives us Markovs inequality.
Example 5.36. Let X be a non-negative random variable (denoting height,
variable pricing, or the number of people in the park, for example), and sup-
pose we know the its expectation E[X]. Then most people are comfortable
with the assumption that X would not exceed one thousand times its expec-
tation, because
E[X] 1
Pr[X 1000 E[X]] =
1000 E[X] 1000
5.5 Variance
Consider the following two random variables:
1. X always take the constant value 1.
2. Y = 0 with probability 1 106 , and Y = 106 with probability 106 .
Both X and Y has expectation 1, but they have very different distributions.
To capture their differences, the variance of a random variable is introduced
to capture how spread out is the random variable away from its expectation.
Definition 5.37. The variance of a random variable X is defined as
Var[X] = E[(X E[X])2 ]
Intuitively, the term (X E[X])2 measures the distance of X to its ex-
pectation. The term is squared to ensure that the distance is always positive
(perhaps we could use absolute value, but it turns out defining variance with
a square gives it much nicer properties).
Example 5.38. Going back to the start of the section, the random variable
X (that takes the constant value 1) has E[X] = 1 and Var[X] = 0 (it is never
different from its mean). The random variable
(
0 w.p. 1 106
Y =
106 w.p. 106
also has expectation E[Y ] = 1, but variance
Var[Y ] = E[(Y E[Y ])2 ] = (1 106 ) (0 1)2 + (106 )(106 1)2 106
5.5. VARIANCE 93
Chebyshevs Inequality
Knowing the variance of a random variable X allows us to bound the proba-
bility of X deviating from its mean.
Theorem 5.42 (Chebyshevs Inequality). Let X be a random variable. Then
Var[X]
Pr [|X E[X]| k]
k2
Proof. Let Y = |X E[X]|. Applying Markovs Inequality to Y 2 , we have
Pr [|X E[X]| k] = Pr[Y k] = Pr[Y 2 k 2 ] because Y 0
E[Y 2] E[(X E[X])2 ] Var[X]
= =
k2 k2 k2
Example 5.43. The variance (more specifically the square root of the vari-
ance) can be used as a ruler to measure how much a random variable X
may deviate from its mean. By convention, let Var[X] = 2 . Then
Var[X] 1
Pr[|X E[X]| n] = 2
n2 2 n
Chapter 6
Logic
Logic will get you from A to B. Imagination will take you everywhere.
Albert Einstein
(P Q) R
95
96 logic
, , , ,
T T F T T T T
T F F F T F F
F T T F T T F
F F T F F T T
Figure 6.1: The truth table definition of the connectives NOT (), AND (),
OR (), implication (), and equivalence ().
Most of the definitions are straightforward. NOT flips a truth value; AND
outputs true iff both inputs are true, OR outputs true iff at least one of the
inputs are true; equivalence outputs true iff both inputs have the same truth
value. Implication () may seem strange at first. is false only if is
true, yet is false. In particular, is true whenever is false, regardless
of what is. An example of this in English might be if pigs fly, then I am the
6.1. PROPOSITIONAL LOGIC 97
president of the United States; this seems like a correct statement regardless
of who says it since pigs dont fly in our world.1
Finally, we denote the truth value of a formula , evaluated on an inter-
pretation I, by [I]. We define [I] inductively:
Given a formula , we call the mapping from interpretations to the truth value
of (i.e., the mapping that takes I to [I]) the truth table of .
At this point, for convenience, we add the symbols T and F as special atoms
that are always true or false, respectively. This does not add anything real
substance to propositional logic since we can always replace T by P P
(which always evaluates to true), and F by P P (which always evaluates
to false).
Equivalence of Formulas
We say that two formulas and are equivalent (denoted ) if for all
interpretations I, they evaluate to the same truth value (equivalently, if and
have the same truth table). How many possible truth tables are there over n
atoms? Because each atom is either true or false, we have 2n interpretations. A
formula can evaluate to true or false on each of the interpretations, resulting in
n
22 possible truth tables (essentially we are counting the number of functions
of the form {0, 1}n {0, 1}).
With such a large count of distinct (not equivalent) formulas, we may
wonder is our propositional language rich enough to capture all of them? The
answer is yes. The following example can be extended to show how AND, OR
and NOT (, and ) can be used to capture any truth table. Suppose we
1
A related notion, counterfactuals, is not captured by propositional implication. In the
sentence if pigs were to fly then they would have wings, the speaker knows that pigs do not
fly, but wish to make a logical conclusion in an imaginary world where pigs do. Formalizing
counterfactuals is still a topic of research in logic.
98 logic
P Q (= P Q)
T T T
T F F
F T T
F F T
We find the rows where is true; for each such row we create an AND formula
that is true iff P and Q takes on the value of that row, and then we OR these
formulas together. That is:
(P Q) (P Q) (P Q)
| {z } | {z } | {z }
first row third row fourth row
This can be simplified to the equivalent formula:
(P Q) (P Q) (P Q) (P Q) P P Q
The equivalence
P Q P Q (6.1)
is a very useful way to think about implication (and a very useful formula for
manipulating logic expressions).
Finally, we remark that we do not need both OR and AND ( and ) to
capture all truth tables. This follows from De Morgans Laws:
( )
(6.2)
( )
P P is unsatisfiable.
P P is valid.
(P Q) (Q P )
(P Q) (Q P )
Proof. The claim essentially follows from definition. If is valid, then [I] =
T for every interpretation I. This means ()[I] = F for every interpretation
I, and so is unsatisfiable. The other direction follows similarly.
2
In complexity jargon, checking if a formula is satisfiable is NP-complete, and finding
an efficient algorithm to determine satisfiability would show that P=NP.
3
In complexity jargon, the unsatisfiability problem is co-NP complete. The major open
problem here is whether or not NP=coNP; that is, whether there exists an efficient way of
convincing someone that a formula is unsatisfiable.
100 logic
Bob carries an umbrella if it is cloudy and the forecast calls for rain.
It is not cloudy.
Can we conclude that Bob is not carrying an umbrella? The answer is no.
Bob may always carry an umbrella around to feel secure (say in Ithaca).
To make sure that we make correct logical deductions in more complex
settings, let us cast the example in the language of propositional logic. Let P
be the atom it is cloudy, Q be the atom the forecast calls for rain, and R
be the atom Bob carries an umbrella. Then we are given two premises:
(P Q) R, P
Can we make the conclusion that R is true? The answer is no, because the
truth assignment P = Q = F, R = T satisfies the premises, but does not satisfy
the conclusion.4 The next definition formalizes proper logical deductions.
Axiom Systems
Checking the validity of a formula is difficult (as we discussed, it has been a
long standing open question). On the other hand, we perform logic reasoning
everyday, in mathematical proofs and in English. An axiom system formalizes
the reasoning tools we use in a syntactic way (i.e., pattern matching and string
manipulations of formulas) so that we may study and eventually automate the
reasoning process.
1
2 This means from the formulas 1 , . . . , n we may infer . We
.. also use the notation 1 , . . . n ` (note that this is different
.
n from the symbol for satisfiability |=).
For example, an axiom system that contains an invalid axiom is not sound,
while a trivial axiom system that contains no axioms or no rules of inference
is trivially incomplete.
Rules of inference. Here are well-known (and sound) rules of inference for
propositional logic:
It is easy to see that all of the above inferences rules preserves validity, i.e.,
the antecedents (premises) entail the conclusion. Therefore an axiom system
using these rules will at least be sound.
5
We have left out the (rather tedious) formal definitions of matching against axioms
or inference rules. This is best explained through examples later in the section.
6.2. LOGICAL INFERENCE 103
C an axiom
C (A C) an axiom
AC Modus Ponens, from line 1 and 2
A Modus Tollens, from line 3 and 1
AB an axiom
A an axiom
B Disjunctive Syllogism, from line 1 and 2
B (C C) an axiom
C C Disjunctive Syllogism, from line 3 and 4
( )
By this we mean any formula that matches against the axiom is assumed
to be true. For example, let P and Q be atoms, then
P (Q P )
(P Q) ((Q P ) (P Q))
are both assumed to be true (in the second example, we substitute = P Q,
= Q P ). To have a sound axiom system, we much start with axioms
that are valid (tautologies); it is not hard to see that the example axiom is
indeed valid.
Simplification: Addition:
Most of the time we also add rules of replacement which allow us to rewrite
formulas into equivalent (and simpler) forms, e.g.,
( ) De Morgans Law
Double negation
6.3. FIRST ORDER LOGIC 105
x Man(x) Mortal(x)
Man(Socrates)
Mortal(Socrates)
Several syntax features of first order logic can be seen above: is one of the
two quantifiers introduced in first order logic; x is a variable; Socrates is a
constant (a particular person); Mortal(x) and Man(x) are predicates.
Formally, an atomic expression is a predicate symbol (e.g., Man(x),
LessThan(x, y)) with the appropriate number of arguments; the arguments
can either be constants (e.g., the number 0, Socrates) or variables (e.g., x,
y and z). A first order formula, similar to propositional logic, is multiple
atomic expressions connected by connectives. The formal recursive definition
goes as follows:
Example 6.13. The following formula says that the binary predicate P is
transitive:
xyz(P (x, y) P (y, z)) P (x, z)
106 logic
Example 6.14. The following formula shows that the constant 1 is a mul-
tiplicative identity (the ternary predicate Mult(x, y, z) is defined to be true if
xy = z):
xy(Mult(1, x, x) Mult(x, 1, x))
Can you extend the formula to enforce that 1 is the unique multiplicative
identity?
Example 6.15. The following formula shows that every number except 0 has
a multiplicative inverse:
Example 6.17. In the following formula (that is not a sentence), the first
occurrence of x is free, and the second one is bound:
yP (x, y) xR(x)
The next formula is a sentence (note that in this case, x captures both
occurrences of x):
yx(P (x, y) R(x))
For example, in the Socrates example, we could have D be the set of all people
(or the set of all living creatures, or the set of all Greeks). An interpretation
I would need to single out Socrates in D, and also specify for each a D,
whether Man(x) and Mortal(x) holds.
Given a first-order sentence , a domain D and an interpretation I = ID
(together (D, I) is called a model), we can define the truth value of , denoted
by [I], recursively:
If has the form x, then [I] is true if and only if for every element
a D, , with free occurrences of x replaced by a, evaluates to true.
If has the form x, then [I] is true if and only if there exists some
element a D such that , with free occurrences of x replaced by a,
evaluates to true.
6.4 Applications
Logic has a wide range of applications in computer science, including program
verification for correctness, process verification for security policies, informa-
tion access control, formal proofs of cryptographic protocols, etc.
In a typical application, we start by specifying of model, a desired prop-
erty in logic, e.g., we want to check that a piece of code does not create
deadlocks. We next describe the system in logic, e.g., the piece of code,
and the logic behind code execution. It then remains to show that our system
satisfies our desired model, using tools in logic; this process is called model
checking. Recently Edmund Clark received the Turing award in 2007 for his
work on hardware verification using model checking. He graduate with his
Ph.D. from Cornell in 1976 with Bob Constable as advisor.
Chapter 7
Graphs
Graphs are simple but extremely useful mathematical objects; they are
ubiquitous in practical applications of computer science. For example:
In a digitalized map, nodes are intersections (or cities), and edges are
roads (or highways). We may have directed edges to capture one-way
streets, and weighted edges to capture distance. This graph is then used
for generation directions (e.g., in GPS units).
On the internet, nodes are web pages, and (directed) edges are links from
one web page to another. This graph can be used to rank the importance
of each web page for search results (e.g., the importance of a web page
can be determined by how many other web pages are pointing to it, and
recursively how important those web pages are).
In a social network, nodes are people, and edges are friendships. Under-
standing social networks is a very hot topic of research. For example,
how does a network achieve six-degrees of separation, where everyone
is approximately 6 friendships away from anyway else? Also known as
the small world phenomena, Watts and Strogatz (from Cornell) pub-
lished the first models of social graphs that have this property, in 1998.
109
110 graphs
Graph Representations
The way a graph is represented by a computer can affect the efficiency of vari-
ous graph algorithms. Since graph algorithms are not a focus of this course, we
instead examine the space efficiency of the different common representations.
Given a graph G = (V, E):
Edge Lists. We may simply have a list of all the edges in E, which implicitly
defines a set of interesting vertices (vertices that have at least one edge
entering or leaving).
If the graph is dense (i.e., has lots of edges), then consider the adjacency
matrix representation. The matrix requires storing O(n2 ) entries, which is
comparable to the space required by adjacency lists or edge lists if the graph
is dense. In return, the matrix allows very efficient lookups of whether an
edge (u, v) exists (by comparison, if adjacency lists are used, we would need
to traverse the whole adjacency list for the vertex u). For sparse graphs,
using adjacency lists or edge lists can result in large savings in the size of the
representation.1
Vertex Degree
The degree of a vertex corresponds to the number of edges coming out or going
into a vertex. This is defined slightly differently for directed and undirected
graphs.
Proof. In a directed graph, each edge contributes once to the in-degree of some
vertex and the out-degree of some, possibly the same, vertex. In an undirected
1
Since the advent of the internet, we now have graphs of unprecedented sizes (e.g., the
graph of social networks such as Facebook, or the graph of web pages). Storing and working
with these graphs are an entirely different science and a hot topic of research backed by both
academic and commercial interests.
112 graphs
graph, each non-looping edge contributes once to the degree of exactly two
vertices, and each self-loop contributes
P twice to the degree of one vertex. In
both cases we conclude that 2|E| = vV deg(v).
Corollary 7.4. In a graph, the number of vertices with an odd degree is even.
Proof. Let A be the set of vertices of even degree, and B = V \ A be the set
of vertices of odd degree. Then by Theorem 7.3,
X X
2|E| = deg(v) + deg(v)
vA vB
P
Since the LHS and the first term of RHS is even, we have that vB deg(v)
is even. In order for a sum of odd numbers to be even, there must be a even
number of terms.
The only difference between G1 and G2 are the names of the vertices; they
are clearly the same graph! On the other hand, the graphs
b b
G1 a H1 a K1 b a c
c c
2 b b
G2 1 H2 a K2 a
3 c c
(a) G1 and G2 are clearly (b) H1 and H2 are clearly (c) Are K1 and K2 isomor-
isomorphic. not isomorphic. phic?
Interactive Proofs
In 1985, Goldwasser, Micali and Rackoff, and independently Babai, found
a work around to prove that two graphs are not isomorphic. The magic is
to add interaction to proofs. Consider a proof system that consists of two
players, a prover P and a verifier V, where the players may communicate
interactively with each other, instead of the prover writing down a single proof.
In general the prover (who comes up with the proof) may not be efficient, but
the verifier (who checks the proof) must be. As with any proof system, we
desire completeness: on input non-isomorphic graphs, the prover P should be
able to convince V of this fact. We also require soundness, but with a slight
relaxation: on input isomorphic graphs, no matter what the prover says to V,
V should reject with very high probability. We present an interactive proof
for graph non-isomorphism in Figure 7.2.
Let us check that the interactive proof in Figure 7.2 is complete and sound.
As of now, given isomorphic graphs, the verifier accepts or rejects with proba-
bility 1/2; this may not fit the description reject with very high probability.
Fortunately, we can amplify this probability by repeating the protocol (say)
100 times, and let the verifier accept if only if b = b0 is all 100 repetitions.
Then by independence, the verifier would accept in the end with probability
at most 1/2100 , and reject with probability at least 1 1/2100 . Note that the
completeness of the protocol is unchanged even after the repetitions.
A walk can always be trimmed in such away that every vertex is visited
at most once, while keeping the same starting and ending vertices.
Example 7.7. The Bacon number of an actor or actress is the shortest path
from the actor or actress to Kevin Bacon on the following graph: the nodes are
actors and actresses, and edges connect people who star together in a movie.
The Erdos number is similarly defined to be the distance of a mathematician
to Paul Erdos on the co-authorship graph.
116 graphs
Figure 7.3: The difference between strong and weak connectivity in a directed
graph.
Connectivity
Definition 7.8. An undirected graph is connected if there exists a path
between any two nodes u, v V (note that a graph containing a single node
v is considered connected via the length 0 path (v)).
To see why, first note that if there are no path between v and u, then of
course the search algorithm will never reach u. On the other hand, assume
that there exists a path between v and u, but for the sake of contradiction,
that the BFS algorithm does not visit u after all the reachable vertices are
visited. Let w be the first node on the path from v to u that is not visited by
BFS (such a node must exists because u is not visited). We know w 6= v since
v is visited right away. Let w1 be the vertex before w on the path from v to
u, which must be visited because w is the first unvisited vertex on the path.
But this gives a contradiction; after BFS visits w1 , it must also visit w since
w is an unvisited neighbor of w1 .4
Now let us use BFS to find the connected components of a graph. Simply
start BFS from any node v; when the graph search ends, all visited vertex form
one connected component. Repeat the BFS on remaining unvisited nodes to
recover additional connected components, until all nodes are visited.
Proof. We prove the theorem for the case of undirected graphs; it generalizes
easily to directed graphs. First observe that if G has a Euler cycle, then of
course G is connected by the cycle. Because every edge is in the cycle, and
each time the cycle visits a vertex it must enter and leave, the degree of each
vertex is even.
To show the converse, we describe an algorithm that builds the Eulerian
cycle assuming connectivity and that each node has even degrees. The algo-
rithm grows the Euler cycle in iterations. Starting from any node v, follow
connected components in directed graphs).
4
This argument can be extended to show that in fact, BFS would traverse a shortest
path from v to u.
5
Originally, Euler was searching for a continuous route that crosses all seven bridges in
the city of Konigsberg exactly once.
7.2. PATHS AND CYCLES 119
any path in the graph without reusing edges (at each node, pick some unused
edge to continue the path). We claim the path must eventually return to v;
this is because the path cannot go on forever, and cannot terminate on any
other vertex u 6= v do to the even degrees constraint: if there is an available
edge into u, there is also an available edge out of u. That is, we now have a
cycle (from v to v). If the cycle uses all edges in G then we are done.
Otherwise, find the first node on the cycle, w, that still has an unused
edge; w must exist since otherwise the cycle would be disconnected from the
part G that still has unused edges. We repeat the algorithm starting from
vertex w, resulting in a cycle from w to w that does not have repeated edges,
and does not use edges in the cycle from v to v. We can then stitch these
two cycles together into a larger cycle:
We can relax the notion of Euler cycles into Euler paths a path that
uses every edge in the graph exactly once.
Corollary 7.12. A undirected graph G = (V, E) has an Euler path, but not
a Euler cycle, if and only if the graph is connected and exactly two nodes has
an odd degree.
Proof. Again it is easy to see that if G has a Euler path that is not a cycle,
then the graph is connected. Moreover, the starting and ending nodes of the
path, and only these two nodes, have an odd degree.
To prove the converse, we reduce the problem into finding an Euler cycle.
Let u, v V be the unique two nodes that have an odd degree. Consider
introducing an extra node w and the edges {u, w}, {v, w}. This modified
graph satisfies the requirements for having a Euler cycle! Once we find the
cycle in the modified graph, simply break the cycle at node w to get a Euler
path from u to v in the original graph.
Here are some easy observations and special cases of graph coloring:
A fully connected graph with n nodes (i.e., every two distinct nodes
share an edge) has chromatic number n; every node must have a unique
color, and every node having a unique color works.
Coloring Planar Graphs. A graph is planar if all the edges can be drawn
on a plane (e.g., a piece of paper) without any edges crossing. A well-known
result in mathematics state that all planar graphs are 4-colorable. E.g., the
complete graph with 5 nodes cannot be planar, since it requires 5 colors! Also
7.3. GRAPH COLORING 121
known as the 4 color map theorem, this allow any map to color all the
countries (or states, provinces) with only four colors without ambiguity (no
neighboring countries will be colored the same). In general, checking whether
planar graphs are 3-colorable is still NP-complete.
Step 3: P removes the cups covering u and v to reveal their colors, (c(u))
and (c(v)).
prover will always convince the verifier by following the protocol. What if the
122 graphs
graph is not 3-colorable? With what probability can the prover cheat? The
coloring (c(v)) must be wrong for at least one edge. Since the verifier V asks
the prover P to reveal the colors along a random edge, P will be caught with
probability 1/|E|.
As with before, even though the prover may cheat with a seemingly large
probability, 11/|E|, we can amplify the probabilities by repeating the proto-
col (say) 100|E| times. Due to independence, the probability that the prover
successfully cheats in all 100|E| repetitions is bounded by
100|E| |E| !100
1 1
1 = 1 e100
|E| |E|
Finite Automata
f is a transition function f : S S.
Here is how a DFA operates, on input string x. The DFA starts in state
s0 (the start state). It reads the input string x one character at at time, and
transition into a new state by applying the transition function f to the current
125
126 finite automata
state and the character read. For example, if x = x1 x2 , the DFA would
start by transitioning through the following states:
After reading the whole input x, if the DFA ends in an accepting state F ,
then x is accepted. Otherwise x is rejected.
Example 8.3. Consider the alphabet = {0, 1} and the DFA M = (S, , f, s0 , F )
defined by
S = {s0 , s1 } F = {s0 }
f (s0 , 0) = s0 f (s0 , 1) = s1
f (s1 , 0) = s1 f (s1 , 1) = s0
The DFA M accepts all strings that has an even number of 1s. Intuitively,
state s0 corresponds to we have seen an even number of 1s, and state s1
corresponds to we have seen an odd number of 1s. A graph of M looks like:
1
0 s0 s1 0
1
Figure 8.1: Illustration for Lemma 8.4. If a DFA M with < c states accepts
the string 1c , then it must also accept infinitely many other strings.
Lemma 8.4. Let c be a constant and L = {1c } (the singleton language con-
taining the string of c many 1s). Then no DFA with < c states can accept
L.
Proof. Assuming the contrary that some DFA M with < c states accepts
L. Let s0 , . . . , sc be the states traversed by M to accept the string 1c (and
so sc F is an accept state). By the pigeon hold principle, some state is
repeated twice, say s = si = sj with j > i. Let t = j i.
We now claim that M must also accept the strings 1c+t , 1c+2t , etc; let us
describe the behavior of M on these inputs. Starting from s0 , after reading
1i , M ends up in state s = si . From this point on, for every t many 1s in the
input, M will loop back to state s = si = sj . After sufficiently many loops,
M reads the final c i t many 1s, and transition from state s = sj to sc ,
an accept state. See Figure 8.1.
This gives a contradiction, since M accepts (infinitely) more strings than
the language L.
On the other hand, see Figure 8.2 for a DFA with c + 2 states that accepts
the language {1c }. The techniques of Lemma 8.1 can be generalized to show
the pumping lemma:
128 finite automata
1 1 0,1
s0 s1 s2 hell 0,1
Figure 8.2: A DFA with 4 states that accepts the language {12 }. This can
be easily generalized to construct a DFA with c + 2 states that accepts the
language {1c }.
Proof sketch. Again let s0 , . . . , s|x| be the states that M travels through to
accept the string x Due to the pigeonhole principle, some state must be
repeated among s0 , . . . , sk , say s = si = sj with 0 i < j k. We can now
set u to be the first i characters of x, v to be the next j i > 0 characters of
x, and w to be the rest of x.
C D
C (3, 3) (5, 5)
D (5, 5) (3, 3)
Roughly the utilities say the following. Both players cooperating is fine (both
prisoners get out of jail). But if one prisoner cooperates, the other should
defect (not only does the defector get out of jail, he always gets to keep the
root all to himself, while his accomplish stays in jail for a long time). If both
players defect, then they both stay in jail.
In game theory we look for a stable state called a Nash equilibrium; we
look a pair of strategies for the prisoners such that neither player has any
incentive to deviate. It is unfortunate (although realistic) that the only Nash
equilibrium here is for both prisoners to defect.
Now suppose we repeat this game 100 times. The total utility of a player
is 100 i (i) where u(i) the utility of the player in round i, and 0 < < 1
P
i=1 u
is a discount factor (for inflation and interests over time, etc.). Instead of
prisoners, we now have competing stores on the same street. To cooperate is
to continue business as usual, while to defect means to burn the other store
down for the day.
Clearly cooperating all the way seems best. But knowing that the first
store would cooperate all the time, the second store should defect in that last
(100th ) round. Knowing this, the first store would defect the round before
(99th round). Continuing this argument1 , the only Nash equilibrium is again
for both prisoners to always defect.
What happens in real life? Tit-for-tat2 seems to be the most popular
strategy: cooperate or defect according to the action of the other player in
the previous round (e.g., cooperate if the other player cooperated). How can
we change our game theoretical model to predict the use of tit-for-tat?
Suppose players use a DFA (with output) to compute their decisions; the
input is the decision of the other player in the previous round. Also assume
that players need to pay for the number of states in their DFA (intuitively,
having many states is cognitively expensive). Then tit-for-tat is a simple DFA
with just 1 state s, and the identity transition function: f (s, C) = (s, C),
f (s, D) = (s, D). Facing a player that follows tit-for-tat, the best strategy
would be to cooperate until round 99 and then defect in round 100. But we
have seen that counting with DFA requires many states (and therefore bears
a heavy cost)! This is especially true if the game has more rounds, or if the
1
See Induction and Rationality in Section 2.5
2
In a famous example in 2000, Apple removed all promotions of ATI graphic cards after
ATI prematurely leaked information on upcoming Macintosh models.
130 finite automata
0,1
Figure 8.3: A NFA with 5 states that accepts the language L3 . Intuitively,
given a string x L3 , the NFA would choose to remain in state s0 until it
reads the third last character; it would then (magically decide to) transition to
state s1 , read the final two characters (transitioning to s2 and s3 ), and accept.
The converse that any x accepted by the NFA must be in the language L3 is
easy to see. This can be easily generalized to construct an NFA with n + 2
states that accepts the language Ln .
The start state of M 0 is the singleton state containing the start state of
M , i.e., t0 = {s0 }.
The final states of M 0 is any state that contains a final state of M , i.e.,
F 0 = {t T = P(S) | t F 6= }.
Intuitively, after reading any (partial) string, the DFA M 0 tries to keep track
of all possible states that M may be in.
We now show that the DFA M 0 accepts any input x if and only if the NFA
M accepts x. Assume that M accepts x; that is, there exists some path of
computation s0 , s1 , . . . , s|x| such that s0 = s0 , s|x| F , and si+1 f (si , xi ).
Consider the (deterministic) path of computation of M 0 on input x: t0 , . . . , t|x| .
It can be shown inductively that si ti for all 0 i |x|:
Base case. s0 t0 since t0 = {s0 } by definition.
Inductive step. If si ti , then because si+1 f (si , xi ), we also have
[
si+1 ti+1 = f (s, xi )
sti
We conclude that s|x| t|x| . Since s|x| F , we have t|x| F 0 and so M 0 would
accept x.
For the converse direction, assume M 0 accepts x. Let t0 , . . . , t|x| be the
deterministic computation path of M 0 , with t0 = t0 and t|x| F 0 . From this
we can inductively define an accepting sequence of state transitions for M on
input x, starting from the final state and working backwards.
Base case. Because t|x| F 0 , there exists some s|x| |x| such that sk F .
Inductive step. Given some si+1 ti+1 , then there must exist some si ti
such that si+1 f (si , xi ) (in order for ti to transition to ti+1 .
It is easy to see that the sequence s0 , . . . , s|x| , inductively defined above, is
an valid, accepting sequence of state transitions for M on input x: s0 = s0
since s0 t0 = t0 = {s0 }, s|x| F by the base case of the definition, and
the transitions are valid by the inductive step of the definition. Therefore M
accepts x.
8.3. REGULAR EXPRESSIONS AND KLEENES THEOREM 133
Definition 8.11. The set of regular expressions over alphabet are de-
fined inductively as follows:
Usually the Kleene star takes precedence over concatenation, which takes
precedence over alternation. In more complex expressions, we use parenthesis
to disambiguate the order of operations between concatenations, alternations
and Kleene stars. Examples of regular expressions over the lower case letters
include: ab|c , (a|b)(c|), . A common extension of regular expressions is
the + operator; A+ is interpreted as syntactic sugar (a shortcut) for AA .
As of now a regular expression is just a syntactic object it is just a
sequence of symbols. Next we describe how to interpret these symbols to
specify a language.
L(x) = {x} (i.e., the singleton set consisting only of the one-character
string x).
Example 8.13. The parity language consisting of all strings with an even
number of 1s can be specified by the regular expression (0 10 10 ) . The
language consisting of all finite strings {0, 1} can be specified either by (0|1)
or (0 1 ) .
We can proof Kleenes Theorem constructively. That is, given any DFA,
we can generate an equivalent regular expression to describe the language
recognized by the DFA, and vice versa. We omit the formal proof of Kleenes
Theorem; in the rest of this section, we give an outline of how a regular
expression can be transformed into a NFA (which can then be transformed
into a DFA).
L() is recognized by a NFA where the start state is also a final state,
and has outgoing transitions.
Case AB: Let the languages L(A) and L(B) be recognized by NFAs MA
and MB , respectively. Recall that L(AB) contains strings that can be
divided into two parts such that the first part is in L(A), recognized
by MA , and the second part is in L(B), recognized by MB . Hence
intuitively, we need a combined NFA MAB that contains the NFA MA
followed by the NFA MB , sequentially. To do so, let us link the
final states of MA to the start state of MB . One way to proceed is
to modify all the final states in MA , by adding to them all outgoing
transitions leaving the start state of MB (i.e., each final state in MA
can now function as the start state of MB and transition to appropriate
states in MB .)
The start state of MAB is the start state of MA . The final states of
MAB is the final states of MB ; furthermore, if the start state of MB is
final, then all of the final states in MA is also final in MAB (because we
want the final states of MA to be linked to the start state of MB ).
We leave it to the readers to check that this combined NFA MAB does
indeed accept strings in L(AB), and only strings in L(AB).
Before we proceed onto other cases, let us abstract the notion of a link from
above. The goal of a link from state s to t, is to allow the NFA to (nonde-
terministically) transition from state s to state t, without reading any input.
We have implemented this link above by adding the outgoing transitions of
t to s (i.e., this simulate the case when the NFA nondeterministically transi-
tions to state t and then follows one of ts outgoing transition). We also make
s a final state if t is a final state (i.e., this simulate the case when the NFA
nondeterministically transitions to state t and then halt and accepts).
Case A|B: Again, let the languages L(A) and L(B) be recognized by NFAs
MA and MB , respectively. This time, we construct a machine MA|B
that contains MA , MB and a brand new start state s0 , and add links
136 finite automata
3
A tempting solution is to instead merge the start state of MA and MB (combining
their incoming and outgoing transitions), and make the newly merged state the start state of
MA|B . This does not work, because such a merger does not force the NFA MA|B to choose
between MA and MB ; on some input, MA|B may transition between the states of MA and
MB multiple times via the merged state. Can you come up with a counter example?
Appendix A
Problem Sets
Problem 2 [5 points]
Compute (38002 7201 ) mod 55. Show your work.
Problem 3 [2 + 4 = 6 points]
Let p 3 be any prime number. Let c, a {1, . . . , p 1} such that a is a
solution to the equation x2 c (mod p), i.e., a2 c (mod p).
(a) Show that p a is also a solution to the equation x2 c (mod p), i.e.,
(p a)2 c (mod p).
(b) Show that a and p a are the only solutions to the equation x2 c
(mod p) modulo p, i.e., if b Z satisfies b2 c (mod p), then b a
(mod p) or b p a (mod p).
137
138 problem sets
Problem 4 [4 points]
How many solutions are there to the equation a+b+c+d = 30, if a, b, c, d N?
(N includes the number 0. You do not need to simplify your answer.)
Problem 5 [2 + 2 + 4 = 8 points]
Let n be a positive even integer.
(a) How many functions f : {0, 1}n {0, 1}n are there that do not map an
element to itself (i.e., f satisfies f (x) 6= x for all x {0, 1}n )?
(b) Given a string x {0, 1}n , let xrev denote the string in {0, 1}n obtained
from x by reversing the ordering of the bits of x (e.g., the first bit of xrev
is the last bit of x, etc.). How many strings x {0, 1}n satisfy xrev = x?
Justify your answer.
(c) How many functions f : {0, 1}n {0, 1}n are there that satisfy f (x) 6= x
and f (x) 6= xrev for all x {0, 1}n ? Justify your answer.
Problem 6 [6 points]
Let n, r, k N+ such that k r n. Show that nr kr = nk nk
rk by using a
combinatorial argument (i.e., show that both sides of the equation count the
same thing).
Problem 7 [3 + 3 = 6 points]
A certain candy similar to Skittles is manufactured with the following proper-
ties: 30% of the manufactured candy pieces are sweet, while 70% of the pieces
are sour. Each candy piece is colored either red or blue (but not both). If a
candy piece is sweet, then it is colored blue with 80% probability (and colored
red with 20% probability), and if a piece is sour, then it is colored red with
80% probability. The candy pieces are mixed together randomly before they
are sold. You bought a jar containing such candy pieces.
(a) If you choose a piece at random from the jar, what is the probability that
you choose a blue piece? Show your work. (You do not need to simplify
your answer.)
(b) Given that the piece you chose is blue, what is the probability that the
piece is sour? Show your work. (You do not need to simplify your
answer.)
A.1. PROBLEM SET A 139
Problem 8 [3 + 3 = 6 points]
A literal is an atom (i.e., an atomic proposition) or the negation of an atom
(e.g., if P is an atom, then P is a literal, and so is P ). A clause is a formula
of the form li lj lk , where li , lj , lk are literals and no atom occurs in li lj lk
more than once (e.g., P Q P is not allowed, since the atom P occurs in
P Q P more than once).
Examples: P1 P2 P4 is a clause, and so is P2 P4 P5 .
Problem 9 [3 + 3 = 6 points]
Consider the formula (P Q) (P Q), where P and Q are atoms.
Problem 10 [6 points]
Let G be an undirected graph, possibly with self-loops. Suppose we have the
predicate symbols Equals(, ), IsV ertex(), and Edge(, ).
Let D be some domain that contains the set of vertices of G (D might
contain other elements as well). Let I be some interpretation that specifies
functions for Equals(, ), IsV ertex(), and Edge(, ), so that for all u, v D,
we have Equals[I](u, v) = T (True) if and only if u = v, IsV ertex[I](u) = T
if and only if u is a vertex of G, and if u and v are both vertices of G, then
Edge[I](u, v) = T if and only if {u, v} is an edge of G (we do not know the
value of Edge[I](u, v) when u or v is not a vertex of G).
Write a formula in first order logic that captures the statement the graph
G does not contain a triangle, i.e., the formula is T (True) under (D, I) if
and only if the graph G does not contain a triangle (a triangle is 3 distinct
vertices all of which are connected to one another via an edge).
140 problem sets
Problem 11 [6 points]
Suppose we have an undirected graph G such that the degree of each vertex is
a multiple of 10 or 15. Show that the number of edges in G must be a multiple
of 5.
Problem 12 [3 + 2 + 5 = 10 points]
Consider the following non-deterministic finite automaton (NFA):
b y
a
x b
b a
a
b a,b
w b
b
z
a
u v
a
(a) Write a regular expression that defines the language recognized by the
above NFA.
(b) Construct (by drawing a state diagram) the smallest deterministic finite
automaton (DFA) that recognizes the same language as the above NFA
(smallest in terms of the number of states).
(c) Prove that your DFA for part (b) is indeed the smallest DFA that rec-
ognizes the same language as the above NFA (smallest in terms of the
number of states).
Problem 13 [6 points]
Let
S S1 , S2 , S3 , S4 , . . . be San infinite sequence ofScountable sets. Show that
S
n=1 n is countable. ( n=1 Sn is defined by n=1 Sn := {x | x Sn for
+
some n N }.)
Appendix B
Problem 1 [6 points]
141
142 solutions to problem sets
Problem 2 [5 points]
Compute (38002 7201 ) mod 55. Show your work.
Solution:
Note that 55 = 5 11, so we have (55) = (4)(10) = 40. Thus, we have (38002
7201 ) mod 55 = ((38002 mod 55)(7201 mod 55)) mod 55 = ((38002 mod (55) mod
55) (7201 mod (55) mod 55)) mod 55 = ((38002 mod 40 mod 55) (7201 mod 40 mod
55)) mod 55 = ((32 mod 55) (71 mod 55)) mod 55 = (9 7) mod 55 = 63 mod
55 = 8, where we have used Eulers theorem in the second equality.
Problem 3 [2 + 4 = 6 points]
Let p 3 be any prime number. Let c, a {1, . . . , p 1} such that a is a
solution to the equation x2 c (mod p), i.e., a2 c (mod p).
(a) Show that p a is also a solution to the equation x2 c (mod p), i.e.,
(p a)2 c (mod p).
(b) Show that a and p a are the only solutions to the equation x2 c
(mod p) modulo p, i.e., if b Z satisfies b2 c (mod p), then b a
(mod p) or b p a (mod p).
Solution:
Problem 4 [4 points]
How many solutions are there to the equation a+b+c+d = 30, if a, b, c, d N?
(N includes the number 0. You do not need to simplify your answer.)
Solution:
B.1. PROBLEM SET A 143
33
3 , since there are 4 distinguishable urns (a, b, c, and d) and 30 indistin-
guishable balls. (See the lecture notes.)
Problem 5 [2 + 2 + 4 = 8 points]
Let n be a positive even integer.
(a) How many functions f : {0, 1}n {0, 1}n are there that do not map an
element to itself (i.e., f satisfies f (x) 6= x for all x {0, 1}n )?
(b) Given a string x {0, 1}n , let xrev denote the string in {0, 1}n obtained
from x by reversing the ordering of the bits of x (e.g., the first bit of xrev
is the last bit of x, etc.). How many strings x {0, 1}n satisfy xrev = x?
Justify your answer.
(c) How many functions f : {0, 1}n {0, 1}n are there that satisfy f (x) 6= x
and f (x) 6= xrev for all x {0, 1}n ? Justify your answer.
Solution:
n
(a) (2n 1)(2 ) , since there are 2n elements in the domain {0, 1}n , and for
each of these elements, f can map the element to any element in {0, 1}n ex-
cept for itself, so there are 2n 1 choices for the element.
(b) 2n/2 , since to construct a string x {0, 1}n such that xrev = x, there
are 2 choices (either 0 or 1) for each of the first n/2 bits (the first half of the
n-bit string), and then the second half is fully determined by the first half.
(c) Consider constructing a function f : {0, 1}n {0, 1}n such that f (x) 6= x
and f (x) 6= xrev for all x {0, 1}n . For each x {0, 1}n such that xrev = x,
there are 2n 1 choices for f (x). For each x {0, 1}n such that xrev 6= x,
there are 2n 2 choices for f (x). Since there are 2n/2 strings x {0, 1}n such
that xrev = x, and since there are 2n 2n/2 strings x {0, 1}n such that
xrev 6= x, the number of functions f : {0, 1}n {0, 1}n such that f (x) 6= x
n/2 n n/2
and f (x) 6= xrev for all x {0, 1}n , is (2n 1)(2 ) (2n 2)(2 2 ) .
Problem 6 [6 points]
Let n, r, k N+ such that k r n. Show that nr kr = nk nk
rk by using a
combinatorial argument (i.e., show that both sides of the equation count the
same thing).
144 solutions to problem sets
Solution:
Problem 7 [3 + 3 = 6 points]
A certain candy similar to Skittles is manufactured with the following proper-
ties: 30% of the manufactured candy pieces are sweet, while 70% of the pieces
are sour. Each candy piece is colored either red or blue (but not both). If a
candy piece is sweet, then it is colored blue with 80% probability (and colored
red with 20% probability), and if a piece is sour, then it is colored red with
80% probability. The candy pieces are mixed together randomly before they
are sold. You bought a jar containing such candy pieces.
(a) If you choose a piece at random from the jar, what is the probability that
you choose a blue piece? Show your work. (You do not need to simplify
your answer.)
(b) Given that the piece you chose is blue, what is the probability that the
piece is sour? Show your work. (You do not need to simplify your
answer.)
Solution:
Let B be the event that the piece you choose is blue, and let D be the event
that the piece you choose is sweet.
Problem 8 [3 + 3 = 6 points]
A literal is an atom (i.e., an atomic proposition) or the negation of an atom
(e.g., if P is an atom, then P is a literal, and so is P ). A clause is a formula
of the form li lj lk , where li , lj , lk are literals and no atom occurs in li lj lk
more than once (e.g., P Q P is not allowed, since the atom P occurs in
P Q P more than once).
Examples: P1 P2 P4 is a clause, and so is P2 P4 P5 .
Solution:
(a) The probability that C evaluates to T rue is equal to 1 minus the prob-
ability that C evaluates to F alse. Now, C evaluates to F alse if and only
if each of the three literals in C evaluates to F alse. A literal in C evalu-
ates to F alse with probability 12 , and since no atom occurs in C more than
once, the probability that all three literals in C evaluate to F alse is ( 12 )3 (by
independence). Thus, the probability that C evaluates to T rue is 1( 12 )3 = 87 .
Problem 9 [3 + 3 = 6 points]
Consider the formula (P Q) (P Q), where P and Q are atoms.
Solution:
146 solutions to problem sets
(a) No, since the interpretation that assigns T rue to P and F alse to Q would
make the formula evaluate to F alse, since (P Q) evaluates to T rue while
(P Q) evaluates to F alse.
(b) Yes, since any interpretation that assigns F alse to P would make (P Q)
evaluate to F alse, and so (P Q) (P Q) would evaluate to T rue.
Problem 10 [6 points]
Let G be an undirected graph, possibly with self-loops. Suppose we have the
predicate symbols Equals(, ), IsV ertex(), and Edge(, ).
Let D be some domain that contains the set of vertices of G (D might
contain other elements as well). Let I be some interpretation that specifies
functions for Equals(, ), IsV ertex(), and Edge(, ), so that for all u, v D,
we have Equals[I](u, v) = T (True) if and only if u = v, IsV ertex[I](u) = T
if and only if u is a vertex of G, and if u and v are both vertices of G, then
Edge[I](u, v) = T if and only if {u, v} is an edge of G (we do not know the
value of Edge[I](u, v) when u or v is not a vertex of G).
Write a formula in first order logic that captures the statement the graph
G does not contain a triangle, i.e., the formula is T (True) under (D, I) if
and only if the graph G does not contain a triangle (a triangle is 3 distinct
vertices all of which are connected to one another via an edge).
Solution:
Problem 11 [6 points]
Suppose we have an undirected graph G such that the degree of each vertex is
a multiple of 10 or 15. Show that the number of edges in G must be a multiple
of 5.
Solution:
P
Let G = (V, E). Recall that 2|E| = vV deg(v). The degree of each P vertex is
a multiple of 10 or 15, and thus is a multiple of 5. Thus, 2|E| = vV deg(v)
is a multiple of 5, since each term of the sum is a multiple of 5. Thus, 5 divides
B.1. PROBLEM SET A 147
2|E|, and since 5 is prime, 5 must divide 2 or |E|. 5 clearly does not divide 2,
so 5 divides |E|, as required.
Problem 12 [3 + 2 + 5 = 10 points]
Consider the following non-deterministic finite automaton (NFA):
b y
a
x b
b a
a
b a,b
w b
b
z
a
u v
a
(a) Write a regular expression that defines the language recognized by the
above NFA.
(b) Construct (by drawing a state diagram) the smallest deterministic finite
automaton (DFA) that recognizes the same language as the above NFA
(smallest in terms of the number of states).
(c) Prove that your DFA for part (b) is indeed the smallest DFA that rec-
ognizes the same language as the above NFA (smallest in terms of the
number of states).
Solution:
(a) (ab)
(b)
a a,b
v a
u b
b w
148 solutions to problem sets
(c) We will show that any DFA that recognizes (ab) must have at least 3
states. 1 state is clearly not enough, since a DFA with only 1 state recognizes
either the empty language or the language {a, b} . Now, consider any DFA
with 2 states. We note that the start state must be an accepting state, since
the empty string needs to be accepted by the DFA. Since the string a is not
accepted by the DFA, the a-transition (the arrow labeled a) out of the start
state cannot be a self-loop, so the a-transition must lead to the other state.
Similarly, since the string b is not accepted by the DFA, the b-transition out
of the start state must lead to the other state. However, this means that bb is
accepted by the DFA, since ab is accepted by the DFA and the first letter of
the string does not affect whether the string is accepted, since both a and b
result in transitioning to the non-start state. This means that the DFA does
not recognize the language defined by (ab) . Thus, any DFA that recognizes
(ab) must have at least 3 states.