CComputer Science, Built

Act X · Horizons and Trust

Part 53 of 61

Quantum Computation

Degreestarts at this level52 min of film15 chaptersprerequisites: Part 1, Part 19, Part 27, Part 30

What can a computer made of quantum parts do that no classical computer can, and what can it not?

The part opens with Feynman's question of 1981: n two-state particles need 2^n amplitudes, 16 petabytes for fifty, so can a classical computer simulate quantum physics at all? It starts from the cost of forgetting, Landauer's kT ln 2 per erased bit, and from reversible gates, which are permutations; allowing any unitary turns shuffles into rotations. A qubit is a point on the Bloch sphere, two of them can share a Bell state that wins the CHSH game 85.4% of the time against a classical 75%, and no gate can copy an unknown state. The series' state-vector simulator, about a hundred lines, then runs every algorithm. Interference answers Deutsch and Jozsa's question in one query, Simon's problem separates quantum from classical queries, and the quantum Fourier transform and phase estimation lead to Shor's algorithm, which factors 15 and 21 from spikes at multiples of 2^t / r. The turn is what does not speed up: Grover's search is a rotation that needs about (pi/4) sqrt(N) rounds, no fewer, and overshoots after that. The part closes with error correction, from the three-qubit code to the surface code and its threshold, and at the frontier with BB84, post-quantum standards and the resources RSA-2048 would take.

What you need. Complex numbers, vectors and matrices; no physics is assumed, and the physics itself is in the companion films.

Mathematics, ideas and history
Landauer and reversibility, qubits and the Bloch sphere, interference, Simon, the QFT, Shor, Grover, BQP, error correction and the surface code
What we build or compute
a state-vector simulator factoring 15 and 21

What you will be able to do

Degree

  • Write a qubit as two amplitudes, apply the Born rule, and place the state on the Bloch sphere.
  • Build a Bell state from H and CNOT and show that it does not factor into two qubits.
  • Explain Grover's search as two reflections that rotate the state by 2 theta, and compute the best number of rounds for N items.

Graduate

  • Derive the quantum Fourier transform's circuit from its product formula and count its gates.
  • Run phase estimation on an eigenvalue and bound the probability of the nearest outcome by 4 / pi^2.
  • Reduce factoring to order finding, and recover the order from a measurement by continued fractions.

Research

  • Place BQP between BPP and PSPACE, and state what the oracle separations do and do not show about NP.
  • Compare the published resource estimates for RSA-2048 with today's hardware, and say what error correction below threshold changes.

Industry

  • Simulate a circuit as a state vector, and say what a real device returns in place of the amplitudes.
  • Compute a repetition code's logical error rate at distance d and the factor each step in distance buys.
  • Detect an intercept-and-resend eavesdropper in BB84 from the error rate of the kept bits.

Contents

Each chapter has a home level. Choose a track to see what to read and watch: Degree 24 min · Graduate 46 min · Research 52 min · Industry 31 min.

  1. 0Feynman's questionDegree2 min
  2. 1The cost of forgettingDegree4 min
  3. 2The qubitDegree4 min
  4. 3Gates, tensor products and entanglementDegree4 min
  5. 4Circuits and universalityIndustry3 min
  6. 5Interference as a resourceDegree4 min
  7. 6Bernstein-Vazirani and SimonGraduate4 min
  8. 7The quantum Fourier transformGraduate4 min
  9. 8Phase estimationGraduate4 min
  10. 9Shor's algorithmGraduate3 min
  11. 10Grover's searchDegree3 min
  12. 11What quantum computers cannot doResearch4 min
  13. 12Quantum error correctionIndustry5 min
  14. 13Frontier: keys, chemistry and the hardwareResearch3 min
  15. Recap, problems, and where this comes backAll tracks3 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.

Feynman's questionDegree2 min

In 1981 Richard Feynman gave a talk with a simple question: can a computer simulate physics? For classical physics, yes. But a system of quantum particles is described by one complex number, an amplitude, for every combination of their states. Ten two-state particles need about a thousand amplitudes, which fit in sixteen kilobytes. Twenty need sixteen megabytes. Thirty, sixteen gigabytes; forty, sixteen terabytes; fifty, sixteen petabytes. Three hundred particles need more numbers than there are atoms in the observable universe. Feynman suspected no classical computer could keep up, and proposed the alternative: build the computer out of quantum parts, and let nature do the arithmetic.

Part 1 met the extended Church–Turing thesis: any reasonable computer can be simulated by a probabilistic Turing machine with at most polynomial slowdown. In 1985 David Deutsch described a universal quantum computer. In 1994 Peter Shor showed that such a machine could factor large numbers in polynomial time, which would break the cryptography of Part 30. In 1996 Lov Grover showed it could search an unsorted list in about the square root of its length, and no quantum algorithm can do better. And in 2024 an experiment showed quantum error correction getting better, not worse, as the code grows. If large machines can be built, the extended thesis is false. This part builds the mathematics, and a simulator, and runs every algorithm on it.

1The cost of forgettingDegree4 min

Does computing have to cost energy? Most of the logic we built in Part 3 throws information away. An AND gate takes four possible inputs to two possible outputs. Three different inputs all give a zero, and once you see the zero you cannot say which of them it was. Is that forgetting free? Picture the simplest memory there is: one molecule in a box, with a wall in the middle. Left means zero, right means one. To erase the bit, setting it to zero whatever it held, pull out the wall, push a piston to the middle, and put the wall back. Two possible states have become one. The physics says that lost uncertainty cannot vanish: it ends up in the surroundings, as heat.

In 1961 Rolf Landauer, at IBM, put a number on it. Erasing a bit whose value is unknown takes the memory from two possible states to one. Its entropy falls by Boltzmann's constant times the logarithm of two. The second law of thermodynamics says the total cannot fall, so at least that much entropy must reach the surroundings, carried by heat: at least k T log two. At room temperature, three hundred kelvin, that is about three times ten to the minus twenty-one joules, or eighteen thousandths of an electronvolt, per bit. A billion billion erasures a second at this limit would cost about three milliwatts. Real transistors spend far more than this per switch. In 2012 a team in Lyon measured it, with a glass bead in a two-well laser trap.

The way out is to compute without merging states. Tommaso Toffoli's gate takes three bits and flips the third only if the first two are both one. Its table moves only two of the eight rows, swapping them: it is a permutation, so no two inputs share an output, nothing is lost, and applying it twice gives back the input. Edward Fredkin's gate swaps the second and third bits when the first is one; it even conserves the number of ones, like billiard balls. Neither throws anything away, and yet, with the third input set to zero, Toffoli's gate writes a AND b. Given constant inputs, either gate can build any Boolean circuit at all. Logic does not need to forget.

Now write a reversible gate as a matrix acting on its basis states. Toffoli's gate becomes an eight by eight matrix with a single one in every row and column: a permutation. The NOT gate is the smallest. Permutation matrices are exactly the unitary matrices whose entries are zeros and ones. Allow any unitary, like this one, and the computation stays reversible but is no longer a shuffle of states: it is a rotation. That step was taken in three papers. In 1980 Paul Benioff described a Turing machine as a quantum-mechanical system. In 1982 Feynman proposed simulating physics with a computer made of quantum parts. And in 1985 David Deutsch defined the universal quantum computer. The next chapter meets its unit, the qubit.

2The qubitDegree4 min

What does one quantum bit actually hold? A qubit's state is a vector with two components, called amplitudes: alpha times the state zero, plus beta times the state one. Draw the two basis states as perpendicular axes, and the state as a unit arrow between them. When we measure, we see zero with probability alpha squared and one with probability beta squared. This is the Born rule, from 1926, and it is why the arrow has length one: the probabilities must add to one. Turn the arrow and the odds change smoothly. But an amplitude can also be negative, and in general complex. This arrow gives the same probabilities as the first, yet it is a different state. Probabilities can only add up; amplitudes can cancel, and quantum algorithms are built on that difference.

How many numbers does a qubit need? Alpha and beta are complex, so four real numbers, with one constraint: three are left. Multiply the whole state by a phase and no measurement can tell the difference, so we may drop that overall phase. What remains physical is the relative phase between the two amplitudes, phi. And because the squared sizes add to one, they are the cosine and sine of one angle, which we call theta over two. Two angles: a point on a sphere. The relative phase is invisible to a measurement of zero against one. The plus state and the minus state both give fifty-fifty odds, differing only in one sign. Yet they are as different as two states can be: in the next chapter one gate turns the first into zero and the second into one.

Felix Bloch's sphere draws every state of one qubit as a point on a ball. Theta is the latitude: zero sits at the north pole and one at the south. Tip the arrow down to the equator and we reach the plus state, an equal superposition. Phi is the longitude, the relative phase. Going once round the equator passes the states plus i, minus, and minus i, all with fifty-fifty odds. Notice what the half angle did. Zero and one are perpendicular vectors, but on the sphere they are opposite poles; plus and minus are opposite too. Every pair of orthogonal states sits at the two ends of a diameter. For an electron's spin, the arrow is the axis along which a measurement is certain to find the spin pointing up.

What does a measurement see on the sphere? By the Born rule, the chance of a zero is the cosine squared of half of theta. The double-angle formula turns that into one plus cosine theta, over two. And cosine theta is just the arrow's height, z. The probability of zero is one plus the height, over two: certain at the north pole, impossible at the south, and even anywhere on the equator, whatever the phase. Measurement is not gentle. Afterwards the state is the answer we saw: the arrow has jumped to a pole, and the rest of the information is gone. To ask about a different axis, rotate it to the vertical first, and then measure.

3Gates, tensor products and entanglementDegree4 min

What can two qubits do that two bits cannot? A one-qubit gate is a two by two unitary matrix: on the Bloch sphere, a rotation. The Hadamard gate is a half turn about the axis between x and z, carrying zero to plus. The T gate puts a phase of an eighth of a turn on the one amplitude: an eighth of a turn about the vertical axis. Two T gates make S, a quarter turn, to plus i. A half turn about x carries zero to one: a quantum NOT. Unitary means U dagger times U is the identity: lengths are kept, so probabilities still sum to one, and every gate can be undone.

Now two qubits. Two independent qubits are described by the tensor product of their states. Multiplied out: one amplitude for each of the four outcomes. But any four amplitudes whose squares sum to one are allowed, not only those that factor. Each qubit doubles the count: n qubits have two to the n amplitudes. A product state needs only two n numbers. A state that does not factor is entangled, and in general needs all two to the n: that is why Feynman's simulation runs out of memory.

The basic two-qubit gate is the controlled-NOT, which flips the second qubit when the first is one. Start with both qubits at zero. A Hadamard on the first gives equal amplitudes on zero zero and one zero. The CNOT turns one zero into one one. Our simulator gives half a chance of zero zero, half of one one, and nothing else: a Bell state. Is it two separate qubits? Then alpha delta is zero, so alpha or delta is zero, and one of the surviving amplitudes would vanish too. Contradiction: the state is entangled. Measure either qubit: the result is random, but the other always agrees.

Agreeing on random bits is easy: toss a coin in advance. This game needs more. A referee sends Alice a random bit x and Bob a random bit y, and they cannot talk. They win if the XOR of their answers equals x AND y: they must agree, unless both questions were one. A classical strategy fixes an answer for each question. XOR the four conditions. On the left each answer appears twice and cancels; on the right we get one. So at most three can hold. No classical strategy wins more than three quarters of the time, and our search through all sixteen confirms it.

Give Alice and Bob one qubit each of a Bell pair. Each measures along an angle set by the question; they agree with probability cosine squared of the difference. Alice uses zero or forty-five degrees, Bob plus or minus twenty-two and a half. In three cases the angles differ by twenty-two and a half degrees: agreement with probability cosine squared of pi over eight. In the fourth they differ by sixty-seven and a half, and disagree just as often. About eighty-five percent against seventy-five; our simulator agrees. No message passes. Boris Tsirelson proved in 1980 that no quantum strategy does better, and Part 27's MIP equals RE grew from games like this.

No quantum computer can copy an unknown state; the proof takes three lines. Suppose one unitary machine copies every state: psi to psi psi, phi to phi phi. Take the inner product of the two lines. Unitaries preserve it, so the overlap of phi and psi equals its own square. So the overlap is zero or one: one machine copies only states that are identical or orthogonal. CNOT copies zero and one perfectly, but fed plus it makes a Bell pair, not two pluses: our simulator puts the overlap at one half. This made error correction look impossible, and it is why eavesdroppers get caught.

4Circuits and universalityIndustry3 min

