Interactive course · ~5 hours

Mathematics for Computer Science

Computer science uses mathematics to say exactly what a program may assume, what it must guarantee, how many possibilities exist, and how uncertain evidence should change a decision. You will prove claims, count and simulate chance, then build the language of sets, functions, relations, recurrences and graphs. Each lab asks for a prediction and then checks it against a construction or calculation.

Nothing here is quoted

Every number you will see was worked out while you watched. When a lab says a claim survived 40 tests and died on the 41st, it tested all forty-one. When it says two dice came up as a seven 1,663 times out of 10,000, it rolled them 10,000 times. The most important habit in this subject is refusing to believe a number until you know what produced it, so no number here asks you to.

What you need before you start

Adding, subtracting, multiplying and dividing. Fractions and percentages. And the idea that a letter can stand in for a number, so that x + 3 = 5 means x is 2. That is the whole list. No programming, no algebra beyond that letter, and no symbols you have not met: every symbol used here is introduced with real numbers first, and there is not a single one of those tall stretched capital letters anywhere in the course.

The steps

Step 1

What a proof is, and why examples are not one

Here is a sentence about numbers. Add up the first few odd numbers and you always get a square number. Check it: 1 is 1, which is 1 times 1. Then 1 + 3 is 4, which is 2 times 2. Then 1 + 3 + 5 is 9, which is 3 times 3. Three tries, three successes.

A sentence like that, one that is either true or false with nothing in between, is called a claim. This one is a claim about every whole number at once, and there is no last whole number, so there are infinitely many cases in it. You could test cases until you were old and never reach the end.

So testing has a strange shape. It can never finish the job of showing a claim is true. But it can finish the job of showing a claim is false, and it can do that in one go. A single case where the claim fails is called a counterexample and one counterexample is fatal. There is no arguing with it and no repairing the claim around it.

What counts as a whole number here

The whole numbers are 0, 1, 2, 3, 4 and onwards forever. No fractions, no decimals, nothing negative. When a claim in this course says "for every whole number n", it usually means the counting numbers 1, 2, 3 and up, and where 0 matters the claim will say so.

The letter n is a stand-in. Writing "n times n" means "pick any whole number you like, and multiply it by itself". It is exactly the x in x + 3 = 5, except that instead of one secret value to find, n is meant to be every value in turn.

What a prime number is, since the labs keep asking

One whole number divides another if it goes in exactly, leaving nothing over. 3 divides 12, because 12 is 3 fours. 5 does not divide 12, because 12 is two 5s with 2 left over. That leftover is called the remainder.

A prime number is a whole number above 1 that nothing divides except 1 and itself. 2, 3, 5, 7, 11 and 13 are prime. 9 is not, because 3 divides it. Primes are the numbers that cannot be broken into smaller factors, and they turn up in this course because claims about them are easy to state and surprisingly hard to settle.

Why can a computer not simply check them all

A program is a list of instructions a computer carries out in order. An algorithm is the method behind such a list: a recipe with steps definite enough that following it needs no judgement, and that always stops with an answer."Test n, then test n plus 1, forever" is a list of instructions, but it is not an algorithm, because it never stops.

So a computer can churn through cases faster than you can, which is a real help when hunting for a counterexample. It cannot turn checking into proving, because the supply of cases never runs out. A program that has tested a billion cases has tested none of the rest, and the rest is where every surviving surprise lives.

Lab 1 · Test a claim until it dies
Try this firstLeave the first claim selected and press Test 20 more twice. Twenty lines appear in the log each time, all of them ticks, and the counter says the claim has survived every test so far. Now press it once more and watch what happens around n = 40.
Notice how confident 40 successes feel. If you had stopped at 30 you would have written the claim down as a fact. The third claim in the chooser is the other half of the lesson: press Test 20 more on it as often as you like and it will never fail, because it happens to be true. The log looks identical to the first thirty lines of the first claim. Testing cannot tell those two situations apart, which is the entire reason proofs exist.
What a proof actually is

A proof is an argument that starts from things already agreed and reaches the claim by steps so small that nobody can object to one of them. It settles infinitely many cases without visiting them, because it never talks about a particular case. It talks about any case, using only what every case has in common.

The odd numbers claim has one. Lay n rows of dots to make a square of side n. To grow it to a square of side n plus 1 you add a strip down one side, a strip along the bottom, and one dot in the corner: that is n plus n plus 1 dots, which is the next odd number. So every square is the one before it plus an odd number, and starting from nothing, adding the first n odd numbers has to give the n-sided square. That paragraph covers every n there will ever be. Step 2 turns this style of argument into a machine.

Lab 2 · Hunt for the counterexample yourself
Try this firstPick the second claim, type 8 into the number box and press Try to break it. The claim says n times n plus 1 has no divisors except 1 and itself whenever n is even. 8 gives 65, and the lab will show you the two numbers that divide it. Then switch to the third claim and try to break that one for as long as your patience lasts.
The third claim is the interesting one. Every even number above 2 is the sum of two primes: 8 is 3 plus 5, 100 is 3 plus 97. Nobody has ever found an even number that breaks it, and computers have checked further than you can imagine. Nobody has ever proved it either. It has been an open question since 1742. Press Try 500 numbers for me and you will add 500 more successes to a pile that already proves nothing.
A friend has written a program that tested a claim about whole numbers for every value from 1 to one billion, and it held every time. What has the program established?
Only those billion values. The tempting answer is the first one, and the reason it is wrong is that "beyond reasonable doubt" is not a thing mathematics recognises. There are real claims that hold for every value a computer has ever reached and fail later. The second answer is a different mistake: the claim was about whole numbers, so fractions were never part of it.
Step 2

Dominoes, and the first big formula

Stand a long line of dominoes on end. You want every one of them to fall. You do not have to push each one, and you do not have to count them. Two facts are enough: the first one falls and every domino that falls knocks over the next. Together those two facts settle a line of any length, including one longer than you have ever seen.

That is the whole idea of induction. The first fact is called the base case. The second is called the step, and it is a promise about every position at once: whichever domino you name, if that one falls then the one after it falls too. Neither fact alone does anything. A first domino that falls into a gap knocks nothing over. A perfect line that nobody pushes stays standing forever.

Why proving "each one knocks the next" does not mean checking each one

Because the step is not a list of promises, it is one promise with a blank in it. You argue about a domino called number k without ever saying what k is, using only facts true of every position: the spacing is the same everywhere, the dominoes are the same size. If the argument uses nothing specific to k, it works for k equals 5 and for k equals five million, and you never wrote either number.

This is why induction feels like cheating the first time. You do a finite amount of work, two arguments, and walk away with infinitely many conclusions. The finite work covers the infinite collection because it was careful never to mention a particular member of it.

What"1 + 2 + ... + n" means

The three dots mean "keep going the same way". So 1 + 2 + ... + 6 means 1 + 2 + 3 + 4 + 5 + 6, which is 21. And 1 + 2 + ... + n means start at 1 and add every whole number in order until you have added n. If n is 4 the sum is 10. If n is 1 the sum is just 1, since you start and stop in the same place.

Nobody writes out a hundred terms. The dots are shorthand for a pattern the reader can continue, and the pattern has to be obvious from the terms shown, which is why sums like this are always written with at least the first two.

