Logic from Switches
How do switches compute, and how many gates does a function need?
The part opens with Shannon's 1937 master's thesis: switches in series compute AND, switches in parallel compute OR, so a relay circuit is a Boolean expression and Boole's 1854 algebra simplifies it. The transistor replaces the relay, and the CMOS inverter's transfer curve, computed from square-law transistors, shows why a chain of gates restores a sloppy signal. NAND alone builds NOT, AND and OR, and so every truth table by its disjunctive normal form; an exhaustive search finds XOR in four NANDs. Karnaugh maps and Quine-McCluskey shrink the normal form, multiplexers turn a truth table into a lookup table, and decision diagrams give a canonical form whose size depends on the variable order. Then the part turns to cost: Shannon's 1949 count shows almost every function needs about 2^n / n gates, while the best bound proved for any explicit function is linear. It ends with the series' netlist simulator, the blocks Pebble needs, and the exact minimum circuits of every 3-input function.
What you need. Truth tables and proof by cases from Part 2. No electronics is assumed: the transistor is treated as a voltage-controlled switch.
- Mathematics, ideas and history
- Boole, Shannon 1937, CMOS, NAND completeness, Post's lattice, normal forms, BDDs, Shannon's counting bound
- What we build or compute
- the series' gate-level simulator; verified blocks
What you will be able to do
Degree
- Translate between a truth table, a Boolean expression and a circuit of gates.
- Build NOT, AND, OR and XOR from NAND gates and explain why that makes NAND complete.
- Minimize a four-variable function with a Karnaugh map and find a circuit's critical path.
Graduate
- Apply Post's five closed classes to decide whether a set of gates is complete.
- Build a reduced ordered decision diagram and show a function whose size depends exponentially on the order.
- Reproduce Shannon's counting argument that almost all functions need about 2^n / n gates.
Research
- Explain gate elimination and why it has only produced linear lower bounds for explicit functions.
- State the Minimum Circuit Size Problem and what is known about its hardness.
Industry
- Describe a circuit as a netlist, simulate it bit-parallel and verify it on every input.
- Explain how an FPGA's lookup table implements any small function, and what synthesis tools minimize.
Contents
Each chapter has a home level. Choose a track to see what to read and watch: Degree 33 min · Graduate 48 min · Research 52 min · Industry 35 min.
- 0A thesis about switchesDegree2 min
- 1Boole's algebraDegree3 min
- 2Circuits are expressionsDegree3 min
- 3The transistorDegree4 min
- 4CMOS gatesDegree3 min
- 5One gate is enoughDegree3 min
- 6Normal forms and mapsDegree3 min
- 7Choosing with gatesDegree3 min
- 8Decision diagramsGraduate3 min
- 9How many gates?Graduate4 min
- 10Gates take timeDegree3 min
- 11The blocks Pebble needsGraduate3 min
- 12Our hardware layerIndustry3 min
- 13Machines of switchesDegree3 min
- 14Gates that forget nothingGraduate2 min
- 15Frontier: the smallest circuitResearch5 min
- Recap, problems, and where this comes backAll tracks2 min
Also on this page: Lecture · Key results · Try it · Lab · Problems · Notes and sources · 中文 · Build the film.
Lecture
The text of each chapter is the film's narration, as it is spoken, so you can read along or revise without the film. The pictures are in the film.
A thesis about switchesDegree2 min
In 1937 a twenty-one-year-old student at MIT, Claude Shannon, was looking after a room-sized machine built of gears, motors and hundreds of telephone relays, Vannevar Bush's differential analyzer. Designing relay circuits then was an art, done by trial and error. Shannon noticed that it did not have to be. The algebra George Boole had invented in 1854 to describe the laws of thought described these circuits exactly. His master's thesis on the idea has been called possibly the most important master's thesis of the century. It is the reason every computer since has been designed with algebra.
Here is his observation, in its simplest form. A battery, a lamp, and two switches, A and B, one after the other. Current flows, and the lamp lights, only if A is closed and B is closed. Try all four settings. The table is Boole's and: switches in series compute A and B.
Now put the two switches side by side, so the current has two ways through. The lamp lights if A is closed, or B is, or both. Switches in parallel compute A or B. And a switch that opens when you push it, instead of closing, computes not. And with and, or and not, as chapter five will prove, you can build any truth table at all.
There is one more ingredient, and it is what makes a machine possible. In a relay, the switch is not pushed by a finger. A current through a coil makes a magnet, and the magnet pulls the contact closed. So the output of one switching circuit can work the switches of the next. Expressions can be plugged into expressions, without limit. Relays gave way to vacuum tubes and then to transistors, a billion times faster and a billion times smaller, but the idea in Shannon's thesis did not change at all. This part builds logic up from that single idea, all the way to the circuits Pebble will need.
1Boole's algebraDegree3 min
George Boole was a self-taught schoolmaster who became a professor in Cork. In 1854 he published An Investigation of the Laws of Thought, and its idea was audacious: reasoning is a kind of algebra. A variable stands for a statement, and takes the value one for true or zero for false. Multiplication is and, addition is or, and a bar is not. His favourite law was x squared equals x: saying something twice is the same as saying it once, which is false for ordinary numbers but true for zero and one. Engineers still use his notation.
Boole's algebra obeys a short list of laws, and they come in pairs. Identity, annihilation, idempotence, complement: each has a version for and and a version for or. Commutativity, distributivity, absorption, and De Morgan's laws from Part 2. Every law on the left turns into the one on the right if you swap and with or, and zero with one. That is the principle of duality, and in chapter four it will reappear in silicon. One law has no counterpart in ordinary arithmetic: or distributes over and. x plus y z equals x plus y, times x plus z. With numbers that is false. Here it is true.
A picture makes it believable. Draw x, y and z as overlapping regions, true inside and false outside. On the left, y and z is the region inside both; add x, and you get everything in x, plus that lens. On the right, x or y is one big region, x or z another, and their and is where they overlap. The same shape. Every law can be checked like this, or by a truth table with eight rows, and that is the difference between Boole's algebra and ours: there are only finitely many cases, so every identity can be checked mechanically.
Laws let you simplify without truth tables. Absorption: x plus x y. Write x as x times one; factor out x; one plus anything is one; so the whole thing is x. As a circuit, an and gate and an or gate collapse into a plain wire. Every simplification of an expression removes gates from a circuit, and logic synthesis tools, which turn a hardware description into a chip, are at heart very fast, very clever users of these laws.
2Circuits are expressionsDegree3 min
Shannon's thesis is a dictionary between two languages. Switches in series are multiplication: and. Switches in parallel are addition: or. A contact that opens when its relay is energized is not. Several contacts worked by the same relay are the same variable, used several times. And so any network of switches between two points is an expression, which is true exactly when current can flow. The dictionary works both ways: to analyse a circuit, write its expression; to design one, write the expression you want, simplify it with the laws, and translate back.
An example every house has. A staircase light, with a switch at the bottom and a switch at the top: flipping either one changes the light. In Shannon's language, the lamp should be on when A is up and B is down, or A is down and B is up. Two branches in parallel, each with two contacts in series; the bars are contacts that close when their switch is down. Try the four positions. The lamp is A exclusive-or B. The real two-way switch in your wall is this circuit, folded into one clever contact.
Here is the payoff. A circuit with three parallel paths: x and y; x and z; x and not y and not z. Seven contacts. Write its expression and apply the laws. Factor out x. What is left in the bracket is y or z, or the negation of y or z, by De Morgan. Something or its negation is always true. So the whole network is just x: one contact does the work of seven. Shannon did exactly this to real telephone circuits, and in the same thesis designed a relay circuit that adds binary numbers, which is where Part 4 begins.
The dictionary also works for analysis. Here is a circuit with three paths: x and y; not x and z; y and z. Its expression is x y plus not x z plus y z. Is the bottom path doing anything? It conducts when y and z are both closed. But then x is either closed, and the top path conducts anyway, or open, and the middle one does. The bottom path never adds a connection the others lack. So y z can be removed: this is the consensus theorem, and synthesis tools apply it constantly. Chapter ten will show a reason you might deliberately keep that useless contact.
3The transistorDegree4 min
Shannon's algebra does not care what the switches are made of, which is lucky, because relays are slow. A relay moves a piece of metal, and takes about a hundredth of a second. A vacuum tube steers electrons through a vacuum and switches a thousand times faster, but it is hot and it burns out; ENIAC, in 1945, had seventeen and a half thousand of them. The transistor, invented at Bell Labs in 1947, switches electrons in a solid crystal with nothing moving at all, and today's switch in a few picoseconds. The kind in every chip is the MOSFET, from 1959, and from 1958 they were built many at a time on one slice of silicon: the integrated circuit.
For logic, a MOSFET is just a switch with three wires. In an n-type transistor, a high voltage on the gate connects the drain to the source; a low voltage disconnects them. The gate itself draws almost no current: it works like the coil of a relay, through an electric field instead of a magnet. A p-type transistor is the mirror image: it conducts when its gate is low. The little bubble on the symbol means not, as on a gate. Two kinds of switch, one that closes on one and one that closes on zero. Put them together and something remarkable happens.
Stack a p-type transistor on an n-type one, the p on top connected to the supply voltage, the n below connected to ground, and join their gates as the input and their middle as the output. This is the CMOS inverter, the C standing for complementary. Input zero: the p transistor conducts and the n does not, so the output is connected to the supply: one. Input one: the n conducts and the p does not, so the output is connected to ground: zero. It computes not. At a stable zero or one, one transistor is off, so the ideal circuit has no path from the supply to ground. Real transistors still leak, and switching consumes energy. That is why static CMOS is so efficient.
Real voltages are not exactly zero and one, so look at everything in between. Sweep the input from ground to the supply, and plot the output, computed here from a standard model of the two transistors. It stays high, then plunges, then stays low. It crosses the diagonal at half the supply: the switching threshold. And in the middle it is very steep: a small change in the input makes a change in the output more than a hundred times bigger. The flat parts are the point. Anything below about forty-five percent of the supply is read as a clean zero, and anything above about fifty-five percent as a clean one. The gaps between what a gate guarantees to produce and what the next gate needs to see are the noise margins.
That steep curve does something wonderful. Feed a chain of inverters a sloppy zero, at thirty-eight percent of the supply, almost in the middle. After one inverter it is a confident one. After two, an almost perfect zero, and it stays perfect. Each gate restores the signal towards the rails. This is what digital means. In an analog circuit, noise accumulates with every stage. In a digital one, every gate throws it away, so a signal can pass through billions of gates and arrive intact. Everything from here on counts in zeros and ones, and it is allowed to because of this curve.
4CMOS gatesDegree3 min
The inverter's trick extends to two inputs. To pull the output down to zero, put two n transistors in series between the output and ground: the path conducts only if A and B are both high. To pull it up, put two p transistors in parallel between the supply and the output: either one conducting, when A or B is low, connects the output to one. Run the four inputs. The output is zero only when both are one: not and, NAND. And as before, for every input exactly one of the two networks conducts.
Swap the arrangement: n transistors in parallel below, p transistors in series above. Now either input high pulls the output down, and only both low pulls it up. NOR. The two networks of every CMOS gate are each other's duals: series in one is parallel in the other, exactly chapter one's duality, and the p network computes the De Morgan twin of the n network. Any expression built from and and or, with an inversion on the output, becomes one CMOS gate this way.
Count the transistors. An inverter takes two. NAND and NOR take four. And or or takes six, because CMOS naturally inverts: you build a NAND and then invert it. Exclusive-or takes eight or more. So the natural gates of CMOS are the inverting ones. And between those two, NAND wins: its series transistors are n-type, and electrons, which carry the current in n-type transistors, move two to three times faster than the holes in p-type ones. A modern chip is mostly NAND gates and inverters, which is why the next chapter asks whether NAND alone is enough.
One more property, and it is why CMOS won. The current the inverter draws from its supply, computed across the sweep, is zero at both ends and spikes only in the middle, while both transistors are partly on. In this ideal model, a stable CMOS gate draws no current; real gates still leak. Switching costs energy in two ways: overlap current while both transistors conduct, and the charge needed to flip the wires and gates it drives. The capacitive switching power is roughly the fraction of wires that switch, times their capacitance, times the supply voltage squared, times the clock frequency. That one formula explains why clocks stopped getting faster around 2005, and why chips grew many cores instead, which is Part 10.
5One gate is enoughDegree3 min
Chapter four said a chip is mostly NAND gates. Could it be nothing but NAND gates? Not: join a NAND's two inputs together. x NAND x is not x. One gate. And: a NAND, then a not. Two gates. Or: invert both inputs, then NAND them. By De Morgan, not x NAND not y is x or y. Three gates. We searched every possible arrangement of NAND gates, for every one of the sixteen functions of two inputs. Not needs one, and needs two, or three, exclusive-or four, and the hardest, exclusive-nor, five.
Here is the four-gate exclusive-or, a small classic. The first gate computes not x and y. Each of the next two combines it with one input: the top one is zero only when x is one and y is not, the bottom one only when y is one and x is not. The last NAND is one when either of those is zero: exactly when the inputs differ. Sharing that first gate between both paths is what makes four enough.
Now the general argument. Take any truth table, here one with three inputs. For each row where the output is one, write an and of the inputs, each either plain or negated, so that it is true on that row and no other. Then or those terms together. The result is true on exactly the rows it should be. This is the disjunctive normal form, and it shows that and, or and not can build every function. Since NAND builds all three, NAND alone can build every function. It is complete. So is NOR, by the mirror argument.
Which other sets of gates are complete? Emil Post answered that completely in 1941. There are exactly five ways for a set of gates to be trapped. If every gate keeps zero, giving zero on all zero inputs, then every circuit does too, and you can never build not. The same for keeping one. If every gate is monotone, circuits are monotone: and and or alone can never invert. If every gate is self-dual, or every gate is affine, an exclusive-or of its inputs plus a constant, circuits stay trapped there too. Here are some gates against the five properties. A cross means the gate escapes that trap. Post proved that escaping all five is also enough. A set is complete exactly when each trap is escaped by some gate in it. Among single two-input gates, only NAND and NOR escape all five.
6Normal forms and mapsDegree3 min
Chapter five's normal form always works, but it can be wasteful. Here is a way to see the waste. A function of three inputs assigns a value to each of the eight corners of a cube, one corner for each input pattern. This one is majority: green where at least two inputs are one. The disjunctive normal form has one term per green corner: four terms. But two green corners joined by an edge differ in one variable only, and that variable does not matter there: a b c and a b not c together are just a b. So cover the green corners with edges, or, better, whole faces. Three edges cover majority: a b plus b c plus a c.
With four inputs the cube has sixteen corners, and in 1953 Maurice Karnaugh found a way to flatten it. Lay the corners out in a four by four grid, with rows and columns in Gray-code order, so that cells side by side differ in exactly one bit. The left edge is next to the right edge, and the top to the bottom: the map is really a torus. Now groups of ones in rectangles of two, four or eight cells are terms with variables dropped. Here three groups cover everything, including the four corners, which are neighbours on the torus. Ten terms of four literals become three terms of two. For more inputs, maps fail and an algorithm takes over: Quine and McCluskey's method merges terms that differ in one bit, again and again, to find every prime implicant, and then picks the fewest that cover the function.
Normal forms can be terrible. Parity, which is one when an odd number of inputs are one, makes a perfect checkerboard on the map. No two ones are neighbours, nothing merges, and every one of the eight ones needs its own term. With n inputs the normal form needs two to the n minus one terms, which for sixty-four inputs is about nine billion billion terms. But a tree of n minus one exclusive-or gates computes it easily. The two-level form, an or of ands, is a poor model of what circuits can do; depth, how many layers deep a circuit is, changes everything, and chapter nine measures it.
So how hard is it to find the smallest formula for a function? Even for two-level forms, starting from the truth table, it is NP-hard, a word Part 26 makes precise: no efficient method is known, and probably none exists. Starting from a DNF, asking whether an equivalent DNF with fewer terms exists is even harder, complete for the second level of the polynomial hierarchy. So the logic synthesis tools that design real chips use clever heuristics, and do not promise the smallest circuit. They are extremely good at it anyway.
7Choosing with gatesDegree3 min
A circuit can choose. A multiplexer has two data inputs, a and b, and a select input s. When s is zero, the output is a; when s is one, it is b. In gates: not s and a, or s and b. Four gates. Watch it route one input or the other to the output as the select bit flips. It is the electrical version of an if statement, and it is about to turn out to be universal too.
A multiplexer can imitate the basic gates. Select with x, and feed in one and zero: if x then zero else one, which is not x. Feed in zero and y: if x then y else zero, which is x and y. Feed in y and one: if x then one else y, which is x or y. So a multiplexer, given the constants zero and one, is complete on its own, and Post's test agrees. This is why some chip families were built entirely from multiplexers.
Shannon also noticed this identity. Any function of x and other inputs equals: if x is zero, the function with x set to zero; if x is one, the function with x set to one. That is a multiplexer, choosing between two simpler functions. Expand those the same way, and again, until no inputs are left. What remains at the leaves are constants, zeros and ones: the truth table itself, read off by a tree of multiplexers driven by the inputs.
Now turn that around. Build the tree of multiplexers in hardware, and instead of constants at the leaves, put eight bits of memory. Whatever eight bits you store, the circuit computes that truth table. Store majority's table, and it is a majority gate. Rewrite the bits, and the same circuit computes parity. This is a lookup table, and it is how a field-programmable gate array works: hundreds of thousands of six-input lookup tables, sixty-four bits each, with programmable wiring between them. Hardware you can change in a few seconds, used for prototyping chips, for network equipment, and for accelerators in data centres.
One more choosing circuit, which every memory needs. A decoder takes a number in binary, here three bits, and lights exactly one of eight output wires: the one with that number. Count through the inputs and the lit wire walks down. Each output is an and of the inputs, plain or negated, which is chapter five's normal form, one term per wire. Pebble uses one to decide which of its sixteen registers to write, and every memory chip uses one to find the row you asked for.
8Decision diagramsGraduate3 min
Truth tables and normal forms are either huge or not unique. In 1986 Randal Bryant made a data structure that is often small, and unique once the variable order is fixed. Start with a decision tree. Here is majority: test a, then b, then c, and read the answer at a leaf. Dashed lines are zero, solid lines one. It is just the truth table, spread out. Now apply two rules. Share any two identical pieces, so all the zero leaves become one leaf and all the ones another. And delete any test whose two branches lead to the same place, because it does not matter. Repeat until neither rule applies. What remains is a reduced ordered binary decision diagram: for majority, four tests instead of seven.
There is a catch. Take x one and x two, or x three and x four, or x five and x six. Test the variables in their natural order, and the diagram is a neat ladder: eight nodes. Test all the odd ones first, then the even ones, and the diagram has to remember which of the first three were one before it can see their partners: sixteen nodes. Computed for more pairs, the good order grows by two nodes per pair; the bad order doubles. With fourteen variables, sixteen nodes against two hundred and fifty-six. Finding the best order is itself NP-hard, so real tools reorder heuristically as they go.
Why go to this trouble? Because with the order fixed, every function has exactly one reduced diagram. So to check that a clever optimized circuit computes the same function as its simple specification, build both diagrams in one shared table and compare two pointers. And, or and not on diagrams, and asking whether any input makes the function true, are polynomial in diagram size; combining two may take the product of their node counts. Counting how many inputs make a function true is fast too: one pass over the nodes. That made decision diagrams the workhorse of chip verification in the 1990s. The catch never goes away: Bryant also proved that the middle output bit of a multiplier has an exponentially large diagram under every possible order. Part 54 uses them anyway, where they work, and Part 26 meets the other great approach, satisfiability solvers.
9How many gates?Graduate4 min
A circuit has two costs. Its size, the number of gates, is area on the chip and power. Its depth, the longest path from an input to the output, is time: every gate on that path adds a delay. Parity of eight bits, as a chain of exclusive-ors: seven gates, seven deep. The same seven gates as a tree: three deep. Same size, less than half the time, and the gap grows: a chain is n minus one deep, a balanced tree ceiling log base two of n. Part 4's adders are a long fight to turn chains into trees.
How many gates does a typical function need? Shannon answered in 1949 without designing a single circuit. He counted. A function of n inputs is a truth table with two to the n rows, so there are two to the two to the n functions. For twenty inputs, a number with three hundred and fifteen thousand digits. A circuit with s gates is a list of s choices: a kind of gate, and two input wires. So there are at most about n plus s squared, to the s, of them. If the count of small circuits is a vanishing fraction of the function count, almost all functions need larger circuits. Almost every function of n inputs needs on the order of two to the n over n gates. Exponential. A random truth table is, almost surely, hopelessly hard.
Here are the numbers, computed. The gates most functions need grow like two to the n over n: for thirty inputs, tens of millions of gates. Compare a circuit that grows like n, the kind engineers actually build, down at the bottom. And it is tight: Oleg Lupanov showed in 1958 that about two to the n over n gates are always enough, for any function. Almost every function sits at that worst case. The functions we can build are the rare exceptions.
There is a second way to measure. Fix the same basis of and, or and not for both. A formula is a circuit in which every gate's output is used only once, so it is a tree, like the expressions of Part 2. A circuit may reuse a result as often as it likes. Sharing matters. Parity of n bits needs only about four n gates of and, or and not as a circuit. But as a formula, Valery Khrapchenko proved in 1971 that it needs at least n squared leaves. Powers of two attain that bound; for general n the order is quadratic. So sharing can save a polynomial factor. Whether it can ever save more than that, for some function, is another open question, and it is tangled up with whether problems can be solved quickly in parallel, which Part 10 meets.
And now the embarrassment. Almost every function needs exponentially many gates. Yet for explicit functions the lower bounds remain linear. Li and Yang reached three point one n in 2022. A November 2026 preprint by Om Swostik Mishra and Rahul Santhanam reports four n minus a logarithmic term. Even that is tiny beside the exponential bound for almost every function. The reason it matters: proving that some problem in NP needs more than polynomially many gates would prove that P is not equal to NP, the most famous open problem in the field. In weaker models we can prove such things. Parity needs exponentially many terms in depth two, as chapter six showed, and Johan Håstad proved it needs exponential size in any constant depth. Part 27 explains why the general case has resisted every technique so far.
10Gates take timeDegree3 min
So far a gate's output changed the instant its inputs did. Real gates take time: a few picoseconds to charge the wire they drive. In a circuit, a change at an input ripples forward gate by gate. The output is not settled until the change has travelled the longest path, here four gates deep. That path is the critical path, and it sets how fast the whole circuit can run. Every block in this part is counted in depth as well as size, because in Part 5 the critical path becomes the length of Pebble's clock cycle. For scale: a four gigahertz clock ticks every two hundred and fifty picoseconds, and a fast gate takes around ten, so a processor gets only a couple of dozen gate delays per cycle. Every design decision in act two is about living inside that budget.
Delays cause stranger things than slowness. Take f equals a b plus not a c, with b and c held at one. Then f is a or not a, which is always one, whatever a does. Now simulate it with every gate taking one unit of time, and let a fall from one to zero. The a b term drops after one AND delay. But the not-a term needs the inverter to react first, so it rises one delay late. For that one moment, both terms are zero, and the output, which should never change, flickers to zero. This is a glitch, from a static hazard. If anything downstream is watching at that moment, it sees a wrong answer.
One fix is surprising. Add the term b c, which the laws of chapter one say is redundant: it changes nothing about the function. But during the transition it holds the output up, and the glitch is gone. For a two-level sum of products and one changing input, cover every pair of neighbouring ones with a single loop. The more common cure is to stop caring: make every circuit settle before anybody looks at it, by reading outputs only at the tick of a clock. That is how Part 5 builds memory and time.
Where does the delay come from? A wire, and every gate input on it, is a small capacitor, and the transistor driving it is a resistor. Charging a capacitor through a resistor takes time: the voltage rises along an exponential, with a time constant R times C. A gate that drives four others has four times the load, and takes four times as long to reach the threshold. So fan-out, the number of inputs a gate drives, costs time, and chip designers limit it and insert buffers to drive long wires. Today, on the largest chips, the wires are slower than the gates.
11The blocks Pebble needsGraduate3 min
With the tools of this part we can now build the parts a processor needs. Pebble will compare numbers, for instructions like branch if less than. Is a less than b? Scan from the most significant bit. While the bits agree, the answer depends on what comes later. At the first place they differ, the number with the zero there is smaller. Here a has a one where b has a zero, so a is bigger. As a formula: an equal signal for each bit, an exclusive-nor, and a sum of terms, one per position, each requiring all the higher bits to be equal. Built and checked on every pair of inputs, the four-bit version takes twenty-one gates.
Next, a priority encoder. Given eight wires, report the position of the highest one that is on. Here, bits five, three and two are on; the answer is five, and a valid flag says that some bit was on at all. The circuit first keeps only the highest one, by and-ing each bit with not of everything above it, and then turns that single hot wire back into a number. Processors use it to decide which interrupt to serve first, and to normalize floating-point numbers by counting leading zeros.
Shifting a number left by k places multiplies it by two to the k, and Pebble has instructions that shift by any amount from zero to thirty-one. Doing it one place at a time would take thirty-one steps. A barrel shifter does it in log n stages instead. Write the shift amount in binary. The first stage shifts by one, or not, according to the lowest bit; the second by two, or not; the third by four. To shift twenty-three by five, which is four plus one: shift by one, skip the two, shift by four. Each stage is a row of multiplexers, so any shift takes the same time: three multiplexers deep for eight bits, five for thirty-two.
Here is everything this chapter built, plus the decoder and multiplexer from chapter seven, with their costs. Each one is a netlist in this series' hardware library, simulated on every possible input and compared with its specification: for the eight-bit comparator, all sixty-five thousand pairs. The last columns rebuild each block from NAND gates only, as chapter five promised was possible: roughly twice the gates, and twice the depth. Pebble will be built from these blocks, and nothing else.
12Our hardware layerIndustry3 min
Every circuit in this series, from this part's comparators to Pebble itself in Part 6, runs on one small piece of code, and it is worth seeing how it works. A circuit is built by calling functions: make three inputs, an exclusive-or, another, two ands and an or. That is a full adder, Part 4's first circuit. Underneath, the circuit is just a numbered list of wires: each entry says what kind of gate drives it and which earlier wires it reads. Because a gate can only read wires that already exist, the list is in an order where every gate comes after its inputs. So evaluating the whole circuit is one pass down the list.
The other trick makes it fast. Each wire does not hold one bit. It holds a 64-bit machine word, and bit number j of that word is the wire's value in test number j. So a single and instruction on two words evaluates an and gate on sixty-four different inputs at once. Checking the eight-bit comparator on all sixty-five thousand of its inputs takes a thousand and twenty-four words per wire, one pass, and a fraction of a second. This is bit-parallel simulation, and chip companies use the same idea, on far bigger machines, before they build anything.
The library can also rewrite a circuit. Every gate is replaced by its construction from chapter five: a not by one NAND, an and by two, an or by three, an exclusive-or by four. The comparator's twenty-one gates become fifty-three NANDs; the barrel shifter's ninety-six become a hundred and ninety-two. And then the rewritten circuit goes through the same exhaustive check as the original. That is how Part 6 can honestly say that Pebble runs on nothing but NAND gates: the claim is checked, not assumed.
So every block in this series is checked the same way. On one side, the specification, written as plain arithmetic. On the other, the gate-level implementation. Run both on every possible input, and compare. For the comparator, sixty-five thousand inputs, all equal. This only works for small blocks: at thirty-two input bits there are four billion cases, and a sixty-four-bit adder has two to the hundred and twenty-eight. Beyond that, verification needs the decision diagrams of chapter eight, the satisfiability solvers of Part 26, or the machine-checked proofs of Part 54.
13Machines of switchesDegree3 min
Shannon's thesis arrived just as people started building computers from switches. In 1937 George Stibitz at Bell Labs wired a relay adder on his kitchen table. In Berlin, Konrad Zuse built the Z1, binary and mechanical, and then in 1941 the Z3, with two thousand six hundred relays, the first working programmable computer. In Iowa, John Atanasoff and Clifford Berry built an electronic calculator with vacuum tubes. At Bletchley Park, Colossus used tubes to break German teleprinter ciphers. And in Philadelphia, ENIAC used seventeen and a half thousand of them and a hundred and fifty kilowatts. Different countries, different purposes, mostly in secret, and all used switching logic. Many were binary, but ENIAC represented numbers in decimal.
Two of these machines are worth a closer look. Zuse's Z3 worked in binary floating point, twenty-two bits per number, and managed about five additions a second. Its program was punched into discarded cinema film. It was destroyed in an air raid in 1943, and in 1998 Raúl Rojas showed that, with some contortions, it could in principle compute anything a Turing machine can. ENIAC was decimal and a thousand times faster, but it was programmed by plugging cables and setting switches, which could take days. The six women who first worked out how to do that, Kay McNulty, Betty Jennings, Betty Snyder, Marlyn Wescoff, Fran Bilas and Ruth Lichterman, were for decades left out of its history. What both machines lacked was the idea of Part 1's universal machine: a program stored as data in the computer's own memory. Part 6 gives Pebble exactly that.
Then came the transistor in 1947 and the integrated circuit in 1958, and the switches started shrinking. In 1965 Gordon Moore, later a founder of Intel, noticed that the number of transistors on a chip was doubling every year, and predicted it would continue; in 1975 he revised it to every two years. Here are some landmark chips on a logarithmic scale, from Intel's 4004 in 1971, with two thousand three hundred transistors, to the B200 of 2024, with two hundred and eight billion across two silicon dies. The long-term trend is close to doubling every two years; packaging also matters at the latest point. Each of those transistors is the switch of chapter three, and each chip is, at heart, Shannon's algebra.
14Gates that forget nothingGraduate2 min
One last question about gates, and a glimpse of the end of the series. An and gate takes four possible inputs to two possible outputs. Three different inputs all give zero. Seeing a zero, you cannot tell which of them it was: the gate has destroyed information. In 1961 Rolf Landauer, at IBM, argued that destroying information has a physical price. Erasing one bit must release at least k T log two of heat, about three zeptojoules at room temperature. Real gates spend about a million times more than that, so the limit is far away, but it is a law of physics, not of engineering.
Can you compute without forgetting? Tommaso Toffoli's gate has three inputs and three outputs. The first two pass straight through; the third is flipped exactly when the first two are both one. Its table is a shuffle of the eight states: every output comes from exactly one input, so nothing is lost, and applying it twice gives back what you started with. Feed it a constant one on the third wire, and the third output is not a and b: a NAND. So by chapter five, reversible gates can compute anything, as Charles Bennett showed in 1973, as long as you keep the extra outputs instead of throwing them away. Edward Fredkin's gate is another: it swaps its last two wires when the first is one, and it never changes how many ones there are, so it can be pictured as billiard balls bouncing through a maze, a model Fredkin and Toffoli proposed in 1982.
This is not just a curiosity. Coherent quantum gates are unitary transformations of the state, so each has an inverse. Measurement and reset are different operations. The Toffoli gate is one of the standard quantum gates, and in Part 53 we will simulate a small quantum computer, Toffoli gates included. And the idea of keeping what you would have thrown away, so you can go back, appears much higher up the tower, in the logs that let databases and file systems undo a crash.
15Frontier: the smallest circuitResearch5 min
Chapter nine counted how many gates a typical function needs. For very small functions we can do better than count: we can find the best circuit for every one. Treat a search state as the set of functions its wires compute. Start from the three inputs and free constants, allow tied input pins, add every possible two-input gate, and keep each new set once. With constants and source wires free, one gate gives thirty-three distinct search states, two give eight hundred and twenty-eight, three give twenty thousand three hundred and sixty, four give over half a million, and at four gates every one of the two hundred and fifty-six functions of three inputs has appeared. So every function of three inputs needs at most four gates, and we know exactly how many each needs: parity of three needs two, the multiplexer three, and majority four, one of the twenty-four hardest. These are not estimates but proofs, by exhaustion.
This cannot go much further. Four inputs give sixty-five thousand functions, and Donald Knuth computed all of their exact costs in 2005: the hardest need seven gates. Five inputs give four billion functions; Knuth settled almost all of them, and the last few were finished by computer in 2019: the hardest needs twelve. At six inputs there are eighteen quintillion functions, and nobody knows the hardest cost. The number of functions squares with every input added. Modern SAT solvers, which Part 26 builds, can find circuits of ten or twelve gates, but proving that no twelve-gate circuit exists for a single six-input function is already at their limit. Exact knowledge of circuit size ends at five inputs.
How are the lower bounds that do exist proved? Almost all of them by one idea, gate elimination. Fix one input to a constant. A gate that input fed becomes a constant, a copy, or an inverted copy of its other input. Simplify constants and copies, and fold inversions into following gates; sometimes further gates disappear too. Choose the function so cleverly that, whatever the circuit, some input can always be fixed to remove at least three gates, and what remains is a function of the same kind with one input fewer. Then induction on the number of inputs gives three n. Norbert Blum reached three n in 1984. It took thirty-two years to add one eighty-sixth of n, and six more to reach three point one n, each by a longer case analysis of how a minimal circuit can look, for functions called affine dispersers, which stay non-constant on every large affine subspace. A November 2026 preprint by Mishra and Santhanam reports four n minus a logarithmic term, by eliminating independent parameters rather than only fixing input variables. The bound is still linear, a long way from two to the n over n.
So ask a computer the question directly. Given the truth table of a function and a number s, is there a circuit of at most s gates? This is the minimum circuit size problem. It is in NP, the class Part 26 defines: a small circuit, once found, is easy to check against every row. Is it as hard as everything in NP? Leonid Levin wondered in the 1970s, Valentine Kabanets and Jin-Yi Cai made the question famous in 2000, and it is still open. In 2022 Shuichi Hirahara proved the version with some rows left unspecified NP-hard, the closest anyone has come. And the question reaches cryptography: Yanyi Liu and Rafael Pass proved in 2020 that one-way functions, the foundation of Parts 29 and 30, exist exactly when a time-bounded version of Kolmogorov complexity is mildly hard on average. This young field, meta-complexity, asks how hard it is to tell how hard something is, and it is one of the most active in theory today.
Recap, problems, and where this comes backAll tracks2 min
What we built in this part. Shannon's dictionary, which turns switching circuits into Boole's algebra and back. The transistor as a switch, and the CMOS inverter, whose steep curve throws noise away at every stage. NAND and NOR in four transistors each, and the proof that NAND alone builds everything. Normal forms, maps and decision diagrams, the ways to write a function down and to shrink it. And Shannon's counting argument: almost every function needs an enormous circuit, though nobody can name one.
Where this comes back. Gates, multiplexers and decoders build the adders of Part 4, the memories of Part 5 and Pebble itself in Part 6. Depth and the critical path decide how fast those circuits run, and Part 7's pipeline exists to shorten it. The power formula explains Part 10's turn to many cores. Decision diagrams come back in Part 54 to check hardware and software, circuit lower bounds in Parts 26 and 27, and reversible gates in Part 53's quantum computer.
Seven problems, with full solutions in the part's notes. Pause on any of them. The sixth is a build problem: it asks you to use this series' hardware library yourself. The last, marked with a star, is a research problem: a computation that took Knuth real ingenuity, and a question nobody can answer.
Next time: arithmetic. With gates in hand, we teach them to count. A half adder, a full adder, and a ripple of them that adds numbers of any length, slowly; then the tricks that make addition take log n time instead of n, two's complement for negative numbers, multiplication, and the arithmetic unit at the heart of Pebble.
The books and papers this part follows are on screen and in the notes. Thank you for watching.
Where it goes next. Gates, multiplexers and decoders build the adders of Part 4, the memories of Part 5 and Pebble itself in Part 6. The critical path decides how fast those circuits run, and Part 7's pipeline exists to shorten it; the power formula explains Part 10's turn to many cores. Decision diagrams return in Part 54, circuit lower bounds in Parts 26 and 27, reversible gates in Part 53.
Key results
The part's results in one place, for revision.
Try it
Lab 3 · One gate is enough, and what two levels cost
Minimize a random five-input truth table with Quine-McCluskey, build it as a netlist, rewrite the netlist in NAND gates alone and check both on all 32 inputs. Then search for the fewest NANDs for each two-input function, and compare parity as a sum of products with parity as a tree of XORs.
python -m videos.cs.labs 3
needs numpy, scipy, matplotlib · download lab03.py ·
source on GitHubrandom 5-input function 21 ones in its table, 7 product terms after minimizing
as AND, OR, NOT 25 gates, depth 6
rewritten in NAND alone 51 gates, depth 11
two-input functions reached with at most 5 NANDs 16 of 16
fewest NANDs NOT 1, AND 2, OR 3, XOR 4, XNOR 5 (the film: XOR 4, XNOR 5)
parity of 8 inputs, sum of products 128 terms (2^(n-1)), 1031 gates, depth 11
parity of 8 inputs, XOR tree 7 gates (n - 1), depth 3
Any truth table can be built from NAND alone, but the recipe that proves it, the sum of products, is exponentially wasteful for parity; nobody knows a function in NP that provably needs more than a small multiple of n gates.
The code (110 lines; it asserts its own result)
"""Lab 3: build a random truth table from gates, rewrite it in NAND alone, and count what parity costs in two levels."""
import numpy as np
from videos.coursekit import labs
from explainer.cs.pebble import hdl, logic
from explainer.cs.pebble.blocks import tree
TITLE = "One gate is enough, and what two levels cost"
GOAL = ("Minimize a random five-input truth table with Quine-McCluskey, build it as a netlist, rewrite the netlist "
"in NAND gates alone and check both on all 32 inputs. Then search for the fewest NANDs for each two-input "
"function, and compare parity as a sum of products with parity as a tree of XORs.")
TASKS = [
"Replace the random table by majority of five inputs. How many prime implicants does it have, and how many gates?",
"Change the search to NOR gates (out = ~(a | b)). Which function now needs five gates instead of four?",
"Rewrite the XOR tree with to_nand() and compare its gate count and depth with the sum of products for n = 8.",
]
NAMES = {0b0110: "XOR", 0b1001: "XNOR", 0b1000: "AND", 0b1110: "OR", 0b0111: "NAND", 0b0001: "NOR", 0b0011: "NOT x",
0b0101: "NOT y", 0b1100: "x", 0b1010: "y", 0b0000: "0", 0b1111: "1", 0b0100: "x AND NOT y",
0b0010: "y AND NOT x", 0b1101: "x OR NOT y", 0b1011: "y OR NOT x"}
def table_of(c, n):
"""The circuit's output on all 2^n inputs, as an array of 0/1 (input pattern p sets variable j to bit j of p)."""
return hdl.unpack(c.evaluate(hdl.exhaustive(c))["f"][0], 1 << n)
def sum_of_products(on, n):
"""The minimized sum of products of the function that is 1 on the minterms ``on``: (circuit, product terms)."""
c = hdl.Circuit("sum of products")
xs = c.input("x", n)
terms = logic.min_cover(set(on), set(), n)
c.output("f", logic.sop(c, terms, logic.Literals(c, xs)))
return c, terms
def fewest_nands(max_gates=5):
"""Breadth-first search over sets of wire functions: the fewest NAND gates for each two-input function."""
x, y = 0b1100, 0b1010 # bit 2x + y of a 4-bit table is the value at (x, y)
best = {x: 0, y: 0}
frontier = {(y, x)}
for g in range(1, max_gates + 1):
nxt = set()
for wires in frontier:
for i, a in enumerate(wires):
for b in wires[i:]:
out = ~(a & b) & 0b1111
if out not in wires:
nxt.add(tuple(sorted(wires + (out,))))
best.setdefault(out, g)
frontier = nxt
return best
def run(seed=0):
rng = np.random.default_rng(seed)
lab = labs.Lab()
# 1. a random function of five inputs: truth table -> minimized sum of products -> NAND only
n = 5
truth = rng.integers(0, 2, 1 << n)
c, terms = sum_of_products(np.flatnonzero(truth), n)
nand = c.to_nand()
lab.row("random 5-input function", f"{int(truth.sum())} ones in its table, {len(terms)} product terms after minimizing")
lab.row("as AND, OR, NOT", f"{c.size()} gates, depth {c.depth()}")
lab.row("rewritten in NAND alone", f"{nand.size()} gates, depth {nand.depth()}")
assert np.array_equal(table_of(c, n), truth), "the sum of products is the function"
assert set(nand.counts()) == {"NAND"} and np.array_equal(table_of(nand, n), truth), "and so is the NAND rewrite"
# 2. the fewest NANDs for each of the sixteen two-input functions
best = fewest_nands()
lab.row("two-input functions reached with at most 5 NANDs", f"{len(best)} of 16")
lab.row("fewest NANDs", f"NOT {best[0b0011]}, AND {best[0b1000]}, OR {best[0b1110]}, XOR {best[0b0110]}, XNOR {best[0b1001]}"
" (the film: XOR 4, XNOR 5)")
assert len(best) == 16 and (best[0b0011], best[0b1000], best[0b1110], best[0b0110], best[0b1001]) == (1, 2, 3, 4, 5)
# 3. parity: 2^(n-1) product terms in two levels, n - 1 XOR gates in a tree
ns = list(range(2, 9))
sop_gates, xor_gates = [], []
for k in ns:
odd = [m for m in range(1 << k) if m.bit_count() % 2]
terms = sorted(logic.prime_implicants(set(odd), set(), k)) # Quine-McCluskey's merging rounds
assert len(terms) == 2 ** (k - 1) and all(mask == 0 for _, mask in terms), "no two minterms of parity merge"
flat = hdl.Circuit("parity, sum of products")
flat.output("f", logic.sop(flat, terms, logic.Literals(flat, flat.input("x", k))))
t = hdl.Circuit("parity, xor tree")
t.output("f", tree(t, t.xor, t.input("x", k)))
assert t.size() == k - 1 and np.array_equal(table_of(flat, k), table_of(t, k))
sop_gates.append(flat.size())
xor_gates.append(t.size())
lab.row("parity of 8 inputs, sum of products", f"{2 ** 7} terms (2^(n-1)), {sop_gates[-1]} gates, depth {flat.depth()}")
lab.row("parity of 8 inputs, XOR tree", f"{xor_gates[-1]} gates (n - 1), depth {t.depth()}")
lab.note = ("Any truth table can be built from NAND alone, but the recipe that proves it, the sum of products, "
"is exponentially wasteful for parity; nobody knows a function in NP that provably needs more than "
"a small multiple of n gates.")
fig, ax = labs.figure(2, size=(11, 4.2))
ax[0].semilogy(ns, sop_gates, "o-", color=labs.RED, label="sum of products (2 levels)")
ax[0].semilogy(ns, xor_gates, "o-", color=labs.GREEN, label="tree of XOR gates")
ax[0].semilogy(ns, [2 ** (k - 1) for k in ns], "--", color=labs.MUTED, label="2^(n-1) product terms")
ax[0].set(title="Parity of n inputs: gates needed", xlabel="n", ylabel="gates")
ax[0].legend()
order = sorted(best, key=lambda f: (best[f], NAMES[f]))
ax[1].barh([NAMES[f] for f in order], [best[f] for f in order], color=[labs.GOLD if NAMES[f] in ("XOR", "XNOR") else labs.BLUE for f in order])
ax[1].invert_yaxis()
ax[1].set(title="Fewest NAND gates for each two-input function", xlabel="NAND gates")
ax[1].tick_params(axis="y", labelsize=8)
ax[1].set_axisbelow(True)
lab.fig = fig
return lab
Now change it
- Replace the random table by majority of five inputs. How many prime implicants does it have, and how many gates?
- Change the search to NOR gates (out = ~(a | b)). Which function now needs five gates instead of four?
- Rewrite the XOR tree with to_nand() and compare its gate count and depth with the sum of products for n = 8.
Problems, with solutions
Try each problem before opening its solution.
-
NOR is complete. Build NOT, OR and AND from NOR.
Solution
NOT x = x NOR x (1 gate). x OR y = NOT(x NOR y) (2 gates). x AND y = (NOT x) NOR (NOT y), by De Morgan (3 gates). Since {AND, OR, NOT} is complete (the DNF), so is NOR. These counts are the mirror images of NAND's.
-
Post's test. Show {XOR, AND} is not complete but {XOR, AND, 1} is.
Solution
XOR and AND both map 0, 0 to 0, so every circuit of them outputs 0 on the all-zero input: the set is trapped in the 0-preserving class and cannot make NOT. Adding the constant 1 escapes that trap; the other four are escaped already (AND is not affine and not self-dual, XOR is not monotone and does not preserve 1). Concretely, NOT x = x XOR 1, and with NOT and AND we have everything.
-
A Karnaugh map. Minimize f = Σm(1, 3, 4, 5, 9, 11, 12, 13).
Solution
With the variables ABCD, the ones form two groups of four: B'D (minterms 1, 3, 9, 11) and BC' (4, 5, 12, 13). So f = B'D + BC', two terms of two literals, against eight terms of four in the normal form.
-
Counting functions. How many Boolean functions of 3 inputs are there, and how many are monotone?
Solution
2^(2³) = 256 functions. The monotone ones, counted by brute force over all 256 truth tables, number 20 (the Dedekind number M(3)): the constants, the three variables, and the and/or combinations of them such as majority.
-
A hazard. f = xy' + yz with x = z = 1.
Solution
Then f = y' + y = 1 always, but when y changes the term being switched off can fall before the other rises (the y' term waits for an inverter), so f glitches to 0 when y falls from 1 to 0: yz drops at once and xy' rises one inverter delay late. The consensus term of xy' and yz is xz; adding it holds f at 1 while y changes: f = xy' + yz + xz.
-
Build: a 4-to-1 multiplexer in NANDs.
Solution
A 2-to-1 mux in NANDs is NAND(NAND(a, s'), NAND(b, s)) with s' = NAND(s, s): four gates. Three of them make a 4-to-1 mux, and the two first-level muxes share one inverter of s₀: 11 NANDs. The library's mechanical
mux_n(2).to_nand()gives 24 (it rewrites each AND, OR and NOT separately, without sharing or simplifying), with depth 9 against the hand design's 5. Both pass the exhaustive check on all 64 inputs. -
★ Research: four inputs, and MCSP. Extend
compute_census(invideos/cs/cs3/compute.py) to all 65,536 functions of four inputs and recover Knuth's result that the hardest need 7 gates. Open: is the Minimum Circuit Size Problem NP-complete?What is known, and where to start. The breadth-first search over sets of wires that settles three inputs in six seconds explodes at four: the number of distinct circuits grows roughly thirtyfold per gate, and seven gates are needed. Three ideas make it tractable. (1) Symmetry: permuting and negating inputs and negating the output (the NPN group, of order 2⁴·4!·2 = 768) preserves cost, so only the 222 NPN classes of 4-input functions need a search. (2) Meet in the middle: the cost of f is at most the cost of g and h plus one when f = g ∘ h, so costs can be built up from small ones without storing circuits (Knuth's "footprint" method, TAOCP 7.1.2). (3) SAT: encode "a circuit of r gates computes f" as a formula and ask a solver; this is how the last 5-input cases were closed (Haaswijk, Soeken, Mishchenko and De Micheli; Kulikov and others). A correct answer is checked by exhibiting, for each class, a circuit of the claimed size and an exhaustive proof that none is smaller. On MCSP: it is in NP; it is not known to be NP-hard under the usual reductions, and there are results showing that proving it NP-hard by certain natural kinds of reduction would itself imply new circuit lower bounds (Murray and Williams, 2015). Hirahara (2022) proved NP-hardness for partial truth tables. The full question is open.
Notes and sources
Glossary
开关 switch · 继电器 relay · 串联 / 并联 series / parallel · 晶体管 transistor · 互补金属氧化物半导体 CMOS · 上拉 / 下拉网络 pull-up / pull-down network · 传输特性曲线 transfer curve · 噪声容限 noise margin · 与非门 / 或非门 NAND / NOR · 完备的 (functionally) complete · 析取范式 / 合取范式 DNF / CNF · 卡诺图 Karnaugh map · 质蕴涵项 prime implicant · 多路选择器 multiplexer · 译码器 / 编码器 decoder / encoder · 查找表 lookup table (LUT) · 现场可编程门阵列 FPGA · 二元决策图 binary decision diagram (BDD) · 香农展开 Shannon expansion · 电路规模 / 深度 circuit size / depth · 关键路径 critical path · 传播延迟 propagation delay · 险象 / 毛刺 hazard / glitch · 共识项 consensus term · 扇出 fan-out · 桶形移位器 barrel shifter · 优先编码器 priority encoder · 可逆门 reversible gate · 托福利门 Toffoli gate
Sources
Books: Harris & Harris, Digital Design and Computer Architecture, ch. 1–2; Nisan & Schocken, The Elements of Computing Systems, ch. 1; Petzold, Code; Weste & Harris, CMOS VLSI Design, ch. 1; Wegener, The Complexity of Boolean Functions; Jukna, Boolean Function Complexity; Knuth, TAOCP vol. 4A §7.1.
Papers: Boole (1854); Shannon, "A symbolic analysis of relay and switching circuits" (1938) and "The synthesis of two-terminal switching circuits" (1949); Post (1941); Karnaugh (1953); Lupanov (1958); Landauer (1961); Moore, "Cramming more components onto integrated circuits" (1965); Khrapchenko (1971); Bennett (1973); Masek (1979); Toffoli (1980); Fredkin & Toffoli (1982); Bryant (1986, 1991); Håstad (1986); Rojas (1998); Umans (2001); Li & Yang, "3.1n − o(n) circuit lower bounds for explicit functions" (2022).
Research update checked 9 November 2026: Mishra and Santhanam, ECCC TR26-260, revision 1, posted 3 November 2026, reports a \(4n-O(\log n)\) bound for explicit functions over all two-input Boolean gates. The video labels this as a preprint and omits lower-order terms in its gap illustration; this QA checks the attribution, not the paper’s proof.
About this partfrom its README
Part 3 of a sixty-one-part course in computer science (see the series plan and
the syllabus), and the first step of act one: building a computer from switches. Boole turns logic
into algebra; a 21-year-old Shannon notices that relay circuits obey it; the transistor makes the switch fast and
small; one gate, NAND, turns out to be enough for everything; and yet almost every function needs an astronomically
large circuit, and nobody can name one that does. Every circuit here is a netlist in this series' hardware library
(explainer/cs/pebble/hdl.py), simulated bit-parallel and checked on every input (compute.py).
- A thesis about switches. Shannon's 1937 master's thesis; switches in series compute AND, in parallel OR; relays let circuits drive circuits; objectives.
- 1. Boole's algebra. The Laws of Thought (1854); syllogisms as equations; the laws in dual pairs; or distributes over and, shown with Venn regions; simplifying by the laws (absorption as a circuit that collapses to a wire).
- 2. Circuits are expressions. Shannon's dictionary; the staircase light as XOR; seven contacts reduced to one by algebra; the consensus theorem by analysing a circuit.
- 3. The transistor. Relays, tubes, transistors (1947), the MOSFET (1959), the integrated circuit (1958–59); nMOS and pMOS as switches; the CMOS inverter; its transfer curve computed from square-law transistors (threshold 0.50 V_DD, gain ≈ 170, noise margins ≈ 0.40 V_DD); a chain of inverters restoring a sloppy zero.
- 4. CMOS gates. NAND and NOR as dual series–parallel networks, run on all inputs; an and-or-invert gate in six transistors; transistors per gate and why chips are mostly NAND; power only while switching, P ≈ αCV²f.
- 5. One gate is enough. NOT, AND, OR from NAND; the fewest NANDs for each of the sixteen two-input functions, by exhaustive search (XOR 4, XNOR 5); the four-NAND XOR; completeness via the disjunctive normal form; Post's five traps (1941), computed for every two-input gate: only NAND and NOR are complete alone.
- 6. Normal forms and maps. The Boolean cube and implicants as edges and faces; Karnaugh maps as the unfolded 4-cube on a torus, with Quine–McCluskey's prime implicants and a minimal cover (computed); parity's DNF of 2ⁿ⁻¹ terms against a tree of n − 1 XORs; minimization is NP-hard (Masek) and Σ₂ᵖ-complete (Umans).
- 7. Choosing with gates. The 2-to-1 multiplexer; a multiplexer with constants is complete; Shannon expansion; a tree of multiplexers reads a truth table, and a lookup table reprogrammed from majority to parity is how an FPGA works; the 3-to-8 decoder.
- 8. Decision diagrams. From a decision tree to a reduced ordered BDD (majority: 15 nodes to 6); variable order matters exponentially (x₁x₂ + x₃x₄ + ⋯: 2k + 2 against 2ᵏ⁺¹ nodes, computed up to 14 variables); canonical forms make equivalence a pointer comparison; multiplication defeats every order (Bryant, 1991).
- 9. How many gates? Size and depth (parity as a chain and as a tree); Shannon's counting argument (1949) and the computed curves; Lupanov's matching upper bound (1958); formulas against circuits (Khrapchenko's n²); the explicit-function gap (3.1n, Li & Yang 2022; a November 2026 preprint reports 4n − O(log n)), P versus NP, and Håstad's constant-depth bound.
- 10. Gates take time. Propagation delay and the critical path; a static hazard simulated with unit delays and removed by the consensus term; RC delay, fan-out and buffers; the clock budget.
- 11. The blocks Pebble needs. Comparator, priority encoder, barrel shifter (log₂ n stages), and a table of every block with gates, depth, NAND counts and the inputs checked.
- 12. Our hardware layer. Netlists as topologically ordered lists; bit-parallel simulation (64 tests per word); the NAND rewrite, re-verified; exhaustive checking and where it stops.
- 13. Machines of switches. Stibitz, Zuse's Z1 and Z3, Atanasoff–Berry, Colossus, ENIAC and its first programmers; Moore's law on landmark chips from the 4004 to 2024's GPUs.
- 14. Gates that forget nothing. Landauer's bound; the Toffoli gate (reversible and universal); Fredkin's gate; why quantum computing (Part 53) needs them.
- 15. Frontier: the smallest circuit. Exact minimum circuits: every 3-input function solved by breadth-first search over wire-function sets, with free constants and tied input pins (33, 828, 20,360 and 528,991 distinct search states of 1–4 gates; costs 0–4 for 5, 33, 114, 80 and 24 functions; parity 2, the multiplexer 3, majority 4). The census beyond: 4 inputs, at most 7 gates (Knuth, 2005); 5 inputs, at most 12 (the last cases settled by computer in 2019); 6 inputs unknown, at the limit of SAT solvers. Gate elimination, the method behind every linear lower bound: fix an input, remove at least three gates, induct (Blum's 3n, 1984; (3 + 1/86)n, 2016; 3.1n, Li and Yang, 2022, for affine dispersers); a November 2026 preprint by Mishra and Santhanam reports 4n − O(log n) using independent-parameter elimination. The Minimum Circuit Size Problem: in NP, NP-completeness open (Levin; Kabanets and Cai, 2000); partial MCSP NP-hard (Hirahara, 2022); one-way functions and time-bounded Kolmogorov complexity (Liu and Pass, 2020); meta-complexity.
- Recap, where this comes back, in practice, problems.
Companion material in this repository
The syllabus's plan for this partfrom SYLLABUS.md, the plan of record
- Boole (1854): the laws of thought as algebra; the axioms; De Morgan; Venn diagrams and truth tables.
- Shannon's 1937 master's thesis: switches in series are AND, in parallel are OR; the relay circuit as a Boolean expression.
- From relays to tubes to transistors: the MOSFET as a voltage-controlled switch; nMOS and pMOS; the CMOS inverter and its transfer curve and noise margins; NAND and NOR in CMOS by series–parallel duality; why CMOS spends power only when it switches.
- NAND is complete (proved: NOT, AND and OR from NAND, then any function by DNF). Post's lattice (1941): a set of gates is complete iff it escapes all five maximal clones (monotone, affine, self-dual, 0-preserving, 1-preserving).
- Normal forms: DNF and CNF from a truth table, and their exponential cost. Karnaugh maps as Gray-coded faces of the Boolean cube (3D) and the 4-variable torus. Prime implicants; Quine–McCluskey; minimization is Σ₂ᵖ-complete (Umans).
- Multiplexers, decoders, encoders. Shannon expansion f = x·f₁ + x̄·f₀. The mux as a lookup table, which is how FPGAs work.
- Binary decision diagrams (Bryant 1986): reduce and share to get a canonical form. Variable order changes the size exponentially (computed). Part 54 uses them.
- Circuit complexity:
- size and depth;
- Shannon's counting argument (1949): almost all n-input functions need ≳ 2ⁿ/n gates (proved by counting circuits against functions);
- Lupanov's matching upper bound;
- yet explicit-function lower bounds remain linear: 3.1n (Li & Yang, 2022), with 4n − O(log n) reported by Mishra & Santhanam in a November 2026 preprint. The gap returns in Part 27.
- Formulas against circuits; parity needs 2ⁿ⁻¹ terms in depth two.
- Gates take time: propagation delay, the critical path, glitches and hazards, fan-out, RC delay. Our simulator with unit delays shows a glitch.
- The blocks Pebble needs, built and gate-counted: comparators, parity trees, priority encoders, a log-depth barrel shifter.
- The series' hardware layer: netlists in Python, bit-parallel simulation (64 vectors per word), exhaustive verification of every block.
- History: Zuse's Z1–Z3 (1938–41), Stibitz's relay calculators, Atanasoff–Berry, Colossus (1944); Moore's 1965 paper.
- Reversible gates (Toffoli, Fredkin) as a preview of Part 53. Outro.
Computed: gate counts and critical paths of every block; exhaustive checks; BDD sizes under good and bad variable orders; Shannon's counting curves; glitch traces. Visuals: relay contacts clicking into series and parallel; the CMOS inverter's transfer curve; truth table → Boolean cube → K-map faces; a BDD collapsing as nodes merge; two towers of numbers, 2^(2ⁿ) functions against the circuits of size s. In practice: FPGAs and hardware description languages (Verilog, VHDL, Chisel), logic synthesis, BDD- and SAT-based hardware verification. Reading: Harris & Harris, Digital Design and Computer Architecture ch. 1–2; Nisan & Schocken, The Elements of Computing Systems ch. 1; Petzold, Code; Shannon 1938, 1949; Bryant 1986; Wegener, The Complexity of Boolean Functions; Jukna, Boolean Function Complexity; Knuth, TAOCP 4A §7.1; Weste & Harris, CMOS VLSI Design ch. 1; Li & Yang 2022 (3.1n); Mishra & Santhanam, ECCC TR26-260 revision 1, November 2026 preprint (reports 4n − O(log n), attribution checked 9 November 2026).
中文讲义
本讲的中文部分(与英文版对应)。
习题与解答
-
NOR 是完备的。 用 NOR 搭出 NOT、OR 和 AND。
解答
NOT x = x NOR x(1 个门)。x OR y = NOT(x NOR y)(2 个门)。x AND y = (NOT x) NOR (NOT y),由德摩根律(3 个门)。既然 {AND, OR, NOT} 是完备的(析取范式),NOR 也是。这些门数正是 NAND 的镜像。
-
波斯特判据。 证明 {XOR, AND} 不完备,而 {XOR, AND, 1} 完备。
解答
XOR 和 AND 都把 0, 0 映到 0,所以它们组成的任何电路在全零输入上都输出 0:这个集合被困在“保 0”类里,造不出 NOT。加上常数 1 就逃出了这个陷阱;另外四个陷阱已经逃出(AND 不是仿射的、也不是自对偶的,XOR 不是单调的、也不保 1)。具体地,NOT x = x XOR 1, 有了 NOT 和 AND 就有了一切。
-
卡诺图。 化简 f = Σm(1, 3, 4, 5, 9, 11, 12, 13)。
解答
变量为 ABCD 时,这些 1 组成两个四格的组:B'D(最小项 1, 3, 9, 11)和 BC'(4, 5, 12, 13)。所以 f = B'D + BC',两项、 每项两个文字,而范式需要八项、每项四个文字。
-
数函数。 3 个输入的布尔函数有多少个?其中单调的有多少个?
解答
共 2^(2³) = 256 个。对全部 256 张真值表穷举,单调函数有 20 个(戴德金数 M(3)):两个常数、三个变量,以及它们的 与、或组合,例如多数函数。
-
险象。 f = xy' + yz,其中 x = z = 1。
解答
此时 f = y' + y = 1 恒成立,但当 y 变化时,被关掉的那一项可能先于另一项变高(y' 那一项要等反相器),所以在 y 从 1 变 为 0 时 f 会毛刺到 0:yz 立刻变低,而 xy' 要晚一个反相器延迟才变高。xy' 与 yz 的共识项是 xz;加上它,在 y 变化期间 f 保持为 1:f = xy' + yz + xz。
-
动手:用 NAND 搭 4 选 1 多路选择器。
解答
用 NAND 搭的 2 选 1 多路选择器是 NAND(NAND(a, s'), NAND(b, s)),其中 s' = NAND(s, s):四个门。三个这样的选择器组成 4 选 1,第一级的两个共享同一个 s₀ 的反相器:11 个 NAND。库中机械的
mux_n(2).to_nand()给出 24 个(它把每个 AND、OR、NOT 分 别改写,不共享也不化简),深度 9,而手工设计是 5。两者都通过了全部 64 个输入的穷举检查。 -
★ 研究题:四个输入,以及 MCSP。 把
compute_census(在videos/cs/cs3/compute.py里)推广到四个输入的全部 65,536 个函数,重新得到高德纳的结论:最难的需要 7 个门。未解:最小电路规模问题(MCSP)是 NP 完全的吗?已知什么,从哪里入手。 对导线集合做广度优先搜索,六秒就能解决三个输入,到四个输入就爆炸了:不同电路的数目每加一个门大约增长 三十倍,而需要七个门。三个想法让它变得可行。(1)对称性:置换、取反输入以及对输出取反(NPN 群,阶为 2⁴·4!·2 = 768)不改变 代价,所以只需搜索四输入函数的 222 个 NPN 等价类。(2)中间相遇:当 f = g ∘ h 时,f 的代价至多是 g 与 h 的代价之和加一,于是 可以不存储电路、由小代价逐步建立大代价(高德纳的“足迹”方法,TAOCP 7.1.2)。(3)SAT:把“r 个门的电路计算 f”编码成公式交给 求解器;最后几个五输入情形就是这样解决的(Haaswijk、Soeken、Mishchenko 与 De Micheli;Kulikov 等)。正确的答案要这样检验:对每个 等价类,给出一个达到所称规模的电路,并穷举证明不存在更小的。关于 MCSP:它属于 NP;在通常的归约下还不知道它是 NP 难的,而且有 结果表明,用某些自然的归约证明它 NP 难,本身就会推出新的电路下界(Murray 与 Williams,2015)。Hirahara(2022)对部分真值表证明了 NP 难。完整的问题仍然悬而未决。
Build the film
python -m videos.cs.cs3.compute # the part's numbers, into .cache/cs3
python tools/build.py cs3 # render and assemble the film
EXPLAINER_TTS=silent python tools/qa_scene.py cs3 Hook # one chapter, silent, with a contact sheet
Scenes: videos/cs/cs3. Setup: see the course page. Source of these notes: the README and the scenes' narration.
Build it
python -m videos.cs.cs3.compute # every number in the part (about ten seconds)
python tools/build.py cs3 -q l # a 480p preview
python tools/build.py cs3 # 1080p