Which gates are enough? Deutsch's quantum circuit model of 1989 is the standard one. Each wire is a qubit, and time runs left to right: here a Hadamard, a CNOT, a T gate, and measurements. Each step is a unitary matrix and the circuit is their product. Matrices act right to left, so the first gate is written last. A gate on one qubit of two is a tensor product with the identity. Written out, each entry of H multiplies a copy of the identity: four by four. With n qubits these matrices are two to the n on a side, so no simulator builds them.

Which gates do we need? Take chapter one's Toffoli gate. It can be built from Hadamards, T gates and their inverses, and CNOTs. Six CNOTs, seven T gates and two Hadamards; multiplied out on our simulator, it is exactly Toffoli's permutation. So anything a classical computer does, a quantum computer can do. In 1995 Adriano Barenco and colleagues showed that CNOT with arbitrary one-qubit gates builds any unitary exactly. The catch is the word arbitrary: one-qubit gates form a continuum, but a real machine offers a short, fixed menu.

Can two fixed gates, H and T, approximate every rotation? Take the product T H T H. H T H is an eighth of a turn about x, and T an eighth of a turn about z. Together they make one rotation, by an angle that is an irrational fraction of a turn. So its powers never return to the start: applied again and again to zero, the points fill a circle around its axis densely. Conjugating by H gives a second axis, and products of the two approach any rotation. T is essential: without it, circuits of H, S and CNOT can be simulated efficiently on an ordinary computer. That is the Gottesman–Knill theorem.

Every result in this part comes from a simulator of about a hundred lines. It keeps all two to the n amplitudes in one array. To apply a gate it views the array as a cube with one axis per qubit, moves the gate's axes to the front, multiplies by the small matrix, and moves them back. A gate on one qubit mixes amplitudes in pairs whose indices differ only in that qubit's bit. On the first qubit the partners are four apart: one stage of Part 19's FFT butterfly, back in chapter seven. Every gate streams through all the amplitudes, sixteen bytes each, doing little arithmetic on each: memory-bound, on the wrong side of Part 9's roofline.

5Interference as a resourceDegree4 min

Where does a quantum speed-up come from? Flip a fair coin, then flip it again. Probabilities multiply along each path and add across paths, and after two flips the outcome is still a coin flip. Now apply a Hadamard to zero, twice. Amplitudes also multiply along paths and add across them, but they carry signs. One path to one picks up a minus sign. So the two paths to one cancel, and the two paths to zero reinforce: the result is zero, with certainty. The algebra says the same in two lines. That cancellation is interference, and a randomized algorithm, whose probabilities can only add, cannot do it.

First we need the function as a gate. The oracle maps x and y to x and y exclusive-or f of x. It is reversible, and chapter one's compute, copy, uncompute builds it from any classical circuit without leaving garbage behind. Now feed the target the minus state. If f of x is zero, nothing flips. If f of x is one, the two terms of the minus state swap places, which is the same state times minus one. Either way the target comes out unchanged, and the input has picked up a sign, minus one to the f of x. The answer has been kicked back into the phase. On a single basis state a sign is invisible, but in a superposition it is a relative sign, and relative signs interfere.

David Deutsch's problem of 1985 is the first in which interference wins. A function takes one bit to one bit. Are its two values equal? Classically you must evaluate it twice. Put the input qubit in an equal superposition and the target in the minus state. One query kicks both answers into the phases at once. Factor out the first sign, and what remains has a plus where the values agree and a minus where they differ. A final Hadamard turns plus into zero and minus into one. Constant functions always give zero, balanced ones always give one, from a single query. The circuit never learns either value of f, only the one fact we asked for.

In 1992 Deutsch and Richard Jozsa scaled this up to n bits. The function is promised to be either constant, or balanced, zero on exactly half its inputs. Hadamards on four qubits give sixteen equal amplitudes. The oracle stamps a sign on each, and Hadamards again bring them together. For a constant function every sign agrees, and all the amplitude piles onto zero zero zero zero. For a balanced function, the signs cancel exactly there, and the amplitude lands somewhere else, a different place for each function. Why? The amplitude of all zeros after the last Hadamards is the average of the signs: plus or minus one if f is constant, zero if it is balanced. Our simulator measures all zeros with probability one or zero. A deterministic classical algorithm would need nine evaluations in the worst case; this needs one.

This is the recipe for the next five chapters. Spread out over every input with Hadamards; mark each input's answer in its phase with the oracle; then apply a transform under which the wrong answers cancel. It is tempting to say a quantum computer tries every answer in parallel. But measure right after the oracle and you get one random input and its value, no better than one classical query. The gain is all in the third step. And we should be honest about Deutsch–Jozsa. Its advantage is over certainty. A randomized classical test that checks k random inputs is fooled by a balanced function with probability at most two to the one minus k. Ten queries, and it is almost never wrong. An exponential gap against randomized algorithms needs a harder problem, and Daniel Simon found one.

6Bernstein-Vazirani and SimonGraduate4 min

Can a quantum computer be exponentially faster? Ethan Bernstein and Umesh Vazirani, in 1993, hid a whole string in a function. The function takes x to the parity of the bits that x shares with a secret string s. Classically each query returns one bit, so the best you can do is ask about one position at a time: four queries for four bits, n for n. Quantumly, run the same circuit as Deutsch–Jozsa. The oracle stamps the sign minus one to the s dot x on every input. But that pattern of signs is exactly what Hadamards make from the string s, by chapter five's formula read backwards. Hadamard undoes itself, so the final Hadamards return s. Our simulator measures one zero one one, the secret, with probability one, from a single query.

In 1994 Daniel Simon found a problem with an exponential gap. A function on n-bit strings is promised to be two-to-one in a special way: two inputs collide exactly when they differ by a hidden string s, under exclusive-or. Find s. Here are the eight inputs for three bits. Each colour is a pair, x and x exclusive-or s. Classically the only clue is a collision, two inputs with the same output; their exclusive-or is s. With q queries there are about q squared over two pairs, each a collision with probability one in one less than two to the n. So the first collision needs about two to the n over two queries. That is Part 17's birthday bound, and Simon proved that no classical algorithm, even a randomized one, does much better.

Simon's circuit has two registers. Hadamards spread the first over every input, and one query writes f of x into the second. Suppose the second register reads some value. Two inputs give that value, x nought and x nought exclusive-or s, so the first register is left in an equal superposition of exactly those two. Apply Hadamards again. Each output y receives two contributions, with signs that agree when y dot s is zero and are opposite when it is one. So every y with y dot s equal to one cancels. What survives, all with equal probability, are the y orthogonal to s. One run gives one random linear equation that s must satisfy.

Now collect equations. Our simulator's first run gave one one zero: so the first two bits of s are equal. The second gave nought nought one: the last bit of s is zero. Watch the candidates. Seven nonzero strings could be s. The first equation rules out four of them, the second rules out two more. One is left, one one zero, and it is the hidden string. In general n minus one independent equations determine s. Each run gives a new independent equation with probability at least a half, and on average a little over n runs are enough, and Gaussian elimination, modulo two, finishes the job: polynomial in n, against the classical two to the n over two.

7The quantum Fourier transformGraduate4 min

Can two to the n amplitudes be transformed with about n squared gates? Part 19 met the discrete Fourier transform, and the fast algorithm that computes it. The quantum version is the same transform applied to amplitudes: basis state j goes to an equal superposition of every k, with phase omega to the j k. Omega is a root of unity, a fraction of a turn round the circle; for eight points, an eighth of a turn. Draw each entry of the matrix as an arrow at its phase. Row one turns an eighth of a turn per column, row two a quarter, and so on. It is exactly Part 19's matrix, scaled by one over root N so that it is unitary. Classically, the FFT needs about N log N operations on N numbers. For two to the n numbers, that is exponential in n.

Here is the fact that makes the quantum transform cheap. Write the output index k in binary. The phase of each term splits into one factor per bit of k, and a sum over all bit strings of a product is a product of sums. So the transform of a basis state is a product of n single qubits, each an equal mix of zero and one with its own phase. Whole turns do nothing, so the l-th qubit's phase only sees the last l bits of j, read as a binary fraction. For j equals five on three qubits: half a turn, a quarter turn, and five eighths. Nothing is entangled. Each output qubit needs only a Hadamard and a few rotations.

Count the gates. On four qubits: the first gets a Hadamard and three controlled rotations, the next a Hadamard and two, and so on down, then two swaps. Qubit l needs one Hadamard and n minus l rotations, so the total is n times n plus one over two, plus n over two swaps: order n squared gates for two to the n points. Our simulator runs this circuit on a random state and compares it with numpy's FFT. They agree to rounding error, about ten to the minus sixteen. On eight qubits the circuit has forty gates, where the FFT needs two thousand and forty-eight operations, and the gap grows exponentially with n.

So what is it good for? Feed it a periodic state: four equal amplitudes, four apart, starting at one. After the transform, all the amplitude sits on multiples of sixteen over four, and everything between has interfered away. The offset has moved into the phases, shown here as colour, and the period into where the peaks are. A measurement then samples a multiple of N over r, which is exactly what Shor's algorithm needs in chapter nine. What it is not good for: reading out Fourier coefficients. One run yields one sample. And loading arbitrary data into amplitudes costs as much as the data. In 1994 Don Coppersmith also showed that the tiniest rotations can be dropped, leaving order n log n gates for a close approximation.

8Phase estimationGraduate4 min

How do we read an eigenvalue? Every unitary has eigenvectors, states it only multiplies by a number. Because a unitary keeps lengths, that number has size one: it is a point on the unit circle, e to the two pi i theta. Applied to the eigenvector alone, the phase is global, and no measurement can see it. So control the unitary from a qubit in the plus state. The eigenvector comes out unchanged, and the phase is kicked back onto the control, as in chapter five. On the control's Bloch sphere, seen from above, its arrow turns about the vertical axis by two pi theta. Here theta is nought point three, a turn of a hundred and eight degrees. The question of this chapter is how to read that angle to many bits.

One qubit turned by theta gives at best a bit or two of theta. To get many bits, ask more qubits. Put t counting qubits in the plus state. The first controls U once, the next U twice, then four times, and so on, doubling. Each control picks up two to the k times theta, with whole turns dropped. For theta nought point three: three tenths, six tenths, two tenths, four, eight, and six again. Doubling shifts the binary point of theta, so each qubit holds theta's bits from one place onward. Multiply the qubits out, and the state is a sum over j of e to the two pi i j theta. That is exactly the product form of chapter seven. If theta is m over two to the t, the counting register holds the Fourier transform of m.

Run the inverse Fourier transform on the counting register. The amplitude of outcome m is an average of T phases, each turning by theta minus m over T per step. Draw the terms as arrows, head to tail. For the m nearest to theta times T, they turn slowly and nearly line up, and the average is long. One outcome further on, they turn faster, curl most of the way round, and largely cancel. Interference again. The sum is a geometric series, and its size gives the probability of each outcome. For the nearest m, the leftover angle is at most half a step, and then the probability is at least four over pi squared, about forty per cent. In fact it is usually far more, and if theta is exactly m over T, it is one.

Here is our simulator's run: theta nought point three, six counting qubits. The distribution over the sixty-four outcomes. Theta times sixty-four is nineteen point two, between two outcomes, and the peak is at nineteen, measured with probability nought point eight seven five. In binary that reads nought point nought one nought nought one one, nineteen sixty-fourths, nought point two nine six eight seven five: theta to six bits. Because nineteen point two is not a whole number, some probability leaks to the neighbours, twenty and eighteen. Each extra counting qubit halves the error, and a few more qubits than the bits we want make a wrong answer rare.

9Shor's algorithmGraduate3 min

How does finding a period factor a number? Part 30's RSA rests on factoring being hard. Shor reduced factoring to finding a period. List the powers of seven modulo fifteen: one, seven, four, thirteen, and then one again. The sequence repeats with period four, the order of seven. If the order r is even, a to the r minus one is a multiple of N, and it splits as a difference of squares. Unless a to the r over two is minus one, N divides neither bracket, so each shares a proper factor with N, and Euclid's algorithm finds it: forty-eight and fifty give three and five. A random a works at least half the time, and everything is fast except finding r.

Chapter eight promised that order finding is phase estimation. Multiplication by a modulo N is reversible, since a has an inverse, so it is a unitary, U. From one, it walks round a cycle: one, seven, four, thirteen, and back. Spread a state round the cycle, twisting its phase by s over r of a turn at each step. U moves every term one step on, and the twist comes out as a phase: an eigenvector, with eigenvalue e to the two pi i s over r. Add all r eigenvectors, and the twists cancel everywhere except at one. So the plain state one is an equal superposition of them. Phase estimation on it returns s over r, for a random s. The controlled powers come from repeated squaring, and this arithmetic, about n cubed gates, is most of the cost.