What if the step works but the first domino never falls

Then you have proved nothing, and you can prove nonsense. Take the claim "n equals n plus 1". The step is fine: if n equals n plus 1 then adding 1 to both sides gives n plus 1 equals n plus 2, which is the claim for the next value. Every domino would knock over the next one perfectly.

But 1 does not equal 2, so the first domino never falls, and the whole line stays standing. A step without a base case is a line of dominoes nobody pushed. The next lab lets you glue the first one down and watch exactly that happen.

Lab 3 · Break the line and see what survives
Try this firstPress Push the first one and watch all of them fall. Then press Stand them all up, click on domino number 9 to take it out of the line, and push again. The count underneath tells you how many fell and where the chain stopped.
Two ways to fail, and they look nothing alike. Removing a domino breaks the step, and everything past the gap survives. Pressing Glue the first one down breaks the base case, and nothing falls at all even though every link in the chain is perfect. When a proof by induction goes wrong, it has gone wrong in one of exactly these two ways, and the first thing to check is which.

Now use it on something worth proving. Add up 1 + 2 + ... + n. For n equal to 5 that is 15. There is a short formula that gives the answer for any n without adding anything up, and the picture below is where it comes from, so build the picture before you meet the formula.

Lab 4 · Count the dots, then write the rule
Try this firstSet the slider to 4 and press Add the second copy. A matching upside-down staircase in a second colour slots into the first, and the two together make a plain rectangle whose sides are labelled. Count the rectangle, then halve it. After that, type a rule into the box and press Check my rule.
The rule box is marked on behaviour, not on spelling. It runs whatever you typed for n = 1, 2, 3 and onwards up to 60, and compares each answer against a staircase it actually counts, dot by dot. Any rule that agrees every time passes, however you chose to write it. The rule it starts with is wrong on purpose, and pressing Check will tell you the first n where it disagrees and by how much.
The formula, and the induction proof of it

Two staircases make a rectangle n tall and n plus 1 wide, so one staircase is half of that. Written down: 1 + 2 + ... + n = n(n+1)/2. Writing two things side by side, as in n(n+1), means multiply them. For n = 4 that is 4 times 5 divided by 2, which is 10, and 1 + 2 + 3 + 4 is indeed 10.

The induction proof takes three lines. Base case: for n = 1 the sum is 1, and the formula gives 1 times 2 divided by 2, which is 1. Step: suppose the formula is right for some k, so 1 + 2 + ... + k is k(k+1)/2. Then the sum up to k plus 1 is that, plus k plus 1. Adding those gives (k+1)(k+2)/2, which is exactly the formula with k plus 1 in place of k. Base case, step, done, for every n forever.

Someone proves the step of an induction perfectly: whenever the claim holds for k, it holds for k plus 1. They forget to check the base case. Their claim happens to be false for every single whole number. Is their step wrong?
The step can be perfectly correct. A step says "if this, then that". It says nothing about whether "this" ever happens."n equals n plus 1" has a flawless step and is false for every n, because the promise is never triggered. That is precisely why the base case is a separate thing you must check and not a formality.
Step 3

The smallest counterexample, and a trap that springs shut

Sometimes one domino is not enough to knock over the next. Suppose a shop sells stamps in 3p and 5p only, and you claim every amount from 8p upwards can be made exactly. To make 20p you would reach for the answer to 17p and add a 3p stamp. The domino three places back is the one that helps, not the one immediately before.

So loosen the step. Instead of "if it works for k then it works for k plus 1", say "if it works for every value below k then it works for k". You are allowed to reach back as far as you like. That is called strong induction, and it needs no new faith: if the ordinary version knocks over every domino, so does a version that gets to lean on all of them.

Is strong induction really a different rule

No, and it is worth knowing why. Take the claim you actually care about and wrap it: instead of "the claim holds at n", prove "the claim holds at every value from the start up to n". That wrapped claim can be pushed along by ordinary induction one step at a time, because knowing it up to k is exactly the pile of facts a strong step wants.

So strong induction is ordinary induction wearing a coat. People use it because it saves the bookkeeping, not because it can reach anything the plain version cannot. This is safe to skip: nothing later depends on it.

Why "there is a smallest one" is worth stating out loud

Take any collection of whole numbers that is not empty. It has a smallest member. That sounds too obvious to name, so mathematics names it anyway: the well-ordering of the whole numbers.

It is worth naming because it stops being true almost immediately if you leave the whole numbers. The fractions between 0 and 1 have no smallest member: whatever tiny fraction you pick, half of it is smaller and still in the collection. The negative whole numbers have no smallest member either. So well-ordering is a real property of a particular collection, not a piece of common sense, and every argument in this step leans on it.

A strong induction worth seeing: every number is built from primes

Claim: every whole number above 1 is either prime, or a product of primes multiplied together. Suppose it were false. Then some number breaks it, so by well-ordering there is a smallest breaker. Call it m.

m is not prime, or it would satisfy the claim by itself. So m is a times b with both a and b bigger than 1 and smaller than m. Both are smaller than m, and m was the smallest breaker, so a and b both satisfy the claim: each is a product of primes. Multiply those two products together and you have m as a product of primes, which contradicts m being a breaker. So there is no smallest breaker, so there is no breaker.

Lab 5 · The stamp machine
Try this firstType 8 into the amount box and press Make it. The lab searches for a combination of 3p and 5p stamps that comes to exactly that and shows you which ones. Then press Show the chain down to a base case and watch it take 3 off the amount over and over until it lands somewhere it already knows.
Try 1, 2, 4 and 7. Those four amounts cannot be made at all, and the lab will say so after a real search rather than by looking them up. That is why the claim starts at 8 and why the strong induction needs three base cases and not one: the chain from any amount steps down by 3s, so it lands on 8, 9 or 10 depending on where it started, and all three have to be checked by hand. There is no marking in this lab. Poke at it.

Now the trap. Below is an argument by induction for something obviously false, and the argument looks airtight. Do not read ahead for the flaw. The lab draws the step for you at each size and the flaw is visible the moment the picture gets small enough.

Lab 6 · All crayons are the same colour
Try this firstPress the button marked 5 to predict that the argument breaks at five crayons, then press Show the argument. Two overlapping groups appear with the shared crayons marked, and a line of text counts them. Now walk the size slider down towards 2 and keep watching that count.
The overlap is the whole argument. The step says: drop the last crayon and the rest match, drop the first and the rest match, so everything matches because the two groups share members that force the colours to agree. With 5 crayons the groups share 3, and the reasoning holds. With 2 crayons the groups share nothing at all, so there is no crayon in both to pass the colour along, and the chain from 1 to 2 never happens. Every later step is fine and every later step is useless, because the domino they all depend on was never knocked over.
You want to prove a claim about every whole number from 8 upwards, and your step gets from k to k plus 3. How many base cases do you need to check by hand?
Three. A step of size 3 splits the numbers into three separate chains: 8, 11, 14 and onwards; 9, 12, 15 and onwards; 10, 13, 16 and onwards. Each chain needs its own push. Checking only 8 leaves two entire chains standing, which is the same failure as the crayons, just easier to see.
Step 4

And, or, not: logic you can toggle

