This condensed study guide connects definitions to the mechanisms that use them. Read the short examples to understand why a rule works, then use the reference tables to recall it. The topic list follows the catalog description below; it is not a verified checklist of the current objective assessment. Your current course materials take precedence.
WGU’s June 2026 catalog defines C959 around logic and proofs, Boolean algebra and functions, set theory, finite and infinite sequences and series, relations, graphs, and trees. C960 covers searching and sorting, Big-O, number theory and cryptography, recursion and induction, counting, probability, and models of computation. (wgu.edu)
For each topic, ask: what object am I working with, what does its definition allow, and which operation answers the question? A set of choices, an ordered list of choices, and a probability distribution may describe the same situation, but call for different calculations.
Part IIC960 — Discrete Mathematics II#
Reading route. C960 reuses C959's logic, sets, functions, and finite sums. Follow these chains rather than treating every formula as an isolated fact:
- Trace an algorithm → count its work → compare searches and sorts. Recurrences count recursive work; induction proves claims about it.
- Divisibility and remainders → gcd → modular inverse → RSA. Binary place value makes repeated squaring efficient.
- Count outcomes → assign probabilities → measure outcomes with a random variable → choose a distribution.
- Strings and languages → state machines → regular expressions and limits of finite memory.
11Algorithms and pseudocode#
The mathematical objects are now inputs to procedures. First follow the changing state to find what a procedure does. Only then ask whether it is correct and how its work grows; output, correctness, and cost are different questions.
An algorithm is a finite, unambiguous, effective procedure that transforms inputs into outputs.
A proper algorithm has:
- specified inputs;
- specified outputs;
- precise steps;
- termination after finitely many steps;
- executable operations;
- correctness for all allowed inputs.
11.1Common algorithmic structures#
Sequence#
Execute statements in order.
Selection#
Choose a branch:
if condition
action A
else
action B
Iteration#
Repeat using a loop.
Recursion#
A procedure calls itself on a smaller or simpler input.
11.2Reading pseudocode#
Key distinctions:
- Assignment changes a variable:
- Equality compares values: would be false as an ordinary mathematical equation.
returnusually ends the current procedure immediately.- A loop endpoint may be inclusive or exclusive.
- Array indexing may begin at or .
- Updating a variable inside a loop affects subsequent iterations.
When tracing, maintain a small table containing:
- current iteration;
- relevant variable values;
- output produced so far.
Ignore variables that never change.
11.3Correctness#
An algorithm is correct if it produces the specified output for every permitted input.
A loop invariant is a statement that remains true:
- before the first iteration;
- after each iteration;
- when the loop ends.
A correctness proof typically shows:
- initialization: invariant starts true;
- maintenance: one iteration preserves it;
- termination: invariant plus stopping condition implies the result.
This is induction expressed in algorithmic form.
12Complexity and Big-O#
Use the trace from the previous chapter, but replace a particular input size with n. Count how often the main operation runs. A bound summarizes that count; it does not change what the algorithm computes.
Complexity measures resource growth as input size increases.
Common resources are:
- time;
- memory;
- comparisons;
- arithmetic operations;
- recursive calls.
The focus is asymptotic growth, not exact wall-clock time.
12.1Best, worst, and average case#
- Best case: minimum operations among size- inputs.
- Worst case: maximum operations.
- Average case: expected operations under an assumed input distribution.
Unless specified, complexity questions often ask for worst-case behavior.
Case and bound are separate choices. First choose which inputs to describe, then bound their operation count. Linear search has constant best-case cost and linear worst-case cost. O does not mean “worst,” and Ω does not mean “best”; either notation can bound a best-case, worst-case, or average-case function.
12.2Big-O, Omega, and Theta#
Big-O#
means is an asymptotic upper bound. Formally, there are constants and such that:
for all .
Big-Omega#
means is an asymptotic lower bound.
Big-Theta#
means is both an upper and lower bound—a tight growth classification.
Big-O is not necessarily exact. A linear function is also technically , though is the informative tight classification.
12.3Simplifying complexity expressions#
Discard:
- constant factors;
- lower-order terms.
As grows, the dominant term determines behavior.
12.4Growth hierarchy#
From slower to faster:
for fixed .
Logarithm bases differ only by a constant factor:
so all fixed bases represent:
Polynomial growth is generally considered scalable relative to exponential or factorial growth.
12.5Recognizing loop complexity#
Fixed work#
x = a + b
Linear loop#
for i = 1 to n
Step size other than one#
for i = 1 to n step 10
Still:
Dividing the iteration count by a fixed constant does not change asymptotic class.
Doubling or halving#
i = 1
while i < n
i = 2i
After iterations:
Stop near , so:
Complexity:
Independent nested loops#
for i = 1 to n
for j = 1 to n
so:
Triangular loop#
for i = 1 to n
for j = 1 to i
Total iterations:
therefore:
Linear outer, logarithmic inner#
for i = 1 to n
j = 1
while j < n
j = 2j
Sequential blocks#
For one block followed by another, add costs and retain the dominant term:
Nested blocks#
For genuinely nested independent repetitions, multiply counts.
12.6Common operation sums#
If , the final sum is , even though there are only levels.
13Searching and sorting#
Searching asks where an item is; sorting arranges items so later operations can exploit order. Linear search works without order. Binary search earns its speed by using sorted order to rule out half the candidates at each step.
13.1Linear search#
Inspect elements one by one until:
- the target is found, or
- the collection ends.
No sorting is required.
- best case: ;
- worst case: ;
- average case: .
13.2Binary search#
Binary search requires sorted data.
- inspect the middle element;
- if equal, stop;
- otherwise discard the half that cannot contain the target;
- repeat.
After divisions, the remaining size is roughly:
Set this near :
so:
Worst-case complexity:
Binary search on a linked list may not provide the same practical benefit because accessing the middle is not constant-time.
Two sorting terms recur below. Stable means equal-key records keep their original relative order. In-place means constant auxiliary storage for rearranging the items. Quicksort is often called in-place while its recursion stack is counted separately; check the space convention in the question.
13.3Bubble sort#
Repeatedly compare adjacent elements and swap inverted pairs.
After a full pass, a largest remaining element “bubbles” toward the end.
- worst case: ;
- average: ;
- optimized best case: ;
- stable;
- in-place.
13.4Selection sort#
Repeatedly find the smallest remaining item and place it next.
It performs roughly:
comparisons:
It performs relatively few swaps but remains quadratic.
Usually:
- not stable in its basic form;
- in-place.
13.5Insertion sort#
Maintain a sorted prefix and insert each next item into its proper position.
- best case on already sorted data: ;
- average and worst: ;
- stable;
- in-place;
- efficient for small or nearly sorted inputs.
13.6Merge sort#
- divide the list into halves;
- recursively sort each half;
- merge the sorted halves.
There are approximately:
levels, and each level performs merge work:
Merge sort is:
- stable;
- reliably ;
- usually requires auxiliary memory for arrays.
13.7Quicksort#
- choose a pivot;
- partition elements around it;
- recursively sort partitions.
If partitions are reasonably balanced:
If pivots repeatedly create highly unbalanced partitions:
Typical properties:
- average ;
- worst ;
- often in-place;
- typically not stable.
13.8Algorithm categories#
Brute force#
Enumerate many or all possibilities.
Simple and general, but often exponential or factorial.
Greedy#
Choose the locally best option at every step.
A greedy method is correct only when the problem has a structure proving local choices lead to a global optimum.
Kruskal and Prim are greedy.
Divide and conquer#
Divide into subproblems, solve them, and combine.
Merge sort and binary search use this structure.
Dynamic programming#
Solve overlapping subproblems once and store their answers.
It converts many exponential recursive procedures into polynomial algorithms.
Naive Fibonacci recomputes the same values repeatedly; memoization removes that duplication.
14Number theory#
| Number theory studies integers, divisibility, primes, and remainders. Start with exact division, then allow a remainder. Euclid finds a gcd; back-substitution expresses it as a combination of the inputs. When that gcd is 1, the combination gives a modular inverse. Each step prepares the next. |
14.1Divisibility#
| means: |
| If and , then: |
| and: |
| for integers . |
| If: |
| and: |
| then: |
14.2Division algorithm#
For integer and positive integer , there exist unique integers such that:
with:
Then:
and:
The nonnegative remainder requirement matters with negative dividends.
For example:
so:
not .
14.3Modular congruence#
means:
Equivalent interpretations:
- have the same remainder modulo ;
- they represent the same residue class.
Congruence behaves well under addition and multiplication:
If:
and:
then:
and:
You may reduce values modulo after every step.
Ordinary division is not generally valid modulo . It requires an invertible divisor.
14.4Prime numbers and factorization#
A prime is an integer greater than with exactly two positive divisors:
A composite number has a nontrivial factorization.
To test whether is prime, it is sufficient to test prime divisors no larger than:
If is composite, at least one of must be at most .
The fundamental theorem of arithmetic says every integer greater than has a unique prime factorization apart from order.
14.5Greatest common divisor and least common multiple#
is the greatest positive integer dividing both.
Two integers are coprime when:
The least common multiple satisfies:
14.6Euclidean algorithm#
Use repeated division:
and the identity:
Continue until the remainder becomes zero. The last nonzero remainder is the gcd.
For example:
Therefore:
The algorithm is efficient because remainders decrease rapidly.
14.7Bézout’s identity and extended Euclid#
Bézout’s identity states that there exist integers such that:
The extended Euclidean algorithm finds these coefficients by back-substituting through Euclid’s equations.
For the preceding gcd:
and:
so:
Thus:
14.8Modular inverses#
An inverse of modulo is a number satisfying:
It exists exactly when:
If extended Euclid produces:
then reducing modulo gives:
so:
Reduce a negative coefficient to the standard range by adding multiples of .
Undoing multiplication. Modulo 7, the inverse of 3 is 5 because 3×5 = 15 ≡ 1. Thus 3x ≡ 6 gives x ≡ 5×6 ≡ 2. Modulo 8, however, 2 has no inverse: 2 times any integer stays even and cannot be congruent to 1. The gcd condition tells you when this method is legal.
14.9Linear congruences#
Consider:
Let:
A solution exists exactly when:
If , multiply by the inverse of :
If divides , the congruence has incongruent solutions modulo .
14.10Chinese remainder theorem#
For pairwise coprime moduli:
a system:
has a unique solution modulo:
A constructive method is:
- compute ;
- set:
- find satisfying:
- calculate:
For small systems, substitution is often faster.
15Number bases#
The division algorithm already splits a number into quotient and remainder. Base conversion repeats that operation: the remainder is the last digit, and the quotient contains the digits still to recover.
A base- numeral:
represents:
Allowed digits are:
15.1Converting to decimal#
Expand by place value:
15.2Converting from decimal#
Repeatedly divide by the target base:
- divide by ;
- record the remainder;
- divide the quotient again;
- read remainders from last to first.
The first remainder produced is the least significant digit.
15.3Binary, octal, and hexadecimal#
Binary uses base .
Octal uses base , so each octal digit corresponds to 3 bits.
Hexadecimal uses base , so each hex digit corresponds to 4 bits.
| Hex | Binary |
|---|---|
| 0 | 0000 |
| 1 | 0001 |
| 8 | 1000 |
| A | 1010 |
| F | 1111 |
The number of bits needed to represent positive is:
The number of bits needed to represent all integers from through is:
16Modular exponentiation and cryptography#
You can now reduce remainders, find gcds, and undo multiplication with a modular inverse. Cryptography combines those operations. Binary exponents keep the arithmetic small; Euler’s theorem explains when powers repeat.
16.1Fast modular exponentiation#
To calculate:
do not construct directly.
Write in binary and repeatedly square:
Reduce modulo after every multiplication.
If:
then:
Use only powers corresponding to 1-bits in the exponent.
This requires only:
squaring/multiplication steps.
16.2Euler’s totient function#
counts positive integers no greater than that are coprime to .
For prime :
For distinct primes :
More generally, if:
then:
16.3Fermat’s little theorem#
If is prime and , then:
Equivalent general form:
This can reduce large exponents modulo when is not divisible by .
16.4Euler’s theorem#
If:
then:
Fermat’s theorem is the prime-modulus special case.
16.5Cryptographic terminology#
- Plaintext: original information.
- Ciphertext: encrypted information.
- Encryption: transforms plaintext into ciphertext using a key.
- Decryption: reverses the transformation with the appropriate key.
- Symmetric encryption: the same shared secret, or directly related secrets, perform encryption and decryption.
- Public-key encryption: a public key encrypts or verifies; a private key decrypts or signs.
- Encoding: changes representation but does not provide secrecy.
- Hashing: maps input to a fixed-size digest and is intended to be one-way.
16.6Shift cipher#
Represent letters as residues, often:
Encryption:
Decryption:
A Caesar cipher is insecure because there are only 26 possible shifts.
16.7Affine cipher#
Encryption:
The multiplier must be invertible modulo :
Decryption:
The modular inverse is what makes the transformation reversible.
16.8RSA#
RSA connects nearly every number-theory mechanism in the course.
Key generation#
Choose distinct primes:
Compute:
Compute:
Choose a public exponent satisfying:
and:
Find the private exponent:
The public key is:
The private information includes , and in real implementations usually as well.
Encryption#
For message representative with:
calculate:
Decryption#
Use fast modular exponentiation for both.
Why it works#
Because:
there is an integer such that:
When gcd(m, n) = 1, Euler’s theorem gives:
The Euler argument above requires the message to be coprime to n. RSA also recovers other message representatives: work modulo each prime separately. If p divides the message, both the original and recovered value are 0 modulo p; otherwise Fermat’s theorem applies. Do the same modulo q, then use the Chinese remainder theorem to obtain the same message modulo pq. Textbook RSA here illustrates the arithmetic; real encryption also needs a secure padding scheme.
RSA traps#
- Find modulo , not modulo .
- must be coprime to .
- The message block must be smaller than .
- Reduce after every multiplication.
- In toy problems, factorization of is intentionally feasible; real RSA uses enormous primes.
17Recursion and recurrence relations#
Recall recursive sequences from C959: an initial value plus a rule determines later values. A recursive program uses the same idea to solve smaller inputs. Distinguish the value it returns from the number of operations it performs; each may obey a different recurrence.
17.1Recursive definitions#
A recursive definition contains:
- one or more base cases;
- a rule defining larger objects from smaller ones.
For factorial:
A recursive algorithm must move toward a base case. Otherwise it fails to terminate.
17.2Call stack and unwinding#
When a recursive function calls itself, the current operation waits on the call stack.
For:
the calls expand:
Then return values unwind:
For subtraction, division, or multiple recursive calls, the return order matters.
17.3Recurrence relations#
A recurrence defines sequence terms from preceding terms.
The order is the maximum number of positions referenced backward.
is first-order.
is second-order.
Initial conditions are required to select one particular solution.
17.4Arithmetic and geometric recurrences#
Arithmetic:
Solution:
Geometric:
Solution:
17.5First-order linear recurrence#
For:
repeated substitution gives:
When :
When :
This form models repeated growth plus a fixed deposit or input.
The timing matters. “Add the deposit, then apply interest” and “apply interest, then add the deposit” produce different recurrences.
17.6Solving by telescoping#
If:
sum both sides:
so:
This converts the recurrence into a known finite sum.
17.7Second-order homogeneous recurrences#
Suppose:
Try a solution:
Substitution yields:
This is the characteristic equation.
Distinct roots#
If roots are :
Use two initial conditions to determine .
Repeated root#
If one root has multiplicity two:
The factor supplies the second independent solution.
17.8Fibonacci sequence#
Its characteristic equation is:
with roots:
and:
leading to:
For exam purposes, the recurrence mechanism and growth behavior are more important than reproducing this closed form.
17.9Runtime recurrences#
A runtime recurrence counts calls and local work, not the returned value. In T(n) = 2T(n/2) + Θ(n), the 2 counts recursive calls, n/2 is their input size, and Θ(n) is the work outside them. For merge sort, each level processes n items in total, not n per call; about log₂n levels give Θ(n log n).
Linear recursion#
Unrolling produces constant contributions:
Linear work at every decrement#
This sums:
so:
Repeated halving#
There are levels:
Merge-sort form#
There are levels and work per level:
Naive Fibonacci#
The recursion tree branches and repeats subproblems, giving exponential growth.
17.10Simplified Master theorem#
This form assumes a fixed number a ≥ 1 of subproblems, a fixed shrink factor b > 1, and constant-size base cases. It does not apply to recurrences such as T(n−1), where the input shrinks by subtraction rather than division.
For:
compare with:
- If is polynomially smaller, recursive leaves dominate:
- If they are the same order:
- If is polynomially larger and regularity conditions hold:
This is a structured way to read divide-and-conquer recurrences.
18Mathematical induction#
Induction proves statements indexed by integers.
To prove for every :
Base case#
Prove:
Inductive hypothesis#
Assume:
for an arbitrary .
Inductive step#
Use the hypothesis to prove:
This establishes the chain:
The inductive hypothesis is a temporary assumption about , not permission to assume the case.
18.1Induction for sums#
To prove a formula for:
the case begins by separating the new term:
Then replace the first portion using the inductive hypothesis.
That is the standard mechanism for identities involving cumulative sums.
For the sum identity 1 + … + n = n(n+1)/2, the base n = 1 gives 1 = 1. Assume the identity for k. Then the next sum is k(k+1)/2 + (k+1) = (k+1)(k+2)/2, exactly the required formula for k+1. The proof works because the new case contains the old case plus one new term.
18.2Induction for divisibility#
To prove:
show:
- ;
- assuming: for some integer , rewrite as:
and factor out .
18.3Induction for inequalities#
The inductive hypothesis gives a bound on the -case. Manipulate it in a direction that produces the required bound.
Be careful:
- multiplying by a negative reverses inequalities;
- taking reciprocals of positive values reverses inequalities;
- a true base case does not repair an invalid inductive step.
18.4Strong induction#
Strong induction assumes:
and proves .
Use it when the next case depends on several earlier cases.
Typical uses:
- prime factorization;
- recursively reducing by varying amounts;
- Fibonacci-like recurrences;
- tiling or construction problems.
Strong induction is not logically stronger than ordinary induction; it gives a more convenient hypothesis.
18.5Structural induction#
Structural induction applies to recursively defined objects.
For a recursively defined collection:
- prove the property for every base object;
- assume it holds for component objects;
- prove each construction rule preserves it.
Applications include:
- strings;
- logical formulas;
- rooted trees;
- recursively generated expressions.
It is induction over construction depth rather than an explicit integer variable.
19Counting#
Counting problems are largely classification problems.
Before choosing a formula, determine:
- Is this a sequence of decisions or a choice among cases?
- Does order matter?
- Is repetition permitted?
- Are objects distinguishable?
- Are there restrictions?
- Can the complement be counted more easily?
19.1Sum rule#
If one outcome can occur through disjoint cases containing and possibilities:
The cases must not overlap. If they do, use inclusion-exclusion.
Recognition cue: OR between mutually exclusive alternatives.
19.2Product rule#
If a process has successive stages with:
choices, then the total is:
Multiply when each partial choice has the stated number of extensions. The available objects may change: choosing two distinct people for ordered roles gives n(n−1). If branches have different numbers of extensions, count each branch and add. The word “and” alone does not justify multiplication.
19.3Bijection principle#
If a difficult collection can be paired one-to-one with an easier collection, they have the same size.
Much of combinatorics works by representing an object as:
- a bit string;
- a subset;
- a permutation;
- a tuple;
- a path.
19.4Division rule#
If a counting procedure counts every actual object exactly times, divide by .
This is why combinations divide permutations by : every unordered -element choice appears in orders.
19.5Permutations#
When selecting and ordering distinct objects from :
For all objects:
Order matters.
Examples of ordered roles:
- president, vice president, secretary;
- first, second, third place;
- password positions.
19.6Combinations#
When selecting objects from and order does not matter:
Symmetry:
Choosing which items are included is equivalent to choosing which are excluded.
19.7The four basic selection models#
| Order matters? | Repetition? | Count |
|---|---|---|
| Yes | No | |
| Yes | Yes | |
| No | No | |
| No | Yes |
This table should be automatic.
Count the same people in two ways. From five people, choose a chair and a secretary: 5×4 = 20 assignments because swapping the roles changes the result. Choose a two-person committee instead: divide by 2! to get 10, since each pair was counted in both orders. The formula follows from what counts as a different outcome.
19.8Repeated identical objects#
For total objects where identical categories occur times:
The denominator removes rearrangements among indistinguishable copies.
This is a multinomial coefficient.
More generally:
where:
19.9Circular permutations#
When only rotation is considered equivalent, arrange distinct objects around a circle:
Fix one object to remove rotational duplication.
If reflections are also considered identical, division by may be appropriate, provided the arrangements do not have special symmetry.
19.10Complementary counting#
Use:
This is particularly effective for phrases such as:
- at least one;
- none;
- not all;
- contains a repeated item;
- violates no restriction.
“At least one success” is usually easier as:
The same structural idea works in counting and probability.
19.11Stars and bars#
Count nonnegative integer solutions to:
Imagine identical stars separated into categories by bars.
There are:
positions containing stars and bars, so:
solutions.
Equivalent form:
For positive solutions:
give one item to every category first. The remaining total is , giving:
For lower bounds:
substitute:
so .
Upper bounds generally require inclusion-exclusion.
19.12Multisets#
Choosing items from categories with repetition allowed and order irrelevant is equivalent to:
with .
Thus:
This is combinations with repetition.
19.13Pigeonhole principle#
If objects are placed into boxes, at least one box contains at least:
objects.
To guarantee at least objects in one box, the maximum avoiding that outcome is:
so the guarantee threshold is:
The principle proves existence without identifying which box has the concentration.
19.14Inclusion-exclusion#
For two properties:
For three:
To count objects having none of several properties:
and evaluate “at least one” using inclusion-exclusion.
19.15Binomial theorem#
The coefficient of:
is:
Pascal’s identity:
Interpretation: count -element subsets according to whether they contain one designated element.
19.16Bit strings#
Number of bit strings of length :
Number containing exactly ones:
Number containing at most ones:
Number containing at least one :
Number with no consecutive ones is often modeled recursively: strings ending in may follow any valid shorter string, while strings ending in must have a preceding .
19.17Block method#
When designated objects must remain together, treat them as one block.
If must appear consecutively among other distinct objects:
- treat as one object;
- arrange that block with the others;
- multiply by the internal arrangements of .
If the internal order is fixed, omit the internal factorial.
19.18Gap method#
To prevent certain objects from being adjacent:
- arrange the unrestricted objects;
- identify gaps around and between them;
- place restricted objects into distinct gaps.
This is useful for “no two identical/category- objects adjacent.”
19.19Lexicographic order#
Lexicographic order compares sequences at their first differing position.
Next permutation#
Given an ordering:
- find the largest such that:
- find the largest such that:
- swap ;
- reverse the suffix after position .
If no such exists, the permutation is the last one.
Next -combination#
For:
from :
- find the rightmost with:
- increment ;
- reset every later entry to the smallest consecutive values.
20Discrete probability#
Probability assigns numerical weights to outcomes.
- Experiment: process producing an outcome.
- Outcome: one possible result.
- Sample space : set of all outcomes.
- Event: subset of .
For equally likely finite outcomes:
This ratio is invalid when outcomes are not equally likely.
Counting from the previous chapter supplies the numerator and denominator only when the individual outcomes are equally likely. For two fair dice, the 36 ordered pairs are equally likely; the possible sums 2 through 12 are not. Always identify the elementary outcomes before dividing counts.
20.1Probability axioms#
For pairwise disjoint events:
Consequences:
20.2Complement and unions#
Complement:
General addition rule:
If are mutually exclusive:
and:
20.3Conditional probability#
Suppose 30 of 100 devices are laptops, and 12 of those laptops are patched. Given that a chosen device is a laptop, only those 30 devices remain possible: the patched fraction is 12/30. The original population size 100 is no longer the denominator.
provided .
The condition becomes the new restricted sample space.
Rearranging gives the multiplication rule:
Also:
For a sequence of events:
On a probability tree:
- multiply along a path;
- add probabilities of disjoint successful paths.
20.4Independence#
Events are independent when:
Equivalent, when denominators are nonzero:
and:
Learning one event does not change the probability of the other.
Independence versus mutual exclusivity#
Mutually exclusive means:
If both events have positive probability, mutually exclusive events cannot be independent:
but:
Sampling with replacement is often independent. Sampling without replacement is usually dependent because probabilities change.
20.5Law of total probability#
If:
partition the sample space, then:
This adds every mutually exclusive route by which can occur.
20.6Bayes’ theorem#
Conceptually:
Bayes reverses a conditional.
Given:
- base rates ;
- likelihoods ;
- observed evidence ;
it finds:
The denominator is calculated using total probability.
Base rates matter. A highly accurate test can still produce many false positives when the condition tested is rare.
Bayes as a count. Suppose 10 of 1,000 devices are infected. A scanner flags 9 of those 10 and also flags 99 of the 990 clean devices. Among the 108 flagged devices, only 9 are infected, so P(infected | flagged) = 9/108 ≈ 8.3%. This is not the 90% detection rate: that rate answers P(flagged | infected), the reverse question. The total probability denominator counts all ways to get flagged.
21Random variables#
Toss two fair coins. The outcomes HH, HT, TH, TT each have probability 1/4. Let X count heads: its values are 2, 1, 1, 0. Thus P(X=1) = 1/2 because two different outcomes give that value. A random variable converts outcomes to numbers; its distribution groups and adds their probabilities.
A random variable is a function:
assigning a number to every outcome.
For a discrete random variable, the probability mass function is:
Requirements:
and:
21.1Expected value#
Expected value is a long-run probability-weighted average. It need not be a possible individual outcome.
For transformed values:
Linearity:
The second identity does not require independence.
For games, use net payoff:
and represent losses as negative.
A fair game has expected net value .
21.2Variance and standard deviation#
Variance measures squared deviation from the mean:
Computational form:
Standard deviation:
Scaling properties:
Adding a constant changes the mean but not variance.
For independent :
22Common discrete distributions#
A distribution is a reusable model for a random variable. Choose it from the experiment, not from the formula’s appearance: one success/failure trial, a fixed number of trials, trials until the first success, or a sample without replacement.
22.1Bernoulli#
A Bernoulli random variable represents one trial:
with:
Mean:
Variance:
22.2Binomial#
A binomial model requires:
- a fixed number of trials;
- two outcomes per trial;
- independent trials;
- constant success probability .
If counts successes:
Mean:
Variance:
“At least one” is:
22.3Geometric#
If counts the number of trials until the first success:
for .
Mean:
The geometric distribution is memoryless:
Previous failures do not alter the success probability of future independent trials.
22.4Hypergeometric#
Use the hypergeometric distribution for sampling without replacement.
Suppose:
- population size ;
- successful objects;
- sample size ;
- counts sampled successes.
Then:
This differs from binomial because the trials are dependent and the success probability changes.
23Models of computation#
| Computation can be represented as movement among states according to formal rules. First define the inputs: symbols form strings, and a language is the set of strings we want to accept. A machine then reads a string and decides whether it belongs to that set. |
23.1Alphabets, strings, and languages#
| An alphabet is a finite set of symbols. |
| For: |
| examples of strings include: |
| The empty string is: |
| with length: |
| String concatenation joins strings in order. |
| is the set of all finite strings over , including . |
| contains all nonempty finite strings. |
| A language is any set of strings: |
24Deterministic finite automata#
A DFA answers one question: is this string in the language? Imagine a light that remembers whether the number of 1s read so far is even or odd. Two states suffice because the exact count is irrelevant; only its parity affects the answer.
A DFA is a five-tuple:
where:
- : finite state set;
- : input alphabet;
- : transition function;
- : start state;
- : accepting states.
For every state and every input symbol, a DFA has exactly one next state.
24.1State diagrams#
- circles represent states;
- a free incoming arrow marks the start state;
- double circles mark accepting states;
- labeled arrows represent transitions.
The state is the machine’s entire memory.
24.2Tracing a DFA#
- begin at ;
- read the input from left to right;
- follow one transition per symbol;
- after consuming the entire string, inspect the final state;
- accept exactly when that state lies in .
Entering an accepting state before the input ends does not guarantee acceptance. Remaining symbols may lead elsewhere.
The empty string is accepted precisely when:
because no transitions are taken.
For the even-number-of-1s machine, start in the accepting even state. Reading 101 gives even → odd → odd → even, so it accepts. Reading 10 ends odd and rejects. The labels describe what the machine remembers, not which character it just read.
24.3Transition tables#
A table gives the same function as a state diagram:
| State | 0 | 1 |
|---|---|---|
Every row-symbol combination must contain exactly one destination in a DFA.
24.4State design patterns#
A state should represent exactly the finite information needed about the input read so far.
Even or odd parity#
Use two states:
- even number of s seen;
- odd number of s seen.
Reading switches states. Reading leaves the state unchanged.
Count modulo #
Use states representing residues:
Each new symbol updates the residue.
Has a symbol appeared?#
Use:
- “not yet seen”;
- “already seen.”
Ends with a pattern#
States represent the longest suffix of the input seen so far that is also a prefix of the target pattern.
Trap state#
A trap or sink state is a nonaccepting state whose transitions all return to itself.
Once entered, acceptance is impossible.
24.5Binary numbers modulo #
If a state represents the remainder of a binary prefix modulo , appending bit produces:
This is a common way to construct automata recognizing binary numbers divisible by .
25Nondeterministic finite automata#
Keep the same string and acceptance question, but allow several possible next states. Track all possibilities as a set, not as a guess about which branch is right. Subset construction turns that set into one ordinary DFA state.
An NFA may have:
- no transition for a state-symbol pair;
- one transition;
- several transitions;
- -transitions that consume no input.
Its transition function returns a set of states:
or, with epsilon transitions:
An NFA accepts a string when at least one possible path:
- consumes the full input;
- ends in an accepting state.
One failed branch does not cause rejection if another branch succeeds.
25.1Epsilon closure#
The -closure of a state set is every state reachable using zero or more -transitions.
When tracing an NFA with epsilon transitions:
- take the epsilon closure;
- consume the next symbol from every current state;
- take epsilon closure again;
- repeat.
25.2NFA-to-DFA subset construction#
NFAs and DFAs recognize exactly the same class of languages.
Convert an NFA to a DFA by making each DFA state represent a set of NFA states.
- The DFA start state is the NFA start-state epsilon closure.
- For each DFA state-set and input symbol, collect every reachable NFA state.
- Take epsilon closure.
- Treat the resulting set as one DFA state.
- A DFA state is accepting if its set contains any accepting NFA state.
An NFA with states may produce up to:
DFA states.
26Regular expressions and regular languages#
A state machine describes how to recognize strings. A regular expression describes how to build the same set of strings from alternatives, concatenation, and repetition. These are formal-language expressions; programming-library features such as backreferences can go beyond this model.
Regular-expression operations are:
26.1Union#
matches strings from or .
26.2Concatenation#
matches a string from followed by one from .
26.3Kleene star#
matches zero or more repetitions of .
26.4One or more#
matches one or more repetitions.
A language is regular when it can be recognized by a finite automaton. Equivalent representations include:
- DFA;
- NFA;
- regular expression.
Regular languages are closed under:
- union;
- intersection;
- complement;
- difference;
- concatenation;
- Kleene star;
- reversal.
27Limits of finite-state computation#
The parity machine works because many different prefixes can share one state: their relevant future behavior is identical. Exact unbounded counting cannot be compressed into finitely many such states. That is a memory limit, not a slow-algorithm problem.
A finite automaton has only finitely many memory states.
It can remember:
- parity;
- a remainder modulo a fixed integer;
- whether a pattern has occurred;
- a bounded suffix;
- any other finite classification.
It cannot remember an arbitrary unbounded integer exactly.
For example, the language:
requires remembering how many s occurred so the machine can verify exactly the same number of s. No finite automaton can do this for arbitrarily large .
A Turing machine adds an unbounded read-write tape and can perform computations beyond finite automata. The central distinction is memory:
- finite automaton: fixed finite memory;
- Turing machine: unbounded working memory in principle.
A language is decidable when some algorithm halts on every input and answers membership correctly.
28Moore and Mealy machines#
So far, a machine has reported acceptance after reading a string. Moore and Mealy machines instead attach outputs to its operation. Ask where the output label lives: on a state or on a transition.
Finite-state machines may also produce outputs.
A Moore machine associates output with the current state.
A Mealy machine associates output with transitions, depending on current state and input.
The recognition distinction is:
- Moore output changes after entering a state;
- Mealy output is generated while taking a transition.
The essential classification table#
Shared reference. This end matter covers C959 and C960 together and appears in both guides. Links into the other course open its guide.
| What the question says | What it is invoking |
|---|---|
| “ only if ” | |
| “ is necessary for ” | |
| “Not every ” | for which the property fails |
| “Some is ” | |
| Original implication rewritten equivalently | Contrapositive |
| Same truth column for every row | Logical equivalence |
| One counterexample | Disproves a universal claim |
| All subsets | Power set, |
| Every input gets one output | Function |
| No output is shared | Injective |
| Every codomain element is hit | Surjective |
| Inner matrix dimensions agree | Product exists |
| Pivot missing but no contradiction | Free variable, infinitely many solutions |
| Row | No solution |
| Constant difference | Arithmetic sequence |
| Constant ratio | Geometric sequence |
| Infinite geometric sum | Requires |
| Every diagonal relation pair exists | Reflexive |
| Reverse edge always exists | Symmetric |
| No distinct pair occurs both ways | Antisymmetric |
| Every two-step chain has shortcut | Transitive |
| Reflexive, symmetric, transitive | Equivalence relation |
| Reflexive, antisymmetric, transitive | Partial order |
| Uses every edge once | Euler |
| Visits every vertex once | Hamilton |
| Connected and acyclic | Tree |
| Loop variable doubles or halves | Logarithmic |
| Sequential blocks | Add, retain dominant term |
| Nested independent loops | Multiply iteration counts |
| Large modular power | Repeated squaring |
| Modular division | Find an inverse |
| Find modular inverse | Extended Euclidean algorithm |
| RSA private exponent | |
| Prove all integers from a base onward | Induction |
| Next case depends on several prior cases | Strong induction |
| Order matters | Permutation |
| Order does not matter | Combination |
| Unordered choice with repetition | Stars and bars |
| “At least one” | Complement is often easiest |
| “Given that” | Conditional probability |
| Reverse a conditional after observing evidence | Bayes |
| Fixed independent success trials | Binomial |
| Sampling without replacement | Hypergeometric |
| Weighted average result | Expected value |
| One next state per state-symbol pair | DFA |
| At least one successful computational path | NFA |
| Machine needs unbounded exact counting | Not finite-state |
Distinctions the exams can exploit#
Element versus subset#
says is an element.
says every element of set belongs to .
Empty set versus a set containing it#
Codomain versus range#
The codomain is declared. The range is actually reached.
Surjectivity means they are equal.
Converse versus contrapositive#
is equivalent to:
not to:
Symmetric versus antisymmetric#
Symmetric requires reverse pairs.
Antisymmetric forbids reverse pairs only for distinct elements.
They are not logical opposites.
Sequence versus series#
A sequence is a list:
A series is its sum:
Necessary divergence test#
proves diverges.
does not prove convergence.
Walk, trail, and path#
- walk: repetitions allowed;
- trail: no repeated edge;
- path: open walk with no repeated vertex;
- cycle: closed trail of length at least 1 whose only repeated vertex is its start and end.
Euler versus Hamilton#
- Euler concerns edges.
- Hamilton concerns vertices.
MST versus shortest-path tree#
An MST minimizes total selected edge weight.
Dijkstra minimizes source-to-vertex distances.
These objectives are not equivalent.
Big-O versus Theta#
Big-O is an upper bound.
Theta is a tight bound.
A function can have many valid Big-O bounds.
Modular inverse versus reciprocal#
There are no ordinary fractions modulo .
To divide by , multiply by , which exists only when:
Permutation versus combination#
Ask whether swapping selected objects creates a different outcome.
- yes: permutation;
- no: combination.
Mutually exclusive versus independent#
Mutually exclusive means they cannot occur together.
Independent means one does not affect the probability of the other.
Nontrivial mutually exclusive events are dependent.
Accepting state versus accepted string#
A finite automaton accepts only after consuming the entire string and ending in an accepting state.
Passing through one earlier is not enough.
Formulas to know cold#
Logic#
Sets and functions#
Number of functions :
Sequences#
Graphs and trees#
Full -ary tree:
Adjacency matrix powers, Boolean arithmetic: the entry is 1 exactly when a walk of length runs from to :
With ordinary arithmetic the same entry counts those walks.
Transitive closure on vertices, as graphs and as a Boolean matrix sum:
Counting#
for generalized pigeonhole occupancy.
Probability#
Number theory and RSA#
Complexity#
Exam preparation chiefly depends on recognizing which definition or mechanism a question invokes.