Our simulator factors fifteen, with a equal to seven, using nine counting qubits, twice fifteen's four bits plus one: five hundred and twelve outcomes. After the inverse Fourier transform, all the probability sits on four spikes, a quarter each, at the multiples of five hundred and twelve over four, as chapter seven predicted. Three hundred and eighty-four over five hundred and twelve is three quarters, and its denominator is the order, four. A shot at two hundred and fifty-six gives one half, because s and r shared a factor, and a shot at nought gives nothing. Nine of our twenty shots found four at once. One honest caveat: our simulator writes a to the x modulo N straight into the work register.

The best known classical method, Part 30's number field sieve, takes time growing roughly like e to the cube root of the number of bits. Shor's algorithm needs about n cubed gates. On a logarithmic scale, one curve keeps climbing and the other barely rises. The sieve's record, RSA-250, eight hundred and twenty-nine bits, took about two thousand seven hundred core-years in 2020. Shor's method also finds discrete logarithms, so Diffie–Hellman and elliptic curves fall with RSA. A caution: early hardware runs that factored fifteen and twenty-one used circuits simplified with knowledge of the answer, as Smolin, Smith and Vargo pointed out in 2013.

10Grover's searchDegree3 min

How fast can a quantum computer find a needle? Grover's algorithm looks for one marked item w among N, using an oracle that flips the sign of w's amplitude. Everything happens in a plane: the marked state, and the even superposition of the unmarked ones. The starting state sits a small angle theta above the unmarked axis, with sine theta equal to one over root N. The oracle reflects the state in the unmarked axis. The diffusion step reflects it in the starting state. Two reflections make a rotation by twice the angle between the mirrors: two theta. After k rounds the angle is two k plus one, times theta. Here N is sixty-four, and six rounds carry the state just past vertical.

The same rounds, seen as the sixty-four amplitudes. At the start they are all equal, one eighth each. The oracle flips the marked amplitude below the axis. On amplitudes the diffusion step means: replace each one by twice the mean minus itself, an inversion about the mean. The mean has dropped a little, so the unmarked amplitudes shrink slightly, while the marked one, far below the mean, jumps far above it. Repeat. After six rounds the marked amplitude is nought point nine nine eight. Keep going and it falls again, as the unmarked amplitudes turn negative: the rotation has overshot.

Our simulator's success probability against the number of rounds follows the formula exactly: sine squared of two k plus one, times theta. It peaks when the angle reaches a right angle, after about pi over four times root N rounds: for sixty-four items, six rounds, and success ninety-nine point seven per cent. Run longer and it falls: after twelve rounds it is almost zero, and then it climbs again. Unlike a classical search, more work can make the answer worse. As N grows, the rounds grow like root N, while a classical search in random order needs about N over two looks on average: for sixty-five thousand items, two hundred and one rounds against about thirty-two thousand looks.

Could a cleverer algorithm beat root N? No. Compare each run with a run whose oracle marks nothing. One query can push the two apart by at most twice the amplitude the algorithm puts on w at that moment. Add over all N choices of w. Those amplitudes square to one in total, so they sum to at most root N, and T queries move all the runs apart by at most two T root N in total. But to name w, every one of the N runs must end a fixed distance from the run that marks nothing. So T is at least a constant times root N, as Bennett, Bernstein, Brassard and Vazirani proved in 1997. Brute-force search over n-bit keys drops only from two to the n to two to the n over two: still exponential.

11What quantum computers cannot doResearch4 min

Where does BQP sit among the classes? What exactly can a quantum computer do efficiently? The class is BQP, defined by Bernstein and Vazirani in 1993. A problem is in it if, for inputs of n bits, a classical program can write down in polynomial time a circuit of polynomially many gates from chapter four's set, ending in the measurement of one qubit. On yes-instances it accepts with probability at least two thirds; on no-instances, at most one third. The thirds are arbitrary: run it k times and take the majority, and the error falls exponentially in k, as for Part 27's BPP. And BQP contains BPP: chapter one's Toffoli gates make any classical circuit reversible, and a Hadamard on a fresh qubit is a fair coin.

Where does BQP sit among the classical classes? It contains BPP, as we saw. For an upper bound, write the amplitude of an outcome as Feynman did: a sum over every path through the intermediate basis states, multiplying along each path and adding across paths, as in chapter five. With only Hadamard and Toffoli gates, which suffice for any quantum computation, every path weighs plus or minus the same small number. The amplitude is the count of positive paths minus the count of negative ones, scaled. A classical machine can add the paths one at a time, reusing its memory: exponential time, but polynomial space. And comparing the counts puts BQP inside PP, as Adleman, DeMarrais and Huang showed in 1997. None of these inclusions is known to be strict.

Does BQP contain the NP-complete problems? Nobody knows, but the evidence says no. Here is the picture most researchers believe, though none of it is proved. Factoring and discrete logarithms lie in BQP and in NP, and are not thought to be NP-complete. The NP-complete problems sit outside BQP. Brute force gains only a square root: sixty-five thousand assignments of sixteen variables still need two hundred and one Grover rounds. And relative to a random oracle, Bennett, Bernstein, Brassard and Vazirani showed that NP is not inside BQP. A fast quantum algorithm would have to exploit structure, as Shor's does. BQP may also reach outside NP: relative to an oracle, Raz and Tal showed in 2018 that it escapes the whole polynomial hierarchy.

If quantum computers are more powerful, an experiment should show it. In 2011 Scott Aaronson and Alex Arkhipov, and independently Bremner, Jozsa and Shepherd, identified sampling tasks natural for quantum hardware and, under complexity assumptions, hard for classical machines: an efficient exact classical sampler would collapse the polynomial hierarchy. In 2019 Google's team reported sampling from random circuits on fifty-three qubits in about two hundred seconds, and estimated ten thousand years for a supercomputer. IBM replied that, with better use of disk storage, a supercomputer would need about two and a half days. In 2020 a team in China reported a photonic version. By 2022, tensor-network methods had simulated the 2019 task. The contest goes on, and the extended Church–Turing thesis is now being tested in the laboratory.

12Quantum error correctionIndustry5 min

How do we protect a state we may neither copy nor look at? Part 28 protected bits by copying them and reading the copies. For qubits all three ideas seemed to fail, and some leading physicists doubted that quantum computers could be made reliable. First, chapter three's no-cloning theorem forbids copies. Second, reading a qubit destroys it: measure a superposition, and you are left with zero or one. Third, errors are continuous: a qubit can drift by any small angle. In 1995 Peter Shor found a way round all three, and Andrew Steane another in 1996: spread the state by entanglement, and measure only parities, which reveal the error but nothing about the state.

The simplest code protects against bit flips. Two CNOTs spread one qubit over three, as one entangled state, not three copies. Suppose the middle qubit flips. Measure two parities, using extra qubits: does the first agree with the second, and the second with the third? Both terms give the same answers, so we learn where the error is and nothing about the amplitudes. Each single flip lights a different pattern, the syndrome, as with Part 28's Hamming code. Flip the culprit back, and our simulator recovers the original amplitudes in all four cases.

The third obstacle, continuous error, dissolves when the syndrome is measured. A small unwanted rotation by epsilon is a combination of doing nothing and a full bit flip. Applied to the encoded state, it makes a superposition of no error and one whole flip. Measuring the syndrome forces a choice: with probability cosine squared epsilon, no error; with sine squared epsilon, a whole flip, which we know how to undo. And any error on one qubit is a combination of four: nothing, a bit flip, a phase flip, or both. Correct bit flips and phase flips, and everything else is corrected.

Qubits suffer a second kind of error: a phase flip, which turns plus into minus. In the Hadamard basis a phase flip is a bit flip, so the same code, turned sideways, catches it. Shor nested the two: three blocks against phase flips, and each block three qubits against bit flips, nine in all. A phase flip anywhere in a block changes that block's sign, and the checks comparing neighbouring blocks light up. Every check is a product of Pauli operators that leaves each codeword alone. Daniel Gottesman's stabilizer formalism of 1997 describes whole families of codes this way: here eight checks on nine qubits leave one logical qubit.

The leading design today is the surface code, from Alexei Kitaev's toric code of 1997, developed by Dennis, Kitaev, Landahl and Preskill, and by Fowler and colleagues in 2012. Data qubits sit on the corners of a grid. Each face measures the parity of its corners: blue faces catch bit flips, purple faces phase flips, and every check touches only near neighbours. A bit flip lights the blue faces beside it. A chain of flips lights only its two ends, and a decoder pairs the lit faces by the shortest chains that explain them. Only a chain right across the lattice goes unseen: at distance five that takes five errors, and any two are corrected.

Take the simplest case: the repetition code against independent bit flips. With distance d and a majority vote, the code fails only if more than half the bits flip. For small p the first failing term dominates, so the logical error falls like p to the power d plus one over two. Below the threshold, here one half, a bigger code is better: at one per cent, each step in distance divides the error by about thirty. Above it, bigger is worse. Real codes under real noise have thresholds near one per cent. In 2024 Google's team grew a surface code from distance three to five to seven, and each step roughly halved the logical error: clearly below threshold, in hardware.

13Frontier: keys, chemistry and the hardwareResearch3 min

What will quantum computers actually change, and when? Quantum mechanics also protects secrets. In Bennett and Brassard's protocol of 1984, Alice sends random bits, each encoded in one of two bases chosen at random. Bob measures each in a random basis, and afterwards they compare bases in public and keep only the positions where they agreed. With nobody listening, our simulation's kept bits agree perfectly. An eavesdropper must measure to learn anything, and measuring in the wrong basis disturbs the state: a quarter of the kept bits come out wrong, and Alice and Bob notice. The more urgent defence needs no quantum hardware at all. In 2024 the United States standards body NIST published post-quantum algorithms that replace RSA and elliptic curves with lattice and hash-based problems not known to fall to Shor's algorithm, and the migration is under way, because data recorded today could be decrypted later.

How far away is a machine that breaks today's cryptography? Resource estimates have fallen fast. In 2019 Craig Gidney and Martin Ekerå estimated that factoring a 2048-bit RSA key would take about twenty million noisy qubits for about eight hours. In 2025 Gidney brought that under a million qubits, in under a week. Both assume physical error rates of about one in a thousand, and the surface code of chapter twelve; today's largest machines have hundreds to about a thousand physical qubits. The decisive step is error correction that improves as the code grows, and in 2024 Google's team showed it: each step up in distance roughly halved the logical error rate. Our repetition code does far better on paper, but it only corrects bit flips, while a real code must also catch phase errors.

What are they likely to be good for? First, Feynman's own problem: simulating molecules and materials whose electrons are too entangled for classical methods, where a quantum computer simply is the right kind of machine. Second, cryptanalysis, which is why the migration to new cryptography has already begun. Elsewhere the case is weaker. Several proposed quantum speedups for recommendation systems and optimization were matched by new classical algorithms once examined closely, starting with Ewin Tang's in 2018. Claims of quantum advantage on sampling tasks, from 2019 on, have repeatedly been challenged by better classical simulations. The contest continues, which is how it should be.

Recap, problems, and where this comes backAll tracks3 min

What we built in this part. The energy cost of erasing a bit, and reversible computation that avoids it. The qubit, a unit vector of two complex amplitudes, and gates that rotate it on the Bloch sphere. Entanglement, which wins a game no classical strategy can, and the theorem that forbids copying. Interference as the resource behind every algorithm: Deutsch–Jozsa, Bernstein–Vazirani and Simon. The quantum Fourier transform, built from Part 19's butterflies; phase estimation; Shor's algorithm, factoring fifteen and twenty-one on our own simulator; Grover's square-root search, and the proof that it cannot be beaten; and error correction, which turns many noisy qubits into fewer good ones.

Where this comes back. Part 54 proves programs correct, and the same logic extends to quantum ones. Part 55 asks what we can trust, the post-quantum migration included. Part 56's expander graphs build good codes, classical and quantum. Part 58 gives programs mathematical meaning. And Part 60 builds hardware for a single job, which is what every quantum computer is today.

In practice. Find every place your systems rely on RSA or elliptic curves, and plan the move to the new standards. Experiment with small circuits in an open-source toolkit, on a simulator first. A laptop holds a full state vector of about thirty qubits; tensor networks go further for shallow circuits. Judge any claimed speedup against the best classical algorithm, not the naive one. And watch logical error rates, not raw qubit counts.