Claims combine."It is raining and I have an umbrella" is built from two smaller claims, and whether the big one is true depends on nothing except whether each small one is true. That is what makes this mechanical enough for a machine.

Three combiners do most of the work. A and B is true only when both are. A or B is true when at least one is, including when both are, which is not how "or" behaves in a menu. not A is true exactly when A is false. Since each part is only ever true or false, you can list every possible situation in a small table and fill it in. That table is called a truth table.

A single true-or-false value is called a bit, and it is the smallest piece of information there is. Written down, a bit is usually 1 for true and 0 for false. Everything a computer stores, every number, letter, photograph and sound, is a pile of bits and every calculation it performs is these three combiners applied to them in enormous quantities.

Does "or" really include both

In this subject, yes, always."You may have tea or coffee" in ordinary speech usually means one or the other and not both. In logic,"A or B" is true in three of the four situations, and false only when both parts are false.

When someone means strictly one or the other, they say exclusive or and spell it out. The plain "or" is inclusive, and the reason is convenience: inclusive or obeys tidier rules and the exclusive version is easy to build out of the three combiners when you actually want it.

What "if A then B" means when A is false

Take the promise "if it rains, I will bring an umbrella". It is broken in exactly one situation: it rained and you did not bring one. If it did not rain, the promise is not broken whatever you did, because it never asked for anything.

So "if A then B" counts as true whenever A is false, which strikes everybody as odd the first time. "If the moon is cheese then I am a fish" is a true statement. It has to be, because a promise with a condition that never fires cannot have been broken. This is the same point the induction step made in Step 2, in different words.

Where De Morgan turns up when you are actually working

Search boxes and filters."Show me everything that is not (cheap and fast)" is the same set as "everything that is either expensive or slow". People get this wrong constantly, usually by turning the first into "not cheap and not fast", which is a much smaller set: it drops everything that is cheap but slow.

The same swap runs through hardware, where the two combiners are physical circuits, and through searching, where a filter is turned inside out to make it faster. Safe to skip, but once seen you will notice it every week.

Lab 7 · The toggle board
Try this firstPress the A button to turn A on, leaving B off. The result light and the sentence underneath change, and one row of the truth table lights up to show which situation you are in. Then work through the expression chooser, pressing every one of the six with A on and B off.
Four rows is the whole story for two inputs. The table is not a summary or a sample: those four rows are every situation that can ever occur, so an expression that agrees with another in all four rows is the same expression, permanently. That is a proof about infinitely many uses, obtained by checking four lines, and it is the only place in this course where checking every case is actually possible.
Lab 8 · Turn a claim inside out
Try this firstPress whichever of the four candidates you think matches not (A and B), then press Compare the two tables. Both tables are filled in row by row and every row is marked as agreeing or differing, with the first difference named in words underneath.
The two rules are worth memorising. Not (A and B) is the same as (not A) or (not B). Not (A or B) is the same as (not A) and (not B). Negating a combination flips every part and swaps and with or. They are called De Morgan's laws, after Augustus De Morgan, who wrote them down in the 1840s. Press Use three inputs and check them again on eight rows: the pattern does not care how many parts there are.
A shop's filter says "hide everything that is not (in stock and under £20)". A jumper is in stock and costs £45. Is it hidden?
Hidden."In stock and under £20" needs both, so it is false for a £45 jumper, so "not (that)" is true and the jumper goes. The second answer is the classic mistake: it reads the rule as "not in stock and not under £20", which is what you get by pushing the "not" inwards without the and-to-or swap. De Morgan is the correction.
Step 5

Counting without listing

A lunch is one sandwich and one drink. There are 3 sandwiches and 4 drinks. You could write out every lunch and count them, and for these numbers you should, because seeing the twelve is what makes the next sentence believable. Every sandwich pairs with every drink, so the count is 3 times 4.

That is the product rule: when a thing is built from independent choices made one after another, multiply the number of options at each choice. Beside it sits the sum rule: when a thing is one of several separate groups, add the sizes of the groups. The sum rule has a condition attached that people forget, and the first lab is mostly about that condition.

When do I multiply and when do I add

Read the description and look for the joining word."A sandwich and a drink" is two choices that both happen, so multiply."A sandwich or a soup" is one item drawn from two separate groups, so add. The word in the sentence is doing the arithmetic.

The trap is that adding is only correct if nothing sits in both groups. If three items appear on both the sandwich list and the soup list, adding the two lists counts those three twice, and the answer is the sum minus 3. Multiplying has its own condition: the number of drinks must not depend on which sandwich you picked.

What"2 to the power of n" means, with real numbers first

Two light switches, each up or down, give four arrangements: up-up, up-down, down-up, down-down. Add a third switch and each of those four splits in two, giving 8. A fourth gives 16, a fifth 32. Each new switch doubles the count, because every arrangement of the old switches survives twice, once with the new switch up and once with it down.

Multiplying n twos together is written 2 to the power of n, and in the labs here it is typed as power(2, n). So power(2, 3) is 2 times 2 times 2, which is 8, and power(2, 10) is 1024. The same shorthand works for any base: power(10, 3) is 1000. The one that surprises people is power(2, 0), which is 1, because zero switches still have exactly one arrangement, the empty one.

Why doubling is the shape that matters in computing

Because a computer's smallest choice is a bit, which has two settings. Everything is built by putting bits side by side, so the number of possibilities is always some number of twos multiplied together. Eight bits in a row is the usual bundle, and it has power(2, 8) settings, which is 256. That bundle of eight bits is called a byte. It is the unit files and memory are measured in.

Doubling gets out of hand fast, and that cuts both ways. Thirty bits already give more than a billion arrangements, which is why a password of decent length cannot be guessed by trying them all. Thirty items to arrange give a number with 33 digits, which is why some perfectly clear questions cannot be answered by a computer checking every case, no matter how fast it is.

Lab 9 · The lunch counter
Try this firstLeave the sliders at 3 sandwiches and 4 drinks and press List them all. Twelve lunches appear, actually written out, with the multiplication printed underneath. Then raise the drinks slider one notch at a time and watch the list and the product stay in step.
Now press Add a third choice and set desserts to 6. There are 72 lunches, the widget prints the first 60 and tells you it dropped 12, which is the moment the product rule stops being a convenience and starts being the only option. Then try the overlapping groups switch: it puts the same two items on both menus, and the honest count printed underneath comes out lower than the sum, by exactly the number of shared items.
Lab 10 · Switches, and the rule for them
Try this firstSet the slider to 3 switches and press Count them by listing. All eight arrangements are printed out and counted. Raise the slider to 4 and count again, then to 5, and see whether you can say what the count will be at 6 before you press the button.
The rule box is checked by listing, not by trusting. When you press Check, the lab builds every arrangement of n switches for n from 1 to 14 and counts them one at a time, then compares your rule against those counts. Fourteen switches is 16,384 arrangements, which is where the listing has to stop. Your rule, if it is right, does not have to stop anywhere, which is the point of having one.
A café offers 4 sandwiches and 3 soups. Two of the sandwiches are also sold as soups, and appear on both lists. How many different single items can you order?
Five. The sum rule needs the groups to be separate. Here two items sit in both, so 4 plus 3 counts them twice. Subtract the two duplicates: 7 minus 2 is 5. Twelve uses the product rule where it does not belong: you are choosing one item, not one sandwich and one soup.
Step 6

Arranging and choosing

Three tiles marked A, B and C. Line them up. The orders are ABC, ACB, BAC, BCA, CAB and CBA, so there are six. The product rule explains the six without listing them: three tiles could go first, then two are left for second place, then one for last, and 3 times 2 times 1 is 6.

Multiplying n down to 1 like that is called a factorial, written with an exclamation mark after the number. So 3 factorial is 6, 4 factorial is 24, and 5 factorial is 120. It is the number of ways to put n different things in order, and it grows faster than almost anything else in this course.

How fast does factorial actually grow

10 factorial is about 3.6 million. 13 factorial is over 6 billion. 20 factorial has 19 digits, and counting them at a billion per second would take about 77 years. 60 factorial is larger than the number of atoms anybody thinks exists.

This is why "just try every order and pick the best" is not a plan. A delivery van with 20 stops has 20 factorial routes. No faster computer rescues that, because doubling the speed of the machine buys you less than one extra stop. Problems shaped like this are the reason algorithms get invented.

Why choosing 2 people out of n means dividing by 2

Count handshakes at a party of 5. Pick the first person: 5 ways. Pick the second: 4 ways left. That is 20, but it is wrong, because picking Ana then Ben and picking Ben then Ana are the same handshake counted twice. So the answer is 20 divided by 2, which is 10.

The pattern is general. Whenever order does not matter, count as though it did and then divide by the number of orders you have overcounted by. For pairs that number is 2, because two things can be arranged in 2 factorial ways. For triples it is 6, because three things can be arranged in 3 factorial ways.

Why every number in Pascal's triangle is the two above it added

Write "n choose k" for the number of ways to pick k things out of n. Now single out one particular item, say the red one. Every selection either includes the red one or does not, and there is no third case, so add the two counts.

Selections that include the red one still need k minus 1 more items from the other n minus 1, and selections that leave it out need all k from the other n minus 1. Those two counts are exactly the two entries sitting above in the triangle. So the triangle is not a coincidence or a pattern somebody spotted: it is that one sentence, drawn.

Lab 11 · Every arrangement, written out
Try this firstSet the tiles slider to 3 and press List every arrangement. All six appear, with the running product 3 × 2 × 1 shown beside the count. Push the slider to 4, then 5, then 6, listing each time, and watch how quickly the box fills up.
Then set the second slider below the first. With 5 tiles and only 3 positions to fill, the count becomes 5 × 4 × 3, which is 60, and the listing shows why: the fourth and fifth tiles simply never get placed. Order still matters here, so ABC and CBA are both in the list. The next lab is the same question with order thrown away.
Lab 12 · Pascal's triangle, checked against reality
Try this firstClick the first 10 in the row that reads 1, 5, 10, 10, 5, 1. The two numbers above it that add up to it are marked, and underneath the lab writes out every actual way to choose 2 letters from 5, all ten of them. Then click a few other cells and watch the listing keep pace.
The listing is the check. Nothing in this lab reads the answer off the triangle. Clicking a cell sends the widget away to build every selection of that size from that many items and count them, and the number it comes back with is placed next to the triangle's number so you can see they agree. The rule box at the bottom asks for the count of pairs, which is the third column, and it is graded against those same real listings.
A class of 12 must send 3 people to a meeting. Nobody has a special role: the three are simply going. Which count is right?
Divide by 6. Choosing Ana, Ben and Cara in any of their six orders sends the same three people, so counting ordered picks overcounts by 3 factorial, which is 6. The answer is 220. The second option would be right if the three had distinct jobs, such as chair, note-taker and treasurer, because then the order would carry real information.
Step 7

Too many pigeons

Thirteen people are in a room. Two of them share a birth month. There is no need to ask anybody anything: there are twelve months and thirteen people, so somewhere two people have to land together. That is the pigeonhole principle, and stated plainly it is almost insulting. If you put more items than holes, some hole holds at least two items.

It earns its keep in a stronger form. Put 30 items into 4 holes and some hole holds at least 8, because if every hole held 7 or fewer the total could not pass 28. In general, some hole holds at least the total divided by the number of holes, rounded up. That is a guarantee with no cleverness in it, which is exactly what makes it useful: it holds however maliciously the items were placed.

What "at least" is really promising

"Some hole holds at least 8" does not say which hole, and does not say 8. It says there is a hole with 8 or more, and it refuses to say anything else. That vagueness is the source of its strength: the claim survives every arrangement, including the ones designed to break it.

The opposite mistake is common. Pigeonhole never says the items are spread evenly, and it never says two particular items collide. It says a collision exists somewhere. When you need to know where, you need a different argument.

Why no program can shrink every file

Suppose someone claims a program that makes every file smaller, and a matching program that puts each one back exactly. Count the files of exactly 10 bits: there are power(2, 10) of them, which is 1024. Every one of them has to come out shorter, so every one lands among the files of 9 bits or fewer, and there are only 1023 of those, counting the empty one.

1024 items, 1023 holes. Two different files must squash to the same thing, and then the program that puts them back cannot know which one it started from. So the claim is impossible, for every program, forever and the argument fits in a paragraph. Safe to skip, but it is the clearest example of a proof that rules out an entire industry of promises.

Reading a chance as a fraction, a decimal and a percentage

A probability is how often something happens out of all the equally likely possibilities. A fair die has 6 faces, and 2 of them are above 4, so the probability of rolling above 4 is 2 out of 6, which is the fraction 1/3, the decimal 0.333, and 33.3 percent. Those are three spellings of one number.

Probability 0 means it never happens and probability 1 means it always happens, and everything real sits between. The word "chance" is used here for the same thing. Nothing in this step needs more than that, and Step 8 builds the rest. Continue with Probability for Engineering for distributions, Monte Carlo simulation, reliability and quality assurance.

Lab 13 · Try to beat the guarantee
Try this firstLeave it at 7 items and 3 holes and click the holes to place items, spreading them as evenly as you can manage. A line above the holes says what the guarantee promises, and a line below says what your fullest hole actually holds. Try to get the second number below the first.
You cannot, and the lab says why after each placement. Seven items in three holes forces a hole with 3, because three holes of 2 hold only 6. Press Spread them evenly to let the widget try, and it lands on the guarantee exactly: the guarantee is not a loose bound but the best promise that survives every arrangement. Then raise the items to 30 with 4 holes and see the promise rise to 8.

Now a question where the pigeonhole answer is correct and useless. How many people must be in a room before two of them share a birthday? With 366 possible birthdays, pigeonhole guarantees it at 367 people. The real answer, if you only want it to be more likely than not, is far smaller, and most people guess badly.