Six problems, with full solutions in the part's notes. Pause on any of them. The fifth is a build problem: run Shor's algorithm on thirty-five with our simulator, and count how many runs it takes to find the order. The last, marked with a star, is a research problem: the smallest machine that can factor a 2048-bit number, and a proof that nothing smaller can.

Next time, Part 54: proving programs correct. Testing can show the presence of bugs but never their absence. Floyd and Hoare turned programs into logical formulas, and today whole compilers and operating system kernels come with machine-checked proofs.

The books and papers this part follows are on screen and in the notes. Thank you for watching.

Where it goes next. Part 54 proves programs correct, and the same logic extends to quantum ones. Part 55 asks what can be trusted, the post-quantum migration included. Part 56's expander graphs build good codes, classical and quantum, and Part 60 returns to the hardware.

Key results

The part's results in one place, for revision.

Landauer's principle\(\displaystyle Q\ \ge\ kT\ln 2\ \text{ per }\allowbreak \text{erased }\allowbreak \text{bit}\)
The CHSH game\(\displaystyle P_{\text{classical}}\le\tfrac34,\qquad\allowbreak P_{\text{quantum}}=\cos^{2}\tfrac{\pi}{8}\approx 0.854\)
Quantum Fourier transform\(\displaystyle |j\rangle\ \mapsto\ \frac{1}{\sqrt N}\sum_{k=0}^{N-1}e^{2\pi i jk/N}\,|k\rangle,\quad\allowbreak \tfrac{n(n+1)}{2}+\lfloor\tfrac n2\rfloor \text{ gates}\)
Phase estimation\(\displaystyle |a_m|^{2}\ \ge\ \frac{4}{\pi^{2}}\ \text{ for }\allowbreak \text{the }\allowbreak \text{nearest } m \text{ to } 2^{t}\theta\)
Shor's reduction\(\displaystyle a^{r}\equiv 1\ (\mathrm{mod}\ N),\ r \text{ even}:\quad\allowbreak \gcd\bigl(a^{r/2}\pm 1,\ N\bigr)\)
Grover's rotation\(\displaystyle \sin\theta=\frac{1}{\sqrt N},\qquad\allowbreak P_k=\sin^{2}\bigl((2k+1)\theta\bigr),\qquad\allowbreak k\approx\frac{\pi}{4}\sqrt N\)

Try it

Lab 53 · Five quantum claims, each checked on a state-vector simulator

Search 64 items with Grover's two reflections and compare every round with sin^2((2k+1) theta), check the QFT circuit against numpy's FFT, factor 15 and 21 from sampled measurements by continued fractions, play the CHSH game, and measure how fast a repetition code suppresses errors.

Figure produced by Lab 53: Five quantum claims, each checked on a state-vector simulator
Produced by the lab below, seed 0, in 0.2 s.
python -m videos.cs.labs 53 needs numpy, scipy, matplotlib · download lab53.py · source on GitHub
Grover, 64 items, marked item 54         success after 0, 3, 6, 12 rounds: 0.016, 0.591, 0.9966, 0.0001; largest gap to the formula 3e-14
rounds for N = 16 ... 65,536             3, 6, 12, 25, 50, 100, 201   (pi/4 sqrt N)
QFT on 6 qubits against numpy's FFT      largest difference 2.0e-16; 24 gates against 384 operations for the FFT
Shor, N = 15, a = 7, 9 counting qubits   order 4 from 9 of 20 shots; gcd(7^2 ± 1, 15) = 3 and 5
Shor, N = 21, a = 2, 11 counting qubits  order 6 from 7 of 20 shots; gcd(2^3 ± 1, 21) = 3 and 7
CHSH game                                best of 16 classical strategies 0.75; Bell pair 0.8536 = cos^2(pi/8), sampled 0.8546
repetition code at p = 1%                logical error 3.0e-04 at distance 3, 9.9e-06 at 5: each step divides it by 30

Grover's search is a rotation and stops paying after pi/4 sqrt(N) rounds; Shor's measurements land on multiples of Q/r and arithmetic does the rest; and error correction works only below a threshold, where distance buys an exponential suppression.
The code (103 lines; it asserts its own result)
"""Lab 53: run Grover, the QFT, Shor's order finding, the CHSH game and the repetition code on the series' simulator."""

from videos.coursekit import labs  # noqa: I001  (must stay first: it lets explainer.cs import without manim)

import math

import numpy as np

from explainer.cs.quantum import algorithms, qec

TITLE = "Five quantum claims, each checked on a state-vector simulator"
GOAL = ("Search 64 items with Grover's two reflections and compare every round with sin^2((2k+1) theta), check the "
        "QFT circuit against numpy's FFT, factor 15 and 21 from sampled measurements by continued fractions, play "
        "the CHSH game, and measure how fast a repetition code suppresses errors.")
TASKS = [
    "Run algorithms.grover with n = 8 and max_iters = 40. Where is the first peak, where is the first trough, and what do pi/4 times sqrt(N) and the formula's period predict?",
    "Factor 21 with a = 5 instead of a = 2. What is the order, does it give factors, and which values of a fail because the order is odd or a^(r/2) = -1?",
    "In qec.repetition, read the logical error at p = 0.4 and at p = 0.6 for distances 3 to 11. On which side of p = 1/2 does adding distance help, and why?",
]


def order_from_samples(o):
    """The classical half of Shor: the smallest denominator r from the continued fractions with a^r = 1 mod N."""
    good = [s["r"] for s in o["samples"] if s["ok"]]
    return min(good) if good else None