Lab 14 · The birthday surprise
Try this firstPress one of the four guesses before you do anything else, then press Work it out for every group size. A curve is drawn from 2 people up to 100, the crossing point where the chance passes one half is marked, and your guess is placed on the same picture so you can see how far off it was.
How the curve is computed, since it is only multiplication. Line the people up. The second person misses the first's birthday with chance 364 out of 365. The third misses both with 363 out of 365. Multiply those fractions along the line and you have the chance that everybody misses everybody, and one minus that is the chance of a shared birthday. Drag the days in a year slider afterwards and watch the crossing point move: it tracks roughly the square root of the number of days, which is why 23 and 365 belong together. Nothing here is marked.
In a room of 23 people the chance that some pair shares a birthday is just over one half. What is the chance that somebody in that room shares your birthday?
About 1 in 16. The surprise comes from how many pairs there are: 23 people make 23 × 22 ÷ 2 = 253 pairs, and any one of them can do the job. Fixing your birthday throws away all but 22 of those pairs, and the chance drops to roughly 6 percent. The third answer is close in spirit but adds probabilities that overlap, which slightly overshoots.
Step 8

Predict, then run ten thousand

There are two ways to get a probability. You can work it out by counting the possibilities, which needs no equipment and gives an exact answer. Or you can do the thing thousands of times and count how often it happened, which needs no cleverness and gives an answer that wobbles. This step puts the two side by side and lets you watch them meet.

The vocabulary is small. One go is a trial. What comes out of a trial is an outcome. A question you can ask about the outcome, such as "was the total seven", is an event. When every outcome is equally likely, the probability of an event is the number of outcomes that satisfy it divided by the number of outcomes there are.

Why the measured bars never land exactly on the worked-out ones

Because 10,000 trials is a sample and not the whole story. Rolling two dice 10,000 times will give you around 1,667 sevens, but the exact count changes every run, and being off by 40 or 50 is completely ordinary. Nothing has gone wrong when that happens.

What does shrink is the error as a fraction. At 100 trials the measured share of sevens might be 12 percent or 21 percent. At 10,000 it will sit within a fraction of a percent of 16.67. The gap shrinks roughly in step with the square root of the number of trials, so getting the error ten times smaller costs a hundred times as many trials.

What "independent" means, and when it fails

Two things are independent when knowing one tells you nothing about the other. Two dice are independent: the first showing a 6 changes nothing about the second. That is what lets you multiply probabilities to get the chance of both.

Drawing two cards from one pack without putting the first back is not independent, because the first card changes what is left. Multiplying as though it were is one of the most common mistakes in the subject, and the whole of Step 9 is what happens when people ignore it.

Nine tails in a row. Is a head due now

No. The coin has no memory, no ledger and no sense of fairness. The next flip is a half, exactly as the first one was, and the nine tails before it are irrelevant to a piece of metal.

What confuses people is that the long-run share really does settle near one half. It settles by being swamped, not by being corrected. Nine extra tails is a large lead over ten flips and an invisible one over a million, so the average drifts back towards a half without anything ever pushing it there. Lab 16 shows this happening as a line on a chart.

Lab 15 · Predict, then run 10,000 trials
Try this firstWith two dice, the total selected, click the column you think comes up most often, drag the how often slider to your guess, then press Show the worked-out answer. Dashed lines appear on every column at the exact probability, counted from all 36 possible rolls. Only then press Run 10,000 trials and watch the solid bars climb.
Watch the biggest gap, not the bars. The readout tracks the largest distance between any measured bar and its dashed target, and it falls fast at first and then grudgingly. Somewhere around 500 trials the shape is already unmistakable, and the remaining 9,500 buy you two more decimal places. Then try the spinner, where you set the three wedge sizes yourself: nothing about this needs the outcomes to be equally likely, only that the worked-out numbers and the measured ones are computed the same way every time.
Lab 16 · One line, ten thousand flips
Try this firstPress Run 10,000 trials and keep your eye on the left-hand end of the line. It thrashes wildly for the first hundred trials and then calms down. The dashed level is the worked-out probability, and the line is the share measured so far.
Run it four or five times. Every run is a different line and every run ends up in the same narrow band, and the early wildness is never the same twice. That settling is called the law of large numbers, and it is a theorem rather than a hope. Notice what it does not promise: not that the count of heads and tails evens out, only that their share does. The gap in raw counts usually grows while the gap in shares shrinks.
You flip a fair coin 10,000 times and get 5,090 heads, so you are 90 ahead. You flip 10,000 more. What should you expect the total lead to be after 20,000 flips?
Around 90, plus a fresh wobble. The lead has no reason to shrink: coins do not remember. What shrinks is the lead as a share of the flips, from 0.9 percent to about 0.45 percent, because the same lead is divided by twice as many flips. The first answer is the gambler's fallacy in its most convincing costume.
Step 9

A positive test that means very little

A test for a rare illness catches 99 out of every 100 people who have it, and wrongly alarms only 1 healthy person in 100. Those are excellent numbers. You take the test and it comes back positive. Most people, including many who should know better, conclude that they are almost certainly ill.

They are wrong, and not slightly. The reason is that the test's accuracy is only half the story: the other half is how many people had the illness to begin with, which is called the base rate. When the illness is rare, the healthy are so numerous that even their 1 percent of false alarms outnumbers all the true catches.

Two different ways a test can be wrong

A false positive is an alarm on somebody healthy. A false negative is silence about somebody ill. They are separate numbers and improving one usually worsens the other, because a test made keener catches more of the ill and also startles at more of the healthy.

Which mistake matters more depends entirely on what happens next. For a cheap screening test followed by a careful second test, false alarms are tolerable and misses are not. For a test that triggers surgery, the trade runs the other way. There is no accuracy number that captures this, which is why one is never quoted alone.

What "the chance of A given B" means

It means: throw away everybody for whom B is false, and ask about A among those who are left. The chance that a person is ill is one question. The chance that a person is ill given that they tested positive is a different question, asked of a much smaller group.

Swapping the two is the mistake this whole step is about."99 percent of ill people test positive" and"99 percent of positive people are ill" are different sentences with different answers, and they are confused so often that the confusion has a name: the base rate fallacy.

Why a second test changes the picture so much

Because after the first positive you are no longer standing in the general population. You are standing in the group of people who tested positive, and in that group the illness is far more common than it was outside. The base rate for the second test is the answer from the first.

That is the whole of Bayes' rule in one sentence: evidence does not give you an answer, it updates the count you already had. Lab 18 does the second test on the same grid and you can watch the proportion jump.

Lab 17 · Ten thousand people, counted
Try this firstBefore touching the sliders, drag the my guess slider to the percentage of positive-testing people you think are actually ill, then press Fill the grid and count. Ten thousand squares are drawn, sorted into four groups, and the four counts are printed beside them along with your guess for comparison.
Now drag the illness slider up. At 100 ill people in 10,000 a positive result is a coin flip and no better. At 2,000 ill in 10,000 the same test, unchanged, becomes trustworthy. The test did not improve. The population changed, and that alone moved the answer from roughly 50 percent to roughly 96 percent. This is why the same test means one thing in a screening programme and something else entirely in a hospital ward.
Lab 18 · Test the positives again
Try this firstPress Run the second test. Everybody who tested negative the first time leaves the picture, the remaining group is re-tested with the same test, and the counts are printed again. Watch the "actually ill" share of the positives jump between the two rounds.
The second test is the same test. Nothing about it got better. What changed is who is taking it: a group in which the illness is now common rather than rare. Two independent positives from a mediocre test beat one positive from a superb one, and that is the practical lesson hiding inside the arithmetic. Press Back to one test and change the sliders to see how the jump depends on the starting rarity.
In a town of 10,000, exactly 100 people have an illness. A test catches 99 of those 100, and wrongly alarms 1 percent of the 9,900 healthy people. Roughly what share of the people who test positive actually have it?
About half. The test finds 99 of the 100 ill people, and 1 percent of 9,900 healthy people is another 99. So 198 people get an alarm and 99 of them are ill. The second answer confuses "the chance of a positive given illness" with "the chance of illness given a positive". The third forgets that testing positive is information, and moves you off the base rate.
Step 10

The long-run average, and the spread

A game: roll one fair die and win that many pounds. What is it worth to play? Add the six payouts and share them out evenly. 1 + 2 + 3 + 4 + 5 + 6 is 21, and 21 divided by 6 is 3.5. Play the game a thousand times and your total will be close to 3,500.

That 3.5 is the expected value, and the name is misleading because you should never expect it: no roll of a die pays 3.5. It is what the average payout settles on over many plays. When the outcomes are not equally likely you weight them, multiplying each payout by how often it happens and adding those up. A game paying £10 one time in four and nothing otherwise is worth 10 times 1/4, which is £2.50.

How can the average be a value that never occurs

The same way the average household can have 1.7 children. An average is a summary of a pile of numbers, and there is no rule that a summary must be one of the things it summarises. 3.5 is the balance point of the six faces, the place where the die's payouts would balance on a see-saw.

This matters when the average is used to make a decision."The expected wait is 4 minutes" is compatible with everybody waiting either 30 seconds or 20 minutes and nobody ever waiting 4. The average alone cannot tell you which world you are in, and that is what the second half of this step is for.

What a square root is, since the spread needs one

Squaring a number means multiplying it by itself: 5 squared is 25. The square root undoes that: the square root of 25 is 5, because 5 is the number that gives 25 when squared. The square root of 9 is 3, of 100 is 10, of 2 is about 1.414.

It appears here because the natural measure of spread is built from squared distances, which come out in the wrong units. Squaring pounds gives square pounds, which mean nothing, so taking the square root at the end brings the answer back to pounds where it can be compared with the payouts.

Why the average of n dice is just n times 3.5

Averages add, always, even when the things being averaged interfere with each other. The average total of two dice is 3.5 plus 3.5, which is 7, and you do not need to look at the 36 combinations to know that. This is called linearity of expectation and it is the single most useful fact in the subject.

What makes it surprising is that it does not need the parts to be independent. The average number of people who get their own hat back from a shuffled pile is 1, no matter how many people there are, and it is proved by adding n averages of 1/n each, despite the hats being tangled together in an unpleasant way. Safe to skip; nothing later needs it.

Lab 19 · Set the payouts, then play ten thousand times
Try this firstLeave the four payouts as they are and press Work out the average. Each payout is multiplied by its share and the products are added in front of you. Then press Play 10,000 times and watch the running average wander towards that number.
Now press Make payout 4 rare. It sets that payout to £500 with a relative share of 0.009, about one play in a thousand. The worked-out average stays in the same few pounds, but the running average jumps whenever the rare payout lands and wanders several times farther than the ordinary game after 10,000 plays. A long-run average is only useful when your run is long enough for the rare outcomes that shape it.
Lab 20 · Four games, one average
Try this firstPress Play 10,000 of each. Four histograms are drawn side by side, one per game, and a table underneath gives each game's worked-out average, its spread, and how often it finished within £1 of the average.
All four games have an average of exactly £3.50. One pays £3.50 every time. One pays nothing or £7. One is the die. One pays nothing almost always and £3,500 once in a thousand. An average alone cannot tell them apart, so a second number is needed. Take each result's distance from the average, square it, average those squares: that is the variance. Take its square root and you have the standard deviation, a typical distance from the average, measured in pounds. It is the column that separates the four games at a glance.
Two delivery routes both have an average time of 30 minutes. Route A is always between 28 and 32. Route B is 10 minutes on most days and 90 minutes when the bridge is up. You must not be late for a 40-minute deadline. Which route, and what decided it?
Route A. Equal averages, and the decision has nothing to do with the average. A deadline is a question about the tail, and B's tail runs 50 minutes past it. B being quicker on a typical day is exactly the trap: a typical day is not what a deadline asks about. Step 11 is about putting numbers on tails like B's.
Step 11

Fencing in the bad case

Suppose all you know about a delivery time is that it averages 30 minutes and is never negative. Nothing else. Can you say anything about how often it exceeds 90? You can: it happens at most one time in three. If it happened more often than that, those long deliveries alone would drag the average above 30, and nothing else can pull it back down because no delivery takes negative time.

That is Markov's inequality. The chance of landing at or above some threshold is at most the average divided by the threshold. With an average of 30 and a threshold of 90, that is 30 divided by 90, which is one third. It asks almost nothing of you and gives back a real guarantee, and its weakness is that the guarantee is usually far looser than the truth.

Why Markov insists on nothing being negative

Because the argument is "those big values on their own already account for the whole average". If other values are allowed to be negative, they can cancel the big ones out, and the average stops being evidence about them.

A quick example. Half the time you win 1,000 and half the time you lose 1,000, so the average is 0. Markov with a threshold of 10 would claim the chance of reaching 10 is at most 0 divided by 10, which is zero, and yet it happens half the time. Delivery times, queue lengths and counts of things are all safely non-negative, which is why the inequality is useful in practice.

Is a loose bound worth anything

Often, yes, because of what it costs. Markov needs one number, the average, and no assumption about the shape of anything. A bound that holds for every possible shape has to be loose for most of them: it is being honest about how little it was told.

Give it a second number and it tightens sharply, which is what Chebyshev's inequality does. In practice these bounds are used to prove that something is rare enough to ignore, and "at most one in a million" is a satisfying answer even when the truth is one in a billion.

Which situations make Markov exactly right

The ones with nothing in the middle. If a payout is either 0 or exactly the threshold, and nothing else, then Markov's fence sits precisely on the truth. Average 30 with a threshold of 90 is achieved by paying 90 one time in three and 0 otherwise and the bound of one third is then exact.

This is worth knowing because it explains why the bound cannot be improved in general. Any sharper rule using only the average would be false for that distribution. The bound is loose for your case because your case is nicer than the worst one, and the bound was not told which case it had. The lab lets you build this exact distribution and watch the fence land on the truth.

Lab 21 · Markov's fence against the truth
Try this firstLeave one fair die selected, drag the threshold to 5 and press Work out both numbers. Two bars appear: the fence, worked out as the average divided by the threshold, and the truth, counted from the six faces. Read how far apart they are, then try thresholds of 2, 3, 4 and 6.
Then choose the worst case from the list. That distribution pays nothing most of the time and exactly the threshold occasionally, and the two bars land on top of each other. Every other choice leaves a gap, and the gap is the price of a guarantee that had to survive this one too. Notice the fence never dips below the truth, whatever you select: a bound that could be wrong would not be a bound.
Lab 22 · Two fences, one truth
Try this firstChoose ten dice added up, set k to 2, and press Compare the fences. Three bars are drawn: Markov's fence, Chebyshev's fence, and the counted truth. Chebyshev's should be dramatically tighter, and the numbers beside the bars say by how much.
Chebyshev's inequality in words. The chance of being at least k standard deviations away from the average, in either direction, is at most 1 divided by k times k. For k = 2 that is at most 1 in 4; for k = 3, at most 1 in 9; for k = 10, at most 1 in 100. It knows the spread as well as the average, and that second number is what buys the tighter fence. Both fences are still guarantees rather than predictions, and the counted truth is usually far inside them.
A queue's length averages 4 people and is never negative. Someone claims the queue reaches 40 or more on 15 percent of days. What can you say without any other information?
Impossible. Markov puts a ceiling of 4 ÷ 40 = 0.1 on it, so 15 percent cannot happen. This is the useful direction of a loose bound: it rarely tells you what is true, but it regularly tells you that something claimed is false, using one number and no assumptions.
Step 12