def run(seed=0):
    rng = np.random.default_rng(seed)
    lab = labs.Lab()

    # 1. Grover: a rotation by 2 theta each round, so the success probability is sin^2((2k + 1) theta), exactly
    marked = int(rng.integers(0, 64))
    g = algorithms.grover(n=6, marked=marked, max_iters=20)
    gap = max(abs(a - b) for a, b in zip(g["probs"], g["formula"]))
    assert gap < 1e-9, "the simulated amplitudes follow the rotation formula"
    assert g["best_iters"] == 6 and g["p_best"] > 0.99 and g["probs"][12] < 0.01, "six rounds, and twelve overshoot"
    lab.row(f"Grover, 64 items, marked item {marked}", f"success after 0, 3, 6, 12 rounds: {g['probs'][0]:.3f}, "
            f"{g['probs'][3]:.3f}, {g['probs'][6]:.4f}, {g['probs'][12]:.4f}; largest gap to the formula {gap:.0e}")
    scale = algorithms.grover_scaling()
    assert all(abs(r["iterations"] - math.pi / 4 * math.sqrt(r["N"])) < 1 for r in scale)
    lab.row("rounds for N = 16 ... 65,536", ", ".join(str(r["iterations"]) for r in scale) + "   (pi/4 sqrt N)")

    # 2. the QFT circuit is the discrete Fourier transform, in n(n+1)/2 + n/2 gates
    q = algorithms.qft_check(n=6, seed=seed)
    assert q["max_diff_fft"] < 1e-12 and q["gates"] == 24
    lab.row("QFT on 6 qubits against numpy's FFT", f"largest difference {q['max_diff_fft']:.1e}; {q['gates']} gates "
                                                   f"against {q['fft_ops']} operations for the FFT")

    # 3. Shor: sampled measurements, continued fractions, then two gcds
    shor = {}
    for N, a in ((15, 7), (21, 2)):
        o = algorithms.order_finding(a, N, shots=20, seed=seed)
        r = order_from_samples(o)
        assert r == o["r"], "the continued fractions recover the order"
        assert sum(o["probs"][y] for y in o["peaks"]) > 0.6, "the probability sits on multiples of Q / r"
        f = sorted({math.gcd(pow(a, r // 2) - 1, N), math.gcd(pow(a, r // 2) + 1, N)})
        assert f[0] * f[1] == N and 1 < f[0] < N
        shor[N] = o
        lab.row(f"Shor, N = {N}, a = {a}, {o['t']} counting qubits", f"order {r} from {sum(s['ok'] for s in o['samples'])} of 20 "
                f"shots; gcd({a}^{r // 2} ± 1, {N}) = {f[0]} and {f[1]}")

    # 4. CHSH: a shared Bell pair beats every classical strategy
    c = algorithms.chsh(trials=100_000, seed=seed)
    assert abs(c["quantum"] - math.cos(math.pi / 8) ** 2) < 1e-12 and c["classical"] == 0.75
    assert abs(c["sampled"] - c["quantum"]) < 4 * math.sqrt(0.125 / 100_000)
    lab.row("CHSH game", f"best of 16 classical strategies {c['classical']:.2f}; Bell pair {c['quantum']:.4f} = cos^2(pi/8), "
                         f"sampled {c['sampled']:.4f}")

    # 5. the repetition code: below threshold, each step in distance divides the logical error rate
    ps = [0.01, 0.05, 0.1, 0.2, 0.3, 0.4, 0.5]
    rep = qec.repetition(ds=(1, 3, 5, 7), ps=ps, trials=100_000, seed=seed)
    for r in rep["rows"]:
        assert abs(r["simulated"] - r["exact"]) < 5 * math.sqrt(max(r["exact"], 1e-6) / 100_000), (r["d"], r["p"])
    at = {(r["d"], r["p"]): r["exact"] for r in rep["rows"]}
    assert all(abs(at[(d, 0.5)] - 0.5) < 1e-12 for d in (1, 3, 5, 7)), "no distance helps at p = 1/2"
    lam = rep["lambda"]["0.01"][0]
    assert 25 < lam < 35
    lab.row("repetition code at p = 1%", f"logical error {at[(3, 0.01)]:.1e} at distance 3, {at[(5, 0.01)]:.1e} at 5: "
                                         f"each step divides it by {lam:.0f}")
    lab.note = ("Grover's search is a rotation and stops paying after pi/4 sqrt(N) rounds; Shor's measurements land "
                "on multiples of Q/r and arithmetic does the rest; and error correction works only below a "
                "threshold, where distance buys an exponential suppression.")

    fig, ax = labs.figure(2, size=(11, 4.3))
    k = np.arange(21)
    fine = np.linspace(0, 20, 300)
    ax[0].plot(fine, np.sin((2 * fine + 1) * g["theta"]) ** 2, color=labs.GOLD, label="sin^2((2k + 1) theta)")
    ax[0].plot(k, g["probs"], "o", color=labs.BLUE, label="simulated, 6 qubits")
    ax[0].plot(k, 1 - np.cumprod(np.concatenate([[1.0], (63 - k[:-1]) / (64 - k[:-1])])), color=labs.MUTED, ls="--",
               label="classical: k looks")
    ax[0].set(title="Grover's search among 64 items", xlabel="rounds k", ylabel="chance of finding the marked item",
              ylim=(-0.03, 1.38))
    ax[0].set_yticks([0, 0.25, 0.5, 0.75, 1.0])
    ax[0].legend(loc="upper left", ncol=3, fontsize=8)
    o = shor[21]
    ax[1].plot(np.arange(o["Q"]), o["probs"], color=labs.BLUE, lw=1.0, label="P(measure y)")
    ax[1].plot(o["peaks"], [o["probs"][y] for y in o["peaks"]], "o", color=labs.GOLD, label="multiples of 2048 / 6")
    ax[1].set(title="Shor on 21 with a = 2: the counting register", xlabel="measured value y (of 2,048)",
              ylabel="probability", ylim=(0, 0.215))
    ax[1].legend(loc="upper right", ncol=2)
    lab.fig = fig
    return lab

Now change it

  1. Run algorithms.grover with n = 8 and max_iters = 40. Where is the first peak, where is the first trough, and what do pi/4 times sqrt(N) and the formula's period predict?
  2. Factor 21 with a = 5 instead of a = 2. What is the order, does it give factors, and which values of a fail because the order is odd or a^(r/2) = -1?
  3. In qec.repetition, read the logical error at p = 0.4 and at p = 0.6 for distances 3 to 11. On which side of p = 1/2 does adding distance help, and why?

Problems, with solutions

Try each problem before opening its solution.

  1. No-cloning. Prove that no unitary U maps |ψ⟩|0⟩ to |ψ⟩|ψ⟩ for every state |ψ⟩.

    Solution

    Suppose U|ψ⟩|0⟩ = |ψ⟩|ψ⟩ and U|φ⟩|0⟩ = |φ⟩|φ⟩ for two unit vectors. A unitary preserves inner products, so the inner product of the two left sides equals that of the two right sides: ⟨φ|ψ⟩⟨0|0⟩ = ⟨φ|ψ⟩², that is x = x² with x = ⟨φ|ψ⟩. So x = 0 or x = 1: the states are orthogonal or, by Cauchy–Schwarz, equal. A machine that copied every state would copy |0⟩ and |+⟩, whose overlap is 1/√2, a contradiction. Linearity gives the same answer directly: if U copies |0⟩ and |1⟩, then U|+⟩|0⟩ = (|00⟩ + |11⟩)/√2, a Bell pair, not |+⟩|+⟩ = (|00⟩ + |01⟩ + |10⟩ + |11⟩)/2; their overlap is 2 · (1/√2)(1/2) = 1/√2 and the fidelity 1/2, which is what our simulator's CNOT gives (0.50). Extra working space does not help: if U|ψ⟩|0⟩|0⟩ = |ψ⟩|ψ⟩|e_ψ⟩, then x = x²⟨e_φ|e_ψ⟩, so |x| ≤ |x|² and |x| is 0 or 1 again. The theorem forbids copying unknown states, not known orthogonal ones: CNOT fans out basis states, which is why classical bits can be copied.

  2. CHSH. Show that the CHSH game's classical value is 3/4, and that the quantum strategy achieves cos²(π/8).

    Solution

    A deterministic strategy fixes Alice's answers a₀, a₁ and Bob's b₀, b₁. Winning on all four questions needs a₀ ⊕ b₀ = 0, a₀ ⊕ b₁ = 0, a₁ ⊕ b₀ = 0 and a₁ ⊕ b₁ = 1. The XOR of the left sides is 0, since each variable appears twice, and the XOR of the right sides is 1, so at most three hold, and with uniform questions the strategy wins at most 3/4; always answering 0 achieves it. A randomized strategy, with private or shared coins, is a mixture of deterministic ones and its winning probability is their average, so it too is at most 3/4. Our instrument's search over all sixteen deterministic strategies returns 0.75. Quantumly, share |Φ⁺⟩ = (|00⟩ + |11⟩)/√2 and let measuring at angle A mean the basis |A⟩ = cos A|0⟩ + sin A|1⟩ (answer 0), |A⊥⟩ = −sin A|0⟩ + cos A|1⟩ (answer 1). Then ⟨A|⟨B|Φ⁺⟩ = (cos A cos B + sin A sin B)/√2 = cos(A − B)/√2, and likewise ⟨A⊥|⟨B⊥|Φ⁺⟩ = cos(A − B)/√2, so P(a = b) = cos²(A − B). Take A = 0 or π/4 for x = 0 or 1, and B = π/8 or −π/8 for y = 0 or 1. In the three cases other than x = y = 1, |A − B| = π/8 and agreement wins: cos²(π/8). For x = y = 1, A − B = 3π/8 and disagreement wins: sin²(3π/8) = cos²(π/8). The value is cos²(π/8) = (2 + √2)/4 ≈ 0.8536; our simulator gives 0.854 exactly and 0.852 over 200,000 sampled rounds. Each side's answers alone are fair coins, so no message passes; Tsirelson (1980) proved that no quantum strategy does better.

  3. The QFT on three qubits. Write the QFT on three qubits as gates, and check it against the 8 × 8 DFT matrix.

    Solution

    Write j = 4j₁ + 2j₂ + j₃ and k = 4k₁ + 2k₂ + k₃ (qubit 1 the most significant) and ω = e^{2πi/8}. Then ω^{jk} = e^{2πi jk₁/2} e^{2πi jk₂/4} e^{2πi jk₃/8}, and whole turns drop out, so QFT|j⟩ = (1/√8)(|0⟩ + e^{2πi 0.j₃}|1⟩)(|0⟩ + e^{2πi 0.j₂j₃}|1⟩)(|0⟩ + e^{2πi 0.j₁j₂j₃}|1⟩) in binary fractions. With R_k = diag(1, e^{2πi/2^k}) the circuit is: H on qubit 1, which gives |0⟩ + e^{2πi 0.j₁}|1⟩; R₂ on qubit 1 controlled by qubit 2, adding j₂/4 of a turn; R₃ on qubit 1 controlled by qubit 3, adding j₃/8, so qubit 1 holds 0.j₁j₂j₃; H on qubit 2 and R₂ controlled by qubit 3, giving 0.j₂j₃; H on qubit 3, giving 0.j₃; and a SWAP of qubits 1 and 3, because the factors come out in reverse order. That is six gates and one swap, n(n + 1)/2 + ⌊n/2⌋ = 7, as our instrument counts. Check: on |001⟩ (j = 1) the circuit leaves phases of 1/8, 1/4 and 1/2 of a turn on qubits 1, 2 and 3, and after the swap the amplitude of |k⟩ is e^{2πi(k₁/2 + k₂/4 + k₃/8)}/√8 = ω^k/√8, column 1 of the matrix ω^{jk}/√8; on |101⟩ (j = 5) the phases after the swap are 1/2, 1/4 and 5/8, as in chapter 7. Equality on the eight basis states proves equality of the matrices, by linearity. Numerically, qft_check(3) applies the circuit to a random state and agrees with the matrix to 1.7 × 10⁻¹⁵, and with numpy's FFT of the +i sign convention (ifft times √8) to 2.5 × 10⁻¹⁶.

  4. Grover. Show that Grover's iteration is a rotation by 2θ with sin θ = 1/√N, and find the best number of iterations for N = 2²⁰.

    Solution

    Let |s′⟩ be the even superposition of the N − 1 unmarked states. The start |s⟩ = sin θ|w⟩ + cos θ|s′⟩, with sin θ = ⟨w|s⟩ = 1/√N, lies in the plane of |s′⟩ and |w⟩, and both O = I − 2|w⟩⟨w| and D = 2|s⟩⟨s| − I map that plane to itself. In coordinates (|s′⟩, |w⟩), O fixes |s′⟩ and negates |w⟩, a reflection in the line at angle 0; D fixes |s⟩ and negates the direction perpendicular to it, a reflection in the line at angle θ. A reflection in the line at angle α has matrix [[cos 2α, sin 2α], [sin 2α, −cos 2α]], so DO = [[cos 2θ, sin 2θ], [sin 2θ, −cos 2θ]] · [[1, 0], [0, −1]] = [[cos 2θ, −sin 2θ], [sin 2θ, cos 2θ]], the rotation by 2θ. Hence (DO)^k|s⟩ = sin((2k + 1)θ)|w⟩ + cos((2k + 1)θ)|s′⟩, and the success probability is sin²((2k + 1)θ), largest when (2k + 1)θ is nearest π/2, at k ≈ π/(4θ) − 1/2. For N = 2²⁰ = 1,048,576, θ = arcsin(2⁻¹⁰) = 9.765627 × 10⁻⁴ rad and π/(4θ) − 1/2 = 803.75, so k = 804 (close to (π/4)√N = 804.2). Then P = sin²(1609θ) = 0.99999976, a failure probability of 2.4 × 10⁻⁷, against 2.1 × 10⁻⁶ at 803 and 6.0 × 10⁻⁶ at 805; a classical search in random order needs (N + 1)/2 = 524,288.5 looks on average.

  5. Build. Use our simulator to run Shor on N = 35, and count the shots needed to find the order.

    Solution

    Solution notes. Call algorithms.shor(35, a) (or order_finding(a, 35, shots=...) for more shots) for an a coprime to 35 (its r and factors come from the true order, found classically; what each shot gave is in samples). The orders divide λ(35) = lcm(4, 6) = 12; of the 24 residues coprime to 35, 18 have an even order r with a^(r/2) ≢ −1 (the exceptions are 1, 11 and 16, of odd order, and 19, 24 and 34, with a^(r/2) ≡ −1), so a random a works with probability 3/4. With a = 2, r = 12 (2¹² = 4,096 = 117 · 35 + 1); the instrument uses t = 2⌈log₂ 35⌉ + 1 = 13 counting qubits, Q = 8,192 ≥ 35² = 1,225. Since 12 does not divide 8,192, only the four peaks at 0, 2,048, 4,096 and 6,144 are sharp (1/12 each); the other eight are smeared over neighbours (0.057 on the nearest outcome), and the twelve nearest outcomes hold 0.789 of the probability. Each shot y becomes y/Q in lowest terms with denominator at most 35 (Fraction.limit_denominator); its denominator is 12 exactly when the nearby s/12 has s coprime to 12. The exact probability that one shot gives r = 12 at once is 0.329, so about 3.0 shots on average; keeping the lcm of the denominators seen so far, and stopping when 2^lcm ≡ 1, needs 2.3 on average (from 100,000 simulated runs of the exact distribution: one shot 33% of the time, two 33%, three 18%). Our seed-0 run of 20 shots: the first, 4,779 → 7/12, already gives 12, and 4 of the 20 do (4,779 twice, 7,509 → 11/12 and 3,412 → 5/12); the rest give 5/6, 3/4, 2/3, 1/2, 1/4, 1/6 or 0. Then 2⁶ = 64 ≡ 29 ≢ −1, gcd(63, 35) = 7 and gcd(65, 35) = 5: 35 = 5 × 7. A complete answer tabulates the count for several a (a = 4 or 9 has r = 6, a = 8 has r = 4, a = 6 has r = 2) and states the caveat honestly: our simulator writes aˣ mod N into the work register, so the count is of shots, not gates; a full state vector would need 13 + 6 = 19 qubits, 2¹⁹ amplitudes or 8 MB, and a reversible modular multiplier built from chapter 1's Toffoli gates would change the gate count but not these statistics.

  6. ★ Research. Find the least space-time volume of physical qubits needed to factor a 2048-bit number at a physical error rate of 10⁻³, with a matching lower bound.

    Discussion. Open. Every number we have is an upper bound from an explicit compilation: Shor's arithmetic laid out in logical qubits, the logical qubits in surface-code patches, and the cost of the non-Clifford gates and of idle storage counted. Taking the published headline figures at face value, about 20 million qubits for about 8 hours (Gidney and Ekerå, 2019) is about 1.6 × 10⁸ qubit-hours, and under a million qubits for under a week (Gidney, 2025) is under 1.7 × 10⁸: the qubit count fell more than twentyfold while the volume stayed of the same order, so the two figures of merit pull apart. A matching lower bound is out of reach for a deeper reason: a reversible classical circuit is a quantum circuit, so any nontrivial lower bound on the volume needed to factor would also bound classical circuits for factoring 2048-bit numbers, which Part 26's barriers put beyond current techniques. A good partial answer would fix the metric (physical qubits times surface-code cycles, under a stated noise model), lower the best upper bound with a resource estimate others can reproduce, or prove a lower bound inside a stated model, for example for Shor-style period finding with a fixed code and gate set, in terms of the logical qubits, non-Clifford gates and code distance it must use.

Notes and sources

Glossary

  • Landauer's principle, reversible computing, Toffoli and Fredkin gates, uncomputation — erasing a bit costs at least kT ln 2 of heat; computing by permutations of states; three-bit gates that lose nothing; running a circuit backwards to clear its garbage.
  • qubit, amplitude, Born rule, superposition — a two-level quantum system; the complex coefficients of its state; probability as the squared size of an amplitude; a state with more than one nonzero amplitude.
  • global and relative phase, Bloch sphere — a factor no measurement sees; the phase between amplitudes that interference does see; a qubit's state as a point on a sphere, orthogonal states at opposite points.
  • unitary, Hadamard, Pauli X, Y, Z, phase gates S and T, CNOT — a matrix with U†U = I, a rotation of the state; the common one- and two-qubit gates.
  • tensor product, product state, entanglement, Bell state — the joint state of independent systems; a state that factors; one that does not; (|00⟩ + |11⟩)/√2.
  • CHSH game, Tsirelson's bound, no-cloning theorem — a nonlocal game won 3/4 of the time classically and cos²(π/8) quantumly; the quantum maximum; no unitary copies unknown states.
  • universal gate set, Clifford gates, Gottesman–Knill theorem, Solovay–Kitaev theorem — gates that approximate every unitary; H, S and CNOT; circuits of them simulated efficiently classically; approximation with polylogarithmically many gates.
  • state-vector simulation — storing all 2ⁿ amplitudes and applying gates as small matrix products along axes.
  • oracle, phase kickback, interference — a reversible black box for f; f(x) written into a sign; amplitudes reinforcing and cancelling.
  • Deutsch–Jozsa, Bernstein–Vazirani, Simon's problem, hidden subgroup problem, oracle separation — the first problems where interference wins; finding a hidden period of a function on a group; a gap proved relative to a black box.
  • quantum Fourier transform, controlled rotation R_k, approximate QFT — the DFT on amplitudes in O(n²) gates; its phase gates; dropping the smallest rotations for O(n log n).
  • phase estimation, counting register — reading an eigenvalue's phase to t bits with t control qubits and an inverse QFT.
  • order, order finding, Shor's algorithm, continued fractions, convergent — the least r with aʳ ≡ 1 (mod N); finding it by phase estimation; factoring from it; recovering s/r from a measured y/2ᵗ.
  • Grover's algorithm, diffusion (inversion about the mean), amplitude amplification, quantum counting — search in about (π/4)√N queries; the reflection in the start state; the same speed-up for any algorithm; counting solutions by phase estimation.
  • BQP, PP, PSPACE, polynomial method, Holevo bound — bounded-error quantum polynomial time and the classes around it; lower bounds from the degree of acceptance polynomials; n qubits carry at most n classical bits.
  • quantum supremacy (advantage), random circuit sampling, boson sampling — a task done by quantum hardware faster than by any known classical method; two such tasks.
  • bit flip, phase flip, syndrome, stabilizer, logical and physical qubit, code distance — X and Z errors; the measured parities that locate an error; a Pauli product fixing every codeword; the encoded qubit and its carriers; the fewest errors that cause a logical error.
  • surface code, decoder, minimum-weight matching, threshold, Λ — a code of local parity checks on a lattice; the algorithm that pairs lit checks; the physical error rate below which bigger codes are better; the factor gained per step in distance.
  • BB84, intercept-and-resend, post-quantum cryptography (ML-KEM, ML-DSA, SLH-DSA) — key distribution whose eavesdroppers cause errors; the simplest attack, a 25% error rate; classical schemes not known to fall to Shor.
  • resource estimate, space-time volume — the qubits and time a fault-tolerant algorithm needs; their product.

Sources

  • M. A. Nielsen and I. L. Chuang, Quantum Computation and Quantum Information (10th anniversary ed., 2010); N. D. Mermin, Quantum Computer Science: An Introduction (2007); S. Aaronson, Quantum Computing Since Democritus (2013); A. Yu. Kitaev, A. H. Shen and M. N. Vyalyi, Classical and Quantum Computation (2002); J. Watrous, The Theory of Quantum Information (2018); R. de Wolf, Quantum Computing: Lecture Notes; J. Preskill, lecture notes for Caltech's Physics 219.
  • R. Landauer, "Irreversibility and heat generation in the computing process", IBM J. Res. Dev. 1961; C. H. Bennett, "Logical reversibility of computation", IBM J. Res. Dev. 1973; E. Fredkin and T. Toffoli, "Conservative logic", Int. J. Theor. Phys. 1982; A. Bérut et al., "Experimental verification of Landauer's principle linking information and thermodynamics", Nature 2012.
  • R. P. Feynman, "Simulating physics with computers", Int. J. Theor. Phys. 1982; D. Deutsch, "Quantum theory, the Church–Turing principle and the universal quantum computer", Proc. R. Soc. Lond. A 1985; D. Deutsch and R. Jozsa, "Rapid solution of problems by quantum computation", Proc. R. Soc. Lond. A 1992; R. Cleve, A. Ekert, C. Macchiavello and M. Mosca, "Quantum algorithms revisited", Proc. R. Soc. Lond. A 1998.
  • E. Bernstein and U. Vazirani, "Quantum complexity theory", STOC 1993 (SIAM J. Comput. 1997); D. R. Simon, "On the power of quantum computation", FOCS 1994 (SIAM J. Comput. 1997).
  • P. W. Shor, "Algorithms for quantum computation: discrete logarithms and factoring", FOCS 1994, and "Polynomial-time algorithms for prime factorization and discrete logarithms on a quantum computer", SIAM J. Comput. 1997; D. Coppersmith, "An approximate Fourier transform useful in quantum factoring", IBM research report, 1994; A. Yu. Kitaev, "Quantum measurements and the Abelian stabilizer problem", 1995.
  • L. K. Grover, "A fast quantum mechanical algorithm for database search", STOC 1996; C. H. Bennett, E. Bernstein, G. Brassard and U. Vazirani, "Strengths and weaknesses of quantum computing", SIAM J. Comput. 1997; G. Brassard, P. Høyer and A. Tapp, "Quantum counting", ICALP 1998; G. Brassard, P. Høyer, M. Mosca and A. Tapp, "Quantum amplitude amplification and estimation", 2002.
  • A. Barenco et al., "Elementary gates for quantum computation", Phys. Rev. A 1995; C. M. Dawson and M. A. Nielsen, "The Solovay–Kitaev algorithm", Quantum Inf. Comput. 2006; N. J. Ross and P. Selinger, "Optimal ancilla-free Clifford+T approximation of z-rotations", Quantum Inf. Comput. 2016.
  • B. S. Tsirelson (Cirel'son), "Quantum generalizations of Bell's inequality", Lett. Math. Phys. 1980; W. K. Wootters and W. H. Zurek, "A single quantum cannot be cloned", Nature 1982; D. Dieks, "Communication by EPR devices", Phys. Lett. A 1982; A. S. Holevo, "Bounds for the quantity of information transmitted by a quantum communication channel", Probl. Inf. Transm. 1973.
  • L. M. Adleman, J. DeMarrais and M.-D. A. Huang, "Quantum computability", SIAM J. Comput. 1997; R. Beals, H. Buhrman, R. Cleve, M. Mosca and R. de Wolf, "Quantum lower bounds by polynomials", FOCS 1998; R. Raz and A. Tal, "Oracle separation of BQP and PH", STOC 2019 (ECCC 2018).
  • S. Aaronson and A. Arkhipov, "The computational complexity of linear optics", STOC 2011; M. J. Bremner, R. Jozsa and D. J. Shepherd, "Classical simulation of commuting quantum computations implies collapse of the polynomial hierarchy", Proc. R. Soc. A 2011; F. Arute et al., "Quantum supremacy using a programmable superconducting processor", Nature 2019; E. Pednault et al., "Leveraging secondary storage to simulate deep 54-qubit Sycamore circuits", 2019; H.-S. Zhong et al., "Quantum computational advantage using photons", Science 2020; F. Pan, K. Chen and P. Zhang, "Solving the sampling problem of the Sycamore quantum circuits", Phys. Rev. Lett. 2022.
  • P. W. Shor, "Scheme for reducing decoherence in quantum computer memory", Phys. Rev. A 1995; A. M. Steane, "Error correcting codes in quantum theory", Phys. Rev. Lett. 1996; D. Gottesman, Stabilizer Codes and Quantum Error Correction, PhD thesis, Caltech 1997; A. Yu. Kitaev, "Fault-tolerant quantum computation by anyons", 1997 (Ann. Phys. 2003); E. Dennis, A. Kitaev, A. Landahl and J. Preskill, "Topological quantum memory", J. Math. Phys. 2002; A. G. Fowler, M. Mariantoni, J. M. Martinis and A. N. Cleland, "Surface codes: towards practical large-scale quantum computation", Phys. Rev. A 2012; Google Quantum AI and collaborators, "Quantum error correction below the surface code threshold", Nature 2024.
  • C. H. Bennett and G. Brassard, "Quantum cryptography: public key distribution and coin tossing", Proc. IEEE Int. Conf. on Computers, Systems and Signal Processing, Bangalore 1984; NIST, FIPS 203, 204 and 205 (2024).
  • C. Gidney and M. Ekerå, "How to factor 2048 bit RSA integers in 8 hours using 20 million noisy qubits", 2019 (Quantum 2021); C. Gidney, "How to factor 2048 bit RSA integers with less than a million noisy qubits", 2025; F. Boudot, P. Gaudry, A. Guillevic, N. Heninger, E. Thomé and P. Zimmermann, the factorization of RSA-250 (2020); J. A. Smolin, G. Smith and A. Vargo, "Oversimplifying quantum factoring", Nature 2013; E. Tang, "A quantum-inspired classical algorithm for recommendation systems", 2018 (STOC 2019).
About this partfrom its README

Part 53 of a sixty-one-part course in computer science (see the series plan and the syllabus), the third part of Act X, Horizons and Trust. Feynman asked in 1981 whether a classical computer can simulate quantum physics, and suspected it cannot: n two-state particles need 2ⁿ amplitudes. A computer made of quantum parts lets those amplitudes interfere; Shor used that to factor and break Part 30's cryptography, Grover to search in √N steps and no faster, and it is the one serious challenge to Part 1's extended Church–Turing thesis. We build a state-vector simulator of about a hundred lines and run every algorithm in this part on it, from Deutsch–Jozsa and Simon to Shor factoring 15 and 21, Grover's search, BB84 and the repetition code.

The instruments are in explainer/cs/quantum/ (tested in tests/test_cs53_quantum.py):

  • sim.py: the state-vector simulator. n qubits are 2ⁿ complex amplitudes, qubit 0 the most significant bit of the index; the gates H, X, Y, Z, S, T and the rotations Rx, Ry, Rz and phase(t); a k-qubit gate applied by viewing the state as a 2 × 2 × ⋯ × 2 array, moving the gate's axes to the front and multiplying; controlled gates and CNOT; Born-rule probabilities, marginals and sampled measurement; the Bloch vector of a qubit, and the trajectories of H, T, S and Rx(π) on the sphere; a unitarity check.
  • algorithms.py: Landauer's kT ln 2; the Bell state; the CHSH game (the exact quantum value, a sampled one, and a search over all 16 deterministic classical strategies); a CNOT "copying" |+⟩; phase oracles; Deutsch–Jozsa on four qubits for four functions; Bernstein–Vazirani; Simon's problem, run until one candidate secret is left; the QFT circuit checked against its matrix and numpy's FFT, with gate counts; phase estimation; Shor's order finding (the work register holding aˣ mod N written in directly, not built from gates) with continued fractions, and the factors; Grover's success probability against iterations, amplitude snapshots, and the iterations needed as N grows; BB84 with and without an intercept-and-resend eavesdropper.
  • qec.py: the three-qubit bit-flip code (encode, flip, read the two parities, correct); the repetition code of distance 1 to 11 under independent bit flips, logical against physical error rate simulated and exact, and the factor Λ by which each step in distance divides the logical error rate.
Chapter notes
  • Hook. Feynman's question (1981): n two-state particles need 2ⁿ amplitudes, at 16 bytes each 16 kB for 10, 16 MB for 20, 16 GB, 16 TB and 16 PB for 30, 40 and 50; at 300, 2³⁰⁰ ≈ 10⁹⁰, more than the roughly 10⁸⁰ atoms in the observable universe. The extended Church–Turing thesis challenged: Deutsch (1985), Shor (1994), Grover (1996), error correction below threshold in hardware (2024). The part's six objectives.
  • 1. The cost of forgetting. An AND gate maps four inputs to two; erasing a one-molecule memory (illustrative). Landauer's principle derived: entropy falls by k ln 2, so Q ≥ kT ln 2 = 2.87 × 10⁻²¹ J ≈ 0.018 eV per bit at 300 K; 10¹⁸ erasures a second at the limit cost 2.9 mW; measured by Bérut et al. (2012). Toffoli's and Fredkin's gates as permutations of the eight states; Bennett's compute, copy, uncompute (1973), the pattern of every oracle in the part; permutation matrices are exactly the 0–1 unitaries, and allowing any unitary turns shuffles into rotations (Benioff 1980, Feynman 1982, Deutsch 1985).
  • 2. The qubit. α|0⟩ + β|1⟩ and the Born rule; negative amplitudes can cancel; global and relative phase, and cos(θ/2)|0⟩ + e^{iφ} sin(θ/2)|1⟩ as a point on the Bloch sphere, orthogonal states at opposite poles; |+⟩ and |−⟩ with the same probabilities; P(0) = (1 + z)/2, the arrow's height; measurement leaves a pole; Holevo (1973): n qubits sent on their own carry at most n bits; superconducting circuits, trapped ions, neutral atoms, photons.
  • 3. Gates, tensor products and entanglement. H, T, S and Rx(π) as rotations, their paths on the sphere computed by our simulator; U†U = I; the tensor product and 2ⁿ amplitudes (2n numbers for a product state); H then CNOT gives the Bell state, amplitudes 0.707 on |00⟩ and |11⟩ and probabilities 0.50, proved not to factor. The CHSH game: any classical strategy wins at most 3/4 = 0.75 (checked over all sixteen deterministic ones), a shared Bell pair measured at 0, π/4 and ±π/8 wins cos²(π/8): 0.854 exact, 0.852 sampled; Tsirelson (1980) and Part 27's MIP* = RE. No-cloning in three lines (Wootters and Zurek; Dieks, 1982): a CNOT fed |+⟩|0⟩ makes a Bell pair whose overlap with |+⟩|+⟩ is 0.50.
  • 4. Circuits and universality. Reading a circuit right to left as a matrix product; H ⊗ I written out. Toffoli from 6 CNOTs, 7 T or T† and 2 H gates, multiplied out to exactly Toffoli's permutation; Barenco et al. (1995). THTH = Rz(π/4)Rx(π/4) (up to a global phase) is a rotation by an irrational fraction of a turn (cos(θ/2) = cos²(π/8)), its first 160 powers on |0⟩ filling a circle; without T, Gottesman–Knill. The Solovay–Kitaev recursion: error to the power 3/2 and five times the gates per level, so length ∝ log^3.97(1/ε); Ross and Selinger's O(log 1/ε) for H and T. Our simulator's apply in eight lines: a gate mixes amplitudes in pairs, like an FFT stage, memory-bound on Part 9's roofline. The Bell circuit in our simulator, Qiskit and Cirq: amplitudes 0.707, 0.000, 0.000, 0.707; real devices return only samples, after compilation to native gates and routing.
  • 5. Interference as a resource. A coin flipped twice stays a coin; HH|0⟩ = |0⟩ because the two paths to |1⟩ cancel. Phase kickback: U_f|x⟩|−⟩ = (−1)^f(x)|x⟩|−⟩. Deutsch's problem in one query (the always-correct circuit of Cleve, Ekert, Macchiavello and Mosca, 1998), for all four functions. Deutsch–Jozsa on four qubits: the sixteen amplitudes after H, the oracle and H again for f = 0, the top bit and the parity; the all-zeros amplitude is the average sign, so P(0000) = 1.000 for constant and 0.000 for balanced, against 9 = 2ⁿ⁻¹ + 1 classical queries in the worst case. Spread, mark, interfere; measuring straight after the oracle is one classical query; a randomized test of k queries is fooled with probability at most 2^(1−k).
  • 6. Bernstein–Vazirani and Simon. f(x) = s·x for s = 1011: four classical queries, one quantum one, which our simulator answers with 1011 at probability 1.000. Simon's problem on three bits with s = 110: classically the birthday bound, about 2^(n/2) queries; one run yields a y with y·s = 0. Our runs gave 110 and 001, which rule out four and then two of the seven candidates and leave 110 after 2 runs; in general a little over n runs and Gaussian elimination mod 2. Simon against Shor in one table (the hidden subgroup problem); the separation is relative to an oracle.
  • 7. The quantum Fourier transform. The 8 × 8 matrix ω^{jk}/√8 drawn as arrows; the product formula, so a basis state's transform is unentangled (j = 5: half, a quarter and five eighths of a turn); from Part 19's butterflies to Hadamards, controlled rotations R_k and final swaps. n(n+1)/2 rotations and Hadamards plus ⌊n/2⌋ swaps: 4, 7, 12, 24 and 40 gates for n = 2, 3, 4, 6, 8, against N log₂ N = 8, 24, 64, 384 and 2,048 for the FFT; our circuit agrees with numpy's FFT on a random state to between 1.4 × 10⁻¹⁶ and 2.8 × 10⁻¹⁶. A period-4 state on 16 points becomes peaks at 0, 4, 8 and 12; the coefficients cannot be read out, nor arbitrary data loaded cheaply; Coppersmith's approximate QFT in O(n log n) gates (1994).
  • 8. Phase estimation. An eigenvalue is a phase e^{2πiθ}, kicked back onto a control; θ = 0.3, a turn of 108°. Six counting qubits controlling U^(2^k) turn by 0.3, 0.6, 0.2, 0.4, 0.8 and 0.6; the register is a QFT in product form. The inverse QFT gives a geometric series; for the nearest m, |a_m|² ≥ 4/π² ≈ 0.405; phasor chains for m = 19 (0.875) and m = 20 (0.0547). Our run: θT = 19.2, the peak at m = 19 = 010011, θ ≈ 19/64 = 0.296875 with probability 0.875, neighbours 0.055 and 0.024. Uses (factoring, chemistry, counting) and the cost: 2⁶ − 1 = 63 applications of U for six bits; Kitaev's one-qubit version (1995).
  • 9. Shor's algorithm. Powers of 7 mod 15: 1, 7, 4, 13, period 4; 7² = 49, gcd(48, 15) = 3 and gcd(50, 15) = 5; a random a works with probability at least ½. Order finding as phase estimation of multiplication by a, with eigenvectors |u_s⟩ that sum to |1⟩. Fifteen with nine counting qubits (512 outcomes): four spikes of 0.25 at 0, 128, 256 and 384; of 20 shots, 9 give r = 4 at once (384 → 3/4), 256 → 1/2 gives a divisor, 0 nothing. Twenty-one with a = 2 and eleven counting qubits (2,048 outcomes): r = 6 does not divide 2,048, so 0.114 on the nearest outcome and 0.028 on the next; 1707/2048 expanded as a continued fraction gives 5/6, 2³ = 8, gcd(7, 21) = 7 and gcd(9, 21) = 3; 2,048 ≥ 21² = 441, so s/r is a convergent (Legendre); 7 of 20 shots give s/6 in lowest terms, and an lcm of divisors recovers the rest. The number field sieve against n³ gates; RSA-250 (829 bits, about 2,700 core-years, 2020); discrete logarithms fall too; "factoring" 15 and 21 on hardware with circuits simplified by the answer (Smolin, Smith and Vargo, 2013).
  • 10. Grover's search. Two reflections, the oracle in |s′⟩ and the diffusion in |s⟩, make a rotation by 2θ with sin θ = 1/√N; for N = 64 six rounds carry the state just past |w⟩. Inversion about the mean in the 64 amplitudes: from 0.125 each, the marked one reaches 0.998 after six rounds and then falls. Success against rounds follows sin²((2k+1)θ) exactly: 0.9966 at k = 6 (the formula's 5.77, rounded), 0.0001 at k = 12. Rounds against N: 3, 6, 12, 25, 50, 100 and 201 for N = 16 to 65,536, against (N + 1)/2 = 8.5 to 32,768.5 classical looks. Quantum counting from the eigenvalues e^{±2iθ} (2θ = 0.251 rad for N = 64; Brassard, Høyer and Tapp, 1998); amplitude amplification; the BBBV lower bound T ≥ (c/2)√N, sketched.
  • 11. What quantum computers cannot do. BQP defined (accept with probability at least 2/3 or at most 1/3, amplified by majority); BPP ⊆ BQP, and BQP ⊆ PP ⊆ PSPACE by Feynman's sum over paths with H and Toffoli (Bernstein and Vazirani, 1993; Adleman, DeMarrais and Huang, 1997). NP-complete problems: brute force over 2¹⁶ = 65,536 assignments still needs 201 Grover rounds; NP ⊄ BQP relative to a random oracle (Bennett et al., 1997); BQP outside PH relative to an oracle (Raz and Tal, 2018). Supremacy claims and the replies: Aaronson and Arkhipov and Bremner, Jozsa and Shepherd (2011); Google's 53 qubits in about 200 s against an estimated 10,000 years (2019); IBM's 2.5 days; USTC's boson sampling (2020); tensor networks (Pan, Chen and Zhang, 2022). Query limits: search Θ(√N), parity N/2 by the polynomial method, D(f) = O(Q(f)⁶) without a promise (Beals et al., 1998); Holevo's bound.
  • 12. Quantum error correction. Why it seemed impossible: no-cloning, measurement, continuous errors. The three-qubit code on 0.6|0⟩ + 0.8|1⟩: syndromes 00, 10, 11 and 01 for no error and a flip of qubit 1, 2 or 3, and our simulator restores the amplitudes in all four cases. Measuring the syndrome makes errors discrete (ε = 0.1 rad: no error with probability 0.990, a whole flip with 0.010). Shor's nine-qubit code, 6 + 2 = 8 checks; stabilizers (Gottesman, 1997). The surface code at distance 5: 24 checks on 25 data qubits, 49 physical qubits in all, a chain lighting its ends, any 2 errors corrected. The repetition code for d = 1 to 11 (lines exact, dots from 200,000 trials): threshold at p = ½, and at p = 1% each step in distance divides the logical error by Λ ≈ 30; surface-code thresholds near 1% (Fowler et al., 2012); Google Quantum AI (2024), distance 3 to 5 to 7, Λ ≈ 2.
  • 13. Frontier: keys, chemistry and the hardware. BB84 on 4,000 bits: 1,939 kept, 0% errors without an eavesdropper and 26.9% with one measuring and resending (theory 25%); NIST's 2024 post-quantum standards (ML-KEM, ML-DSA, SLH-DSA). RSA-2048 resource estimates: about 20 million noisy qubits for about 8 hours (Gidney and Ekerå, 2019), under a million for under a week (Gidney, 2025), against today's hundreds to about a thousand physical qubits; below threshold in 2024, and our repetition code's factor of about 30 per step, which catches only bit flips. Simulating nature, cryptanalysis, and weaker cases (Tang, 2018). Four open problems and the ★ research problem.
  • Outro. Recap, payoffs (Parts 54, 55, 56, 58 and 60), practice, problems, next part.

Companion material in this repository

The syllabus's plan for this partfrom SYLLABUS.md, the plan of record
  1. Landauer (kT ln 2 per erased bit) and Bennett: reversible computation; Toffoli and Fredkin; compute, copy, uncompute.
  2. Feynman (1982) and Deutsch (1985).
  3. The qubit: amplitudes, the Born rule, the Bloch sphere (3D). The physics is in Quantum Mechanics, Visualized.
  4. Gates as unitaries rotating the Bloch sphere; tensor products and 2ⁿ amplitudes; CNOT; Bell states and the CHSH game (cos²(π/8) ≈ 0.854 against the classical 3/4; callback to Part 27's MIP* = RE); no-cloning in three lines.
  5. Circuits and universality (H, T, CNOT; Solovay–Kitaev); our state-vector simulator.
  6. Interference as the resource: Deutsch, Deutsch–Jozsa, phase kickback.
  7. Bernstein–Vazirani; Simon's problem, an oracle separation and the seed of Shor.
  8. The QFT derived from the FFT's butterfly (callback to Part 19), with O(n²) gates for 2ⁿ points.
  9. Phase estimation.
  10. Shor (1994): order finding (Part 30's number theory), the QFT, continued fractions. Our simulator factors 15 and 21, and the amplitude spikes at multiples of 2ⁿ/r are animated.
  11. Grover (1996): two reflections make a rotation by 2θ; √N iterations; overshoot; optimality (BBBV 1997, sketched); amplitude amplification.
  12. BQP's place (BPP ⊆ BQP ⊆ PP ⊆ PSPACE); no known speedup for NP-complete problems beyond Grover's; the extended Church–Turing thesis; supremacy claims and the classical replies (cited, carefully).
  13. Quantum error correction: why it seemed impossible; the 3-qubit code and syndromes; Shor's 9-qubit code; stabilizers (Gottesman); the surface code and the threshold (callback to Part 28); below threshold (Google 2024, cited) (verify).
  14. Simulation and chemistry; BB84 (an eavesdropper shows up as a 25% error rate); resource estimates for RSA-2048 (Gidney 2025) (verify). Outro.

Computed: the simulator; Bloch trajectories; Deutsch–Jozsa, BV and Simon runs; QFT against FFT; Shor on 15 and 21; Grover's success probability against iterations; logical against physical error rates for the repetition code; BB84. Visuals: gates rotating the Bloch sphere; amplitude bars colored by phase, interfering; Grover's rotation in the plane; Shor's peaks; a surface-code lattice lighting its syndromes. In practice: quantum SDKs (Qiskit, Cirq), post-quantum migration planning, the honest state of the hardware. Reading: Nielsen & Chuang, Quantum Computation and Quantum Information; Mermin, Quantum Computer Science; Aaronson, Quantum Computing Since Democritus; Kitaev, Shen & Vyalyi; de Wolf's lecture notes; Preskill's Ph219 notes; Watrous, The Theory of Quantum Information; Feynman 1982; Deutsch 1985; Shor 1997; Grover 1996; Bennett et al. 1997; Gottesman 1997; Fowler et al. 2012; Bennett & Brassard 1984; Landauer 1961; Bennett 1973.

中文讲义

本讲的中文部分(与英文版对应)。

习题与解答
  1. 不可克隆。 证明不存在幺正算子 U,对每个态 |ψ⟩ 都把 |ψ⟩|0⟩ 映为 |ψ⟩|ψ⟩。

    解答

    设对两个单位向量有 U|ψ⟩|0⟩ = |ψ⟩|ψ⟩ 与 U|φ⟩|0⟩ = |φ⟩|φ⟩。幺正算子保持内积,所以两个左边的内积等于两个右边的 内积:⟨φ|ψ⟩⟨0|0⟩ = ⟨φ|ψ⟩²,即 x = x²,其中 x = ⟨φ|ψ⟩。于是 x = 0 或 x = 1:两个态要么正交,要么(由柯西–施瓦茨不等式) 相等。能复制一切态的机器必须复制 |0⟩ 和 |+⟩,而它们的重叠是 1/√2,矛盾。用线性也能直接看出:若 U 复制 |0⟩ 和 |1⟩,则 U|+⟩|0⟩ = (|00⟩ + |11⟩)/√2,是一个贝尔对,而不是 |+⟩|+⟩ = (|00⟩ + |01⟩ + |10⟩ + |11⟩)/2;两者的重叠是 2 · (1/√2)(1/2) = 1/√2,保真度 1/2,正是我们模拟器里的 CNOT 给出的 0.50。额外的工作空间也无济于事:若 U|ψ⟩|0⟩|0⟩ = |ψ⟩|ψ⟩|e_ψ⟩,则 x = x²⟨e_φ|e_ψ⟩,所以 |x| ≤ |x|²,|x| 仍只能是 0 或 1。这个定理禁止的是复制未知的态, 而不是已知的正交态:CNOT 可以扇出基态,所以经典比特可以复制。

  2. CHSH。 证明 CHSH 博弈的经典值是 3/4,并证明量子策略达到 cos²(π/8)。

    解答

    确定性策略固定 Alice 的回答 a₀、a₁ 和 Bob 的 b₀、b₁。四个问题都赢需要 a₀ ⊕ b₀ = 0、a₀ ⊕ b₁ = 0、 a₁ ⊕ b₀ = 0 和 a₁ ⊕ b₁ = 1。左边的异或为 0,因为每个变量出现两次;右边的异或为 1,所以至多三个成立,问题均匀随机时 这个策略至多赢 3/4;总回答 0 就能达到。随机策略,无论用私有还是共享的硬币,都是确定性策略的混合,赢的概率是它们的 平均,所以也至多 3/4。我们的工具搜索全部十六个确定性策略,得到 0.75。量子地,共享 |Φ⁺⟩ = (|00⟩ + |11⟩)/√2,并约定 “沿角度 A 测量”指在基 |A⟩ = cos A|0⟩ + sin A|1⟩(回答 0)、|A⊥⟩ = −sin A|0⟩ + cos A|1⟩(回答 1)下测量。于是 ⟨A|⟨B|Φ⁺⟩ = (cos A cos B + sin A sin B)/√2 = cos(A − B)/√2,同样 ⟨A⊥|⟨B⊥|Φ⁺⟩ = cos(A − B)/√2,所以 P(a = b) = cos²(A − B)。x = 0 或 1 时取 A = 0 或 π/4,y = 0 或 1 时取 B = π/8 或 −π/8。除 x = y = 1 外的三种情形中 |A − B| = π/8,一致就赢:cos²(π/8)。x = y = 1 时 A − B = 3π/8,不一致才赢:sin²(3π/8) = cos²(π/8)。博弈值为 cos²(π/8) = (2 + √2)/4 ≈ 0.8536;我们的模拟器给出精确值 0.854,200,000 轮抽样得 0.852。单看任何一方,回答都是公平的 硬币,所以没有传递任何消息;Tsirelson(1980)证明了没有量子策略能做得更好。

  3. 三个量子比特上的 QFT。 把三个量子比特上的 QFT 写成门,并与 8 × 8 的 DFT 矩阵核对。

    解答

    记 j = 4j₁ + 2j₂ + j₃,k = 4k₁ + 2k₂ + k₃(量子比特 1 是最高位),ω = e^{2πi/8}。则 ω^{jk} = e^{2πi jk₁/2} e^{2πi jk₂/4} e^{2πi jk₃/8},整圈不起作用,所以用二进制小数写, QFT|j⟩ = (1/√8)(|0⟩ + e^{2πi 0.j₃}|1⟩)(|0⟩ + e^{2πi 0.j₂j₃}|1⟩)(|0⟩ + e^{2πi 0.j₁j₂j₃}|1⟩)。取 R_k = diag(1, e^{2πi/2^k}),电路是:量子比特 1 上的 H,得到 |0⟩ + e^{2πi 0.j₁}|1⟩;由量子比特 2 控制、作用在量子比特 1 上的 R₂,加上 j₂/4 圈;由量子比特 3 控制、作用在量子比特 1 上的 R₃,加上 j₃/8 圈,于是量子比特 1 存的是 0.j₁j₂j₃; 量子比特 2 上的 H 和由量子比特 3 控制的 R₂,得到 0.j₂j₃;量子比特 3 上的 H,得到 0.j₃;最后交换量子比特 1 和 3,因为 各因子是倒序出来的。一共六个门加一次交换,n(n + 1)/2 + ⌊n/2⌋ = 7,与我们的工具的计数一致。核对:在 |001⟩(j = 1)上, 电路在量子比特 1、2、3 上留下 1/8、1/4、1/2 圈的相位,交换之后 |k⟩ 的振幅是 e^{2πi(k₁/2 + k₂/4 + k₃/8)}/√8 = ω^k/√8,正是矩阵 ω^{jk}/√8 的第 1 列;在 |101⟩(j = 5)上,交换后的相位是 1/2、1/4 和 5/8,与第 7 章一致。由线性,在八个基态上相等就证明了两个矩阵相等。数值上,qft_check(3) 把电路作用在一个随机态上, 与矩阵相差 1.7 × 10⁻¹⁵,与 numpy 中取 +i 符号约定的 FFT(ifft 乘以 √8)相差 2.5 × 10⁻¹⁶。

  4. Grover。 证明 Grover 迭代是转过 2θ 的旋转,其中 sin θ = 1/√N,并求 N = 2²⁰ 时最好的迭代次数。

    解答

    令 |s′⟩ 为 N − 1 个未标记态的均匀叠加。初态 |s⟩ = sin θ|w⟩ + cos θ|s′⟩,其中 sin θ = ⟨w|s⟩ = 1/√N, 它位于 |s′⟩ 与 |w⟩ 张成的平面内,而 O = I − 2|w⟩⟨w| 和 D = 2|s⟩⟨s| − I 都把这个平面映到自身。在坐标 (|s′⟩, |w⟩) 下, O 保持 |s′⟩、把 |w⟩ 变号,是关于角度为 0 的直线的反射;D 保持 |s⟩、把与它垂直的方向变号,是关于角度为 θ 的直线的反射。 关于角度为 α 的直线的反射矩阵是 [[cos 2α, sin 2α], [sin 2α, −cos 2α]],所以 DO = [[cos 2θ, sin 2θ], [sin 2θ, −cos 2θ]] · [[1, 0], [0, −1]] = [[cos 2θ, −sin 2θ], [sin 2θ, cos 2θ]],即转过 2θ 的 旋转。因此 (DO)^k|s⟩ = sin((2k + 1)θ)|w⟩ + cos((2k + 1)θ)|s′⟩,成功概率为 sin²((2k + 1)θ),在 (2k + 1)θ 最接近 π/2 时最大,即 k ≈ π/(4θ) − 1/2。N = 2²⁰ = 1,048,576 时,θ = arcsin(2⁻¹⁰) = 9.765627 × 10⁻⁴ 弧度, π/(4θ) − 1/2 = 803.75,所以 k = 804(接近 (π/4)√N = 804.2)。此时 P = sin²(1609θ) = 0.99999976,失败概率 2.4 × 10⁻⁷,而 803 次时为 2.1 × 10⁻⁶,805 次时为 6.0 × 10⁻⁶;经典的随机顺序搜索平均要看 (N + 1)/2 = 524,288.5 次。

  5. 动手。 用我们的模拟器对 N = 35 运行 Shor 算法,数一数找到阶需要多少次测量(shot)。

    解答

    解答要点。 对与 35 互素的 a 调用 algorithms.shor(35, a)(要更多次测量就用 order_finding(a, 35, shots=...))。各个 阶都整除 λ(35) = lcm(4, 6) = 12;在与 35 互素的 24 个剩余中,有 18 个的阶 r 是偶数且 a^(r/2) ≢ −1(例外是阶为奇数的 1、 11 和 16,以及 a^(r/2) ≡ −1 的 19、24 和 34),所以随机取 a 成功的概率是 3/4。取 a = 2,r = 12 (2¹² = 4,096 = 117 · 35 + 1);工具用 t = 2⌈log₂ 35⌉ + 1 = 13 个计数量子比特,Q = 8,192 ≥ 35² = 1,225。因为 12 不整除 8,192,只有 0、2,048、4,096 和 6,144 处的四个峰是尖锐的(各 1/12);其余八个峰摊到相邻结果上(最近的结果上 0.057),离十二个峰最近的结果共占 0.789 的概率。每次测量得到的 y 化成分母不超过 35 的最简分数 y/Q (Fraction.limit_denominator);当附近的 s/12 中 s 与 12 互素时,分母恰为 12。一次测量直接给出 r = 12 的精确概率是 0.329,所以平均约需 3.0 次;若记下目前所见各分母的最小公倍数,在 2^lcm ≡ 1 时停止,平均只需 2.3 次(对精确分布模拟 100,000 轮:33% 的情形一次,33% 两次,18% 三次)。我们 seed 0 的 20 次测量:第一次 4,779 → 7/12 就已给出 12,20 次中 有 4 次如此(4,779 两次,7,509 → 11/12 和 3,412 → 5/12);其余给出 5/6、3/4、2/3、1/2、1/4、1/6 或 0。然后 2⁶ = 64 ≡ 29 ≢ −1,gcd(63, 35) = 7,gcd(65, 35) = 5:35 = 5 × 7。完整的答案应对几个 a 列出次数(a = 4 或 9 时 r = 6,a = 8 时 r = 4,a = 6 时 r = 2),并如实说明前提:我们的模拟器直接把 aˣ mod N 写进工作寄存器,所以数的是测量 次数而不是门数;完整的状态向量需要 13 + 6 = 19 个量子比特,即 2¹⁹ 个振幅、8 MB;用第 1 章的托福利门搭出可逆的模乘法器 会改变门数,但不改变这些统计。

  6. ★ 研究。 求在物理错误率 10⁻³ 下分解一个 2048 位数所需物理量子比特的最小时空体积,并给出相匹配的下界。

    讨论。 尚未解决。我们手里的每个数都是来自显式编译的上界:把 Shor 算法的算术排成逻辑量子比特,把逻辑量子比特放进 表面码的码块,再计入非 Clifford 门和空闲存储的代价。按发表的主要数字计算,约 2000 万个量子比特运行约 8 小时(Gidney 与 Ekerå,2019)约为 1.6 × 10⁸ 量子比特·小时,不到一百万个量子比特运行不到一周(Gidney,2025)不到 1.7 × 10⁸:量子比特 数降到二十分之一以下,体积却仍在同一量级,所以这两个指标并不一致。相匹配的下界之所以遥不可及,还有更深的原因:可逆的经典 电路也是量子电路,所以任何非平凡的时空体积下界,也会给分解 2048 位数的经典电路一个下界,而第 26 部分的障碍表明这超出了 现有技术。好的部分结果可以是:固定度量(物理量子比特数乘以表面码周期数,并说明噪声模型);用别人能复现的资源估计 降低最好的上界;或在一个明确的模型里证明下界,例如对固定编码和门集的 Shor 式周期寻找,用它必须使用的逻辑量子比特、 非 Clifford 门和码距来表示。

Build the film

python -m videos.cs.cs53.compute        # the part's numbers, into .cache/cs53
python tools/build.py cs53                  # render and assemble the film
EXPLAINER_TTS=silent python tools/qa_scene.py cs53 Hook   # one chapter, silent, with a contact sheet

Scenes: videos/cs/cs53. Setup: see the course page. Source of these notes: the README and the scenes' narration.

Build it
python -m videos.cs.cs53.compute
python -m unittest tests.test_cs53_quantum
python tools/build.py cs53