The drunk walker, and the long run

Stand on a line. Flip a coin: heads you step right, tails you step left. Flip a hundred times. Where do you end up? On average, exactly where you started, because left and right cancel. And yet you are almost never at the start, because "on average zero" is a statement about the balance of a crowd of possible walks, not about any particular one.

A more useful quantity is the typical distance from the start. It grows like the square root of the number of steps. Four times as many steps takes you twice as far. A hundred steps puts you around ten paces out, and ten thousand steps puts you around a hundred, not ten thousand.

How can the average position be zero when the walker is never there

Because positive and negative positions cancel when averaged. For every walk that ends 12 paces right there is an equally likely mirror-image walk ending 12 paces left, and averaged over the pair they contribute nothing. The average is exactly 0 and almost nobody is standing there.

The fix is to stop letting the signs cancel. Square the position first, so left and right both count as positive, average those squares, and take the square root at the end. That is the same repair as the standard deviation in Step 10, applied to the same problem.

What "the long run" does and does not promise

It promises that shares settle. It does not promise that a walker returns to the start, that a run of bad luck is repaid, or that anything is due. On a line with no walls, a walker does come back to the start eventually with certainty, which is a real theorem, but the average wait for that return is infinite, which makes it useless as a plan.

Add a wall and the picture changes completely. A gambler with £10 playing a fair game against a casino with millions will hit zero and stop, not because the game is unfair but because one side runs out first. Lab 24 has a wall you can switch on.

Where random walks turn up in computing

Shuffling a pack by repeated small swaps is a walk through the arrangements, and the question "how many swaps until it is properly mixed" is a walk question. Spreading web requests across servers at random is a walk in the queue lengths and the square root law is what says the imbalance stays modest. Estimating a quantity by taking random samples is a walk in the running estimate and the square root is why a hundred times as many samples buys only ten times the accuracy.

The same shape also runs through physics, where it describes a dust speck jostled by air molecules, and finance, where it is the starting model for a price. Safe to skip; nothing later depends on it.

Lab 23 · One walker, then two thousand
Try this firstPress Take one step six or seven times. The walker's path is drawn a step at a time with the position printed beside it. Then press Run 2,000 walkers to replace the single path with the whole crowd's final positions, and read the three numbers underneath.
The three numbers are the point of the lab. The average final position sits near zero and jiggles about. The average distance from the start, ignoring direction, sits near the square root of the number of steps. And the average of the position multiplied by itself sits near the number of steps exactly, which is the cleanest of the three and the one the rule box asks you for. Squaring is what stops the left-hand walkers cancelling the right-hand ones.
Lab 24 · Sandbox: let them run
Try this firstPress Let them go with everything as it is. A crowd of walkers spreads out from the middle and the readouts update as they move. Then push the chance of going right slider to 0.55 and let them go again, and see how little it takes to turn a spreading cloud into a moving one.
Nothing here is marked and nothing is being asked. Switch the wall on and watch the crowd thin out as walkers hit it and stop. Set the chance to exactly 0.5 with a wall at 10 and see that a fair game still loses everybody eventually. Set 5,000 steps with no wall and check the square root law by eye: the spread should be about 70, not 5,000. Then set the chance to 0.45 and watch how completely a small bias beats a large amount of luck.
A fair coin is flipped 10,000 times instead of 100. How does the typical size of the lead of heads over tails change?
About ten times bigger. The lead is a random walk, so it grows like the square root of the flips: a hundredfold increase in flips gives a tenfold increase in the typical lead, from around 10 to around 100. And yet the lead as a share of the flips falls from about 10 percent to about 1 percent. Both statements are true at once, and mixing them up is the source of most confusion about luck.
Next: structure

Probability describes uncertainty. The next part returns to exact objects: sets, mappings, relations and recursive definitions. Those are the pieces used to specify data structures and algorithms without relying on an example input.

Step 13

Sets collect things; functions connect them

A set is a collection where membership matters and order does not. The set {red, blue} is the same as {blue, red}, and writing red twice does not make a new member. The empty set has no members. A set may contain numbers, strings, pixels, users, program states or other sets.

The union A ∪ B contains anything in A or B. The intersection A ∩ B contains only members in both. The difference A \ B keeps members of A that are not in B. A is a subset of B when every member of A is also a member of B. These operations are how database filters and access rules combine.

A function assigns exactly one output to each allowed input. Different inputs may share an output. An injective function does not share outputs; a surjective function reaches every output in its stated codomain; a bijection does both and pairs the two sets perfectly. Always write the domain and codomain, because the same formula can be surjective under one codomain and not another.

Sets are not lists or bags

A list has positions, so [red, blue] differs from [blue, red]. A bag, also called a multiset, keeps counts, so two red marbles differ from one. Converting either to a set deliberately forgets some information. Ask whether that loss is allowed before using a set.

Lab 25 · Operate on two sets
Try this firstSelect intersection. Compare the two input sets with the highlighted result, then try union, difference and symmetric difference.
The universe matters for complements. “Not in A” means members of a stated universe that are outside A; it does not mean every imaginable object.
Lab 26 · Inspect a mapping
Try this firstChoose bijection. Every input should have one arrow, every output one incoming arrow. Then break each property separately.
Totality comes first. A diagram with an input that has no output is not a total function on that domain, even if its other arrows look sensible.
A function maps four students to three lockers. What must be true?
Four inputs cannot fit injectively into three outputs. This is the pigeonhole principle stated as a fact about functions.
Step 14

Every and some change the job of a proof

The symbol ∀ means “for every” and ∃ means “there exists”. To prove ∀x P(x), take an arbitrary allowed x and show P(x). To disprove it, one counterexample is enough. To prove ∃x P(x), provide a witness. To disprove it, show every allowed x fails.

Order matters. “For every user there exists a password they remember” allows a different password for each user. “There exists a password every user remembers” asks for one shared password. Swapping ∀ and ∃ changes the claim, even though the same words and variables appear.

An implication P → Q promises Q only when P is true. Its contrapositive, not Q → not P, is logically equivalent and can be easier to prove. The converse Q → P is a different claim. Proof by contradiction assumes the target is false and derives an impossibility.

How negation crosses a quantifier

Not every item passed means at least one item failed: ¬∀x P(x) is ∃x ¬P(x). No item passed means every item failed: ¬∃x P(x) is ∀x ¬P(x). The quantifier flips and the predicate is negated.

Lab 27 · Find a witness or counterexample
Try this firstChoose every number is even. The finite universe is checked one member at a time. Then switch to an existence claim.
A finite check is a proof only for that finite universe. It does not prove a statement about all whole numbers.
Lab 28 · Choose the proof direction
Try this firstSelect “n² is even implies n is even”. Compare a direct route, its contrapositive and the unrelated converse.
Equivalent does not mean identical wording. A contrapositive proves the original implication; a converse needs its own proof.
What is the negation of “every server replied”?
One missing reply is enough. Negating “every” produces “there exists one that does not”.
Step 15

Relations describe sameness and order

A binary relation records which ordered pairs are connected. Equality, less-than, divides, “has the same remainder modulo 3”, and “can reach in a graph” are relations. A table or directed graph can show every pair when the set is small.

A relation is reflexive if x relates to itself, symmetric if xRy gives yRx, and transitive if xRy and yRz give xRz. An equivalence relation has all three properties and splits a set into disjoint equivalence classes. Congruence modulo k is the standard computing example.

A partial order is reflexive, antisymmetric and transitive. Some pairs may be incomparable. A build dependency, subset relation or divisibility order is partial; ordinary ≤ on numbers is total. A Hasse diagram removes self-loops and edges already implied by transitivity.

Closures add the missing property

A transitive closure adds xRz whenever a path of relation steps connects x to z. Reachability is the transitive closure of one-step graph edges. Reflexive and symmetric closures similarly add self-pairs or reverse pairs. The closure is the smallest enlarged relation with the requested property.

Lab 29 · Test relation properties
Try this firstChoose “same parity”. Inspect the pairs and see why it forms equivalence classes. Compare ≤ and “is a parent of”.
One failed pair defeats a property. The lab names the exact witness instead of relying on the shape of the picture.
Lab 30 · Read a partial order
Try this firstSelect divisibility. Follow cover edges upward and identify incomparable values, minimal elements and maximal elements.
Minimal is not always minimum. A partial order can have several minimal elements and no single element below everything.
Why is “is a prerequisite of” usually a partial order rather than a total order?
Independent courses need no order. A partial order permits incomparable pairs.
Step 16

A recurrence defines a value from smaller values

A recurrence has base cases and a rule for larger inputs. Factorial says 0! = 1 and n! = n(n-1)!. Fibonacci says F₀ = 0, F₁ = 1 and Fₙ = Fₙ₋₁ + Fₙ₋₂. Without enough base cases, the rule never reaches a known value.

Algorithm running times use the same language. T(n)=T(n-1)+n describes one smaller recursive call plus a linear amount of work and sums to Θ(n²). T(n)=2T(n/2)+n describes two half-size calls plus a linear combine and forms Θ(n log n) work across logarithmically many levels.

Three ways to solve or bound a recurrence are useful: expand a few levels and spot a sum, draw a recursion tree, or guess a bound and prove it by induction. The Master theorem covers regular forms T(n)=aT(n/b)+f(n), but not every recurrence fits its conditions.

Memoisation changes repeated recursion

The direct Fibonacci program recomputes the same F values many times and takes exponential work. Storing each answer makes every state run once, giving linear work. The mathematical recurrence for the value is unchanged; the running-time recurrence changes because repeated subproblems disappear.

Lab 31 · Expand a running-time recurrence
Try this firstMove n through powers of two. Compare a shrinking chain, a balanced split and memoised Fibonacci.
Count work across a level and count levels. Multiplying those two quantities explains n log n without memorising a slogan.
Lab 32 · Compare a recursion tree
Try this firstSelect merge sort. The level totals stay at n until the leaves. Then compare binary search and a quadratic combine.
A theorem is a shortcut after the model is correct. State a, b and f(n) before applying any Master-theorem case.
Why does T(n)=2T(n/2)+n have n log n work?
Each level totals n. Halving reaches the base case after about log₂n levels.
Step 17

Events can be independent, dependent or merely uncorrelated

Events A and B are independent when P(A and B)=P(A)P(B). Learning A then does not change the chance of B. Drawing two cards without replacement is dependent because the first draw changes the deck. Drawing with replacement restores the original distribution.

For numerical random variables, covariance records whether deviations from the two means tend to have the same sign. Correlation divides covariance by both standard deviations, putting it between -1 and 1. Correlation measures linear association. It does not prove that one variable causes the other.

Zero correlation does not always mean independence. If X is equally likely to be -1, 0 or 1 and Y=X², the positive and negative linear effects cancel, yet knowing X determines Y. Independence is the stronger statement about the whole joint distribution.

Expectation still adds without independence

E[X+Y]=E[X]+E[Y] whether or not X and Y are independent. Variance is different: Var(X+Y) also has a covariance term. Independence makes that term zero, but simply omitting it from dependent variables understates or overstates the spread.

Lab 33 · Compare joint probabilities
Try this firstSelect two dice. Compare P(A and B) with P(A)P(B), then remove a card without replacement.
Conditional independence needs its condition named. Two symptoms may be related overall but independent after conditioning on the disease that causes both.
Lab 34 · Change a paired data pattern
Try this firstChoose positive association. Compare covariance, correlation and a curved dependence whose correlation is zero.
Plot the pairs. One summary number can miss curves, clusters, outliers and changes in spread.
Two variables have correlation zero. What may you conclude?
Correlation sees a linear pattern. Independence rules out every kind of statistical dependence.
Step 18

Graph invariants survive every legal move

A graph has vertices and edges. Edges may be directed, undirected, weighted or repeated, and loops may or may not be allowed. State the graph model first. A route planner, dependency checker and social network may all use graphs while asking different questions.

The degree of an undirected vertex is the number of incident edge ends. Adding all degrees counts every edge twice, so the sum of degrees is 2|E| and the number of odd-degree vertices is even. This invariant proves some requested graphs or routes cannot exist.

An Euler trail uses every edge once. A connected undirected graph has an Euler circuit when every degree is even, and an open Euler trail when exactly two degrees are odd. This is different from a Hamiltonian path, which visits every vertex once and has no equally simple degree test.

Trees have several equivalent signatures

A finite undirected graph is a tree exactly when it is connected and has |V|-1 edges. Equivalently, it has no cycle and |V|-1 edges, or there is exactly one simple path between every two vertices. These equivalent views support different proofs and algorithms.

Lab 35 · Check the handshake invariant
Try this firstSelect the path graph. Add its degrees and compare the sum with twice the edge count.
The result is structural, not experimental. Each undirected edge supplies exactly two ends, whatever the drawing looks like.
Lab 36 · Decide whether an Euler walk exists
Try this firstChoose exactly two odd vertices. The trail must start at one and end at the other. Compare all-even and four-odd cases.
Connectivity is still required. Correct degree parity cannot join two disconnected components.
Can an undirected graph have exactly three odd-degree vertices?
No. A sum of an odd number of odd values is odd, but the degree sum equals 2|E| and is even.

What you can do now

  • Build and criticise proofs using examples, counterexamples, induction, contradiction and contrapositive.
  • Use sets, functions, quantifiers, equivalence relations and partial orders to specify a problem precisely.
  • Count choices and arrangements, solve common recurrences, and use invariants to prove impossibility.
  • Compute probabilities, update on evidence, distinguish dependence from correlation, and report spread and tail risk.
  • Connect the mathematics to Introduction to Algorithms, Data Structures, Graph Algorithms, Arithmetic Algorithms, and Training That Works.