Quantum Computing: From Bits to Shor · Year 4 Study Hub
Quantum ComputingChapters 1–5

From Bits to Shor

Hi. Pull up a chair. Over the next few hours I'm going to walk you from "what even is a qubit?" all the way to the algorithm that could break internet encryption. You don't need any physics background. If you can multiply two small numbers and read a table, you can follow every step.

Think of it like… Where it's used Real world Key idea Careful

Bit order: on this page, a state like |01⟩ means q0 = 0 and q1 = 1, reading left to right like the textbook. Qiskit and The Quantum Land print q0 on the right, so the same state shows up as "10" there. I'll remind you when it matters.

The plan
  • Chapter 1 covers the why: what quantum computers are, what they're good at, what's holding them back.
  • Chapter 2 covers the rules: qubits, gates, superposition, entanglement, interference, and two party tricks (teleportation and superdense coding).
  • Chapter 3 covers the algorithms: Deutsch–Jozsa, Grover and Shor, and how they use those rules.
  • Chapter 4 covers the engine: the Quantum Fourier Transform, Bernstein–Vazirani, phase estimation, and how the labs are built.
  • Chapter 5 covers the enemy: noise, and the three ways to fight it (error correction, mitigation and suppression).
Chapter 1

Introduction to Quantum Computing

Teacher Ch1 · s.1–41

1.1 Where this all came from

Let's start with a story, because it explains why "quantum computer" is a sensible idea and not science fiction.

  • 1928, David Hilbert (German mathematician) asked: is there a mechanical procedure that can decide whether any mathematical statement is true? That question forced people to define what a "procedure", meaning an algorithm, actually is.
  • 1936, Alan Turing (English mathematician) answered with the Turing machine: an infinitely long tape of cells, a head that reads and writes one symbol at a time, and a table of rules saying "if you're in state A and read a 1, write 0, move right, go to state B." Every laptop and phone today is, in theory, a Turing machine.
  • 1982, Richard Feynman pointed out that simulating nature (atoms, molecules) on such a machine is brutally slow, because nature is quantum. His suggestion: build the computer out of quantum things.
  • 1985, David Deutsch (English physicist) wrote down the theory of a universal quantum computer: a Turing machine whose tape and head obey quantum physics.
A timeline: David Hilbert in 1928, Alan Turing and the Turing machine in 1936, David Deutsch and quantum theory in 1985, leading to the quantum computer
Teacher Ch1 · s.4The chain of questions that led here.
Teacher Ch1 · s.4–5
Think of it like…

Turing defined the "rules of cooking": any recipe can be written as step-by-step instructions. Deutsch asked: what if the kitchen itself followed different physics, where an ingredient can be in two bowls at once? You get recipes that are impossible in a normal kitchen.

1.2 So what is quantum computing?

Here's a definition worth memorising:

Definition

Quantum computing is a new model of computing that uses the rules of quantum physics to process information in ways classical computers can't, enabling speedups on specific problem types.

Two things in that sentence matter. First, it's a different model, not a faster version of the same thing. Second, the speedups apply to specific problems. A quantum computer will not make Word open faster.

That's why, in practice, there are no standalone quantum computers. We have a QPU (quantum processing unit) that sits beside normal hardware, the same way a GPU does. Your CPU runs the program, hands the hard quantum-shaped part to the QPU, gets the answer back and continues.

A quantum chip, the gold chandelier of a quantum computer, and a comparison table of CPU, GPU, TPU and FPGA
Teacher Ch1 · s.6The hardware you've seen in photos, next to the accelerators a QPU sits beside. The chandelier is mostly cooling and wiring. The chip sits at the bottom.
Teacher Ch1 · s.6
Think of it like…

A restaurant kitchen. The head chef (CPU) does most of the work. There's a pastry specialist (GPU) for one kind of job, and now a new specialist (QPU) who is unbelievably good at a few very particular dishes and useless at frying an egg. You call the QPU only when one of those dishes is on the order.

1.3 Why do we need it?

Reason 1: chips are hitting physical limits

Moore's Law was the observation that the number of transistors on a chip doubles roughly every two years. It held for decades, but transistors are now only a few dozen atoms wide. Shrink them further and electrons start to "leak" through barriers by quantum tunnelling, a quantum effect that makes the transistor unreliable. So the free performance gains are slowing down.

A Moore's Law chart of transistor counts rising through the years, and a timeline of Intel process nodes shrinking
Teacher Ch1 · s.8Moore's Law, and the shrinking chips behind it.

Reason 2: some problems are hopeless for any classical computer

Computer scientists sort problems by how fast the work grows as the input gets bigger. This is computational complexity theory. The main families:

ClassPlain meaningExample
PSolvable quickly (polynomial time) by a classical computerSorting, shortest path, testing if a number is prime
NPIf someone hands you an answer, you can check it quicklySudoku: hard to solve, easy to check
NP-completeThe hardest problems inside NP. Solve one fast and you can solve all of NP fastMap colouring, box packing, Sudoku (n×n)
NP-hardAt least as hard as NP-complete (may not even be checkable quickly)Travelling salesman (find the shortest route)
BQPSolvable quickly by a quantum computer with error probability below 1/3Factoring, discrete logarithm (Shor)
PSPACE / EXPSolvable with polynomial memory / exponential timePerfect play in generalised chess or Go
A Venn diagram of P, NP, NP-complete and NP-hard, and curves of computation count against input size from constant up to factorial
Teacher Ch1 · s.9Left: the families in the table. Right: how fast each kind of cost grows.
Careful

BQP is believed to contain factoring, which is outside P as far as anyone knows. It is not believed to contain the NP-complete problems. Quantum computers are not magic NP solvers. They are very good at problems with hidden structure, such as periods and symmetries.

Teacher Ch1 · s.7–11

Two examples of how fast things explode:

  • Seating 10 people around a round table: \((10-1)! = 9! = 362{,}880\) arrangements.
  • A travelling salesman visiting 20 cities and returning home: \(\frac{(20-1)!}{2} = 60{,}822{,}550{,}204{,}416{,}000 \approx 6.08\times 10^{16}\) possible routes.
Ten people around a table with 362,880 seatings, and a travelling salesman route across the United States with about 6.08 × 10^16 possible routes
Teacher Ch1 · s.11Both examples from the slide.
Real world

This isn't just a textbook puzzle. A delivery driver's day is a travelling salesman problem, and it costs real fuel. UPS says its route-planning system, ORION, saves about 100 million miles a year. That's a classical system that finds good routes without proving they're the best, because checking them all is impossible. Better answers here are worth real money, which is why logistics companies keep watching quantum optimisation.

Play with the growth yourself. Notice how \(2^n\) and \(n!\) go from "fine" to "longer than the age of the universe" within a few clicks.

Try it

How fast does the work grow?

20 Computer speed: 10⁹ operations per second
GrowthNameOperationsTime
20

Reason 3: nature itself is quantum

Here's the clearest way to see it. To describe n qubits exactly, a classical computer must store \(2^n\) numbers (called amplitudes; you'll meet them in Chapter 2). Each extra qubit doubles the memory.

Try it

Memory needed to simulate n qubits

50
Where it's used

This is exactly why chemistry is the "killer app". A caffeine molecule has so many interacting electrons that storing its exact quantum state would take more bits than there are atoms on Earth. A quantum computer stores that state natively in its qubits, because it is made of the same kind of physics.

1.4 Bits vs qubits: the side-by-side

Here's the full comparison:

ClassicalQuantum
Basic unitBit: always 0 or 1Qubit: a blend (superposition) of 0 and 1 until measured
Reading itYou get the value; nothing changesYou get 0 or 1 with some probability, and the blend is destroyed
LogicDeterministic logic gates (AND, OR, NOT), many irreversibleUnitary quantum gates: always reversible
RunningSequential operations, same input gives same outputProbabilistic: same input gives a distribution of outputs
Working togetherBits are independentQubits can be entangled and act as one system
CopyingCopy freelyUnknown states cannot be copied (no-cloning)
With n unitsHolds one of \(2^n\) values at a timeDescribed by \(2^n\) amplitudes at once
Best atEveryday tasks: cheap, reliableSimulation, optimisation, structured math problems
Classical logic gates and a bit that is either 0 or 1, beside a qubit drawn as a sphere with quantum gates
Teacher Ch1 · s.12A bit is a choice of two points. A qubit is a point anywhere on a sphere.
Teacher Ch1 · s.12

In one line: "Quantum is not a faster classical computer. It is a different tool for specific problems."

Three myths to unlearn

MythReality
"It tries every answer at once and gives you the best."It holds many possibilities at once, but measuring gives only one random result. The skill is using interference to boost right answers and cancel wrong ones before you measure.
"It will replace your laptop."It targets certain hard problems. Today's machines are small and noisy.
"Encryption is already broken."A future large, error-corrected machine is the threat. That's why NIST published the first post-quantum encryption standards in August 2024.

1.5 Classical coin vs quantum coin

A coin shows the deepest difference between the two worlds: where randomness comes from.

A classical coin

  • Sample space {H, T}. A fair coin gives \(P(H)=P(T)=0.5\).
  • The randomness comes from chaos: initial spin, air, the surface. If you knew all of those perfectly, you could predict the result. It's randomness from ignorance.
  • It can be biased (a weighted coin, a special flipping style).
  • Computers mostly use pseudo-random number generators (PRNGs): formulas that produce numbers that look random from a starting value called a seed. Same seed gives the same sequence every time. They're fast and reproducible, but predictable if you know the seed and the algorithm.
  • True randomness needs physical noise: heat (thermal noise), avalanche diodes, radioactive decay.

A quantum coin

Put a qubit in the state

\[ |+\rangle = \tfrac{1}{\sqrt2}\big(|0\rangle + |1\rangle\big) \]

In words: "plus state equals one over root two times zero, plus one over root two times one." You make it by applying a Hadamard gate (H) to |0⟩.

Measure it and you get 0 or 1 with exactly 50/50 probability. But here the randomness is intrinsic. There is no hidden spin or air current that decided it; physics itself has not decided until you look. That randomness can even be certified with Bell tests, which is how device-independent quantum random number generators (QRNGs) work.

You can also make a biased quantum coin by choosing an angle θ:

\[ |\psi\rangle = \cos\theta\,|0\rangle + \sin\theta\,|1\rangle, \qquad P(0)=\cos^2\theta,\quad P(1)=\sin^2\theta \]

With θ = 30°, \(\cos^2 30^\circ = 0.75\), so P(0) = 0.75 and P(1) = 0.25.

Teacher Ch1 · s.13–15
Try it

PRNG coin vs quantum coin

Pseudo-random (seeded)
Press "Flip 24 times", then press it again with the same seed.

Same seed, same "random" flips. That's predictable by design.

Quantum coin cos θ|0⟩ + sin θ|1⟩
45°

Simulated with your browser's secure random generator. A real QRNG gets its bits by measuring actual qubits.

Schrödinger's cat

Then there's the famous thought experiment: a cat in a sealed box with a device that is triggered by a single quantum event. Quantum mechanics says that until you open the box, the system is in a superposition of "cat alive" and "cat dead". Schrödinger meant it as a joke about how strange this is. For us, the lesson is: a qubit really is in a blend of 0 and 1 until measured, and opening the box (measuring) forces one answer.

Where it's used

QRNGs are already commercial products. They generate cryptographic keys, run lotteries, and feed Monte Carlo simulations in finance. Some smartphones (e.g. Samsung Galaxy Quantum series) include a QRNG chip for security.

1.6 What quantum computers are good at, and what's still hard

Advantages

  • Parallelism: a superposition lets one circuit work on many inputs at once (Chapter 3 explains the catch).
  • Speed-ups for certain problems: exponential for factoring (Shor), quadratic for search (Grover).
  • Natural simulation of molecules and materials, "in their native quantum language".
  • Potential breakthroughs in AI, finance and optimisation.

Challenges

  • Fragile qubits: decoherence, meaning heat, vibration or stray light leaks into the qubit and scrambles its state, often within microseconds.
  • Error correction is expensive: one reliable logical qubit may need ~1,000 noisy physical qubits (Quantum Error Correction, QEC).
  • Scalability: devices today have tens to a few thousand qubits.
  • Algorithm maturity: only a few proven speed-ups exist.
  • Cost and cold: superconducting chips run at 20–100 millikelvin, colder than outer space, inside dilution refrigerators.
Teacher Ch1 · s.17–22
Think of it like…

Error correction: imagine whispering a message across a noisy room. To be sure it arrives, you get many people to whisper the same thing and take a majority vote. Quantum error correction does a cleverer version of this (you can't simply copy qubits), which is why one "good" qubit costs hundreds or thousands of "raw" ones.

One logical qubit built from a grid of physical qubits, with error-correcting codes growing from 17 to 49 to 97 qubits as they correct more errors at a time
Teacher Ch1 · s.18Why 1 logical qubit may need about 1,000 physical ones: fixing more errors takes a bigger grid.

The IBM roadmap (May 2022, updated August 2024) points one way: more qubits per chip, chips linked together, and a shift from "more qubits" to "better, error-corrected qubits".

IBM's quantum development roadmap from 2016 to 2033 and beyond, showing processors by year
Teacher Ch1 · s.21IBM's roadmap, August 2024. Tap to read the details.

1.7 The NISQ era, supremacy and advantage

NISQ stands for Noisy Intermediate-Scale Quantum, a term coined by John Preskill in 2018. It describes where we are today:

  • Devices with roughly 50 to 1,000 qubits that are not error-corrected.
  • Useful for quantum simulation (chemistry, physics), hybrid quantum-classical algorithms like VQE (Variational Quantum Eigensolver) and QAOA (Quantum Approximate Optimization Algorithm), and research and proof-of-concept work.
  • Not yet full-scale universal quantum computing.

A useful chart plots physical error rate against number of qubits. NISQ sits above the error-correction threshold. Below that line, adding more qubits for error correction actually reduces errors, and you get fault-tolerant quantum computing (FTQC). Google's Willow chip (2024, reported in Nature 2025) was the first to show error correction getting better as the code grew.

A scale of physical qubits from 10 to 1 million. NISQ sits around 100 to 1,000 and is where we are today. Fault-tolerant quantum computing lies past the error correction threshold
Teacher Ch1 · s.24Where we are today, and the line we still have to cross.
TermMeaningExample
Quantum supremacyA quantum device solves some task no classical computer can do in reasonable time, even if the task is uselessGoogle Sycamore, 2019, 53 qubits: random circuit sampling in 200 s
Quantum advantageA practical benefit over the best classical method on a real problemThe current goal: chemistry, optimisation, finance
FTQCFault-tolerant quantum computing: error-corrected logical qubits, long computationsNeeded for Shor on real RSA keys
Google's Sycamore chip held in gloved hands
Teacher Ch1 · s.26Google's Sycamore, the chip behind the 2019 result in the table.
A curve across eras: experimental, NISQ, quantum-at-scale and unlimited, with growing numbers of logical qubits
Teacher Ch1 · s.25The eras ahead, from about 60 physical qubits to millions of logical ones.

Key areas to watch: cryptography, optimisation, drug discovery, climate modelling.

Teacher Ch1 · s.23–26

1.8 How do you physically build a qubit?

A qubit is any physical system with two clearly separated states you can control. Several very different technologies compete:

TypeWhat the qubit isWho / deviceTrade-off
SuperconductingTiny electrical circuits made of zero-resistance material that act like artificial atoms (Josephson junctions)IBM Heron r1/r2 (133 and 156 qubits, heavy-hex lattice); Google Sycamore (53, 2D grid); RigettiFast gates; needs 20–100 mK cryogenics
Trapped ionIndividual charged atoms held by electromagnetic fields and controlled with lasersQuantinuum H1-1 (~20, all-to-all connectivity); IonQ Aria (#AQ 25)Very high fidelity; slower gates
PhotonicParticles of light (photons) travelling on optical chipsXanadu Borealis (216 squeezed modes); PsiQuantumRoom-temperature pathways; photon loss
Neutral atom / RydbergUncharged atoms held in a 2D grid by laser "tweezers"Atom Computing (~1,200); QuEra Aquila (256)Scales to many qubits; slower cycles
Quantum annealerNot gate-based: the system "settles" into the lowest-energy answer of an optimisation problemD-Wave Advantage (5,000+ qubits, Pegasus topology)Huge qubit counts, but only for optimisation-shaped problems
TopologicalExotic quasiparticles (anyons) in 2D materials; information stored in how they braidMicrosoft (research stage)Naturally protected from noise, still experimental
A layered diagram from room-temperature control down to the quantum plane, and a person standing beside a large cryogenic system
Teacher Ch1 · s.22Why it's the size of a wardrobe: the chip is tiny, and everything else is cooling and control down to 20–100 millikelvin.
Teacher Ch1 · s.27–32

1.9 Applications: where quantum could actually help

Pick a field.

Real world

Why does chemistry keep coming up? Making fertiliser by the Haber-Bosch process takes huge heat and pressure, and it uses roughly 1–2% of the world's energy. Bacteria do the same reaction at soil temperature, using an enzyme whose core (FeMoco) is too quantum for classical computers to simulate exactly. If we could simulate it, we might learn how to copy it. That's the sort of problem Feynman meant, and a big reason this field gets funded.

Explore

Quantum applications by field

  • Portfolio optimisation with QAOA / Ising models: balance risk and return across thousands of assets.
  • Credit-risk scoring and stress testing using quantum kernels and boosting.
  • Derivatives pricing with Quantum Monte Carlo / amplitude estimation (a quadratic speed-up over classical Monte Carlo).
  • Fraud and anomaly detection with variational quantum classifiers.
  • Liquidity / market-impact simulation using quantum walks.
  • Quantum money: banknotes that can't be forged, thanks to no-cloning.
Teacher Ch1 · s.33–39
Careful

An honest outlook per field: chemistry and materials is "most promising", cryptography "drives new standards", optimisation is "early research", machine learning is "mostly unproven". Keep that in mind when you read headlines.

1.10 The tools you'll use

  • Real quantum computers on the cloud: IBM, Google, Rigetti, Fujitsu.
  • Fake devices, meaning simulators that copy a real chip's noise (e.g. IBM's FakePerth): IBM Quantum, AWS Braket, Azure Quantum.
  • Simulators: The Quantum Land (drag-and-drop, used in class), Qiskit (Python, used in the labs), Cirq (Google).

The developer workflow has four steps: Code (Qiskit / Cirq), Translate the algorithm into a quantum circuit, Choose real hardware or a simulator, Execute (measure, iterate). Inside every run: Initialize qubits, Apply gates, let interference shape the outcomes, Measure to get a classical result.

The Quantum Land interface annotated step by step: drag gates, set qubits, send to the server, read the histogram
Teacher Ch2 · s.12The Quantum Land, the simulator used in class, annotated.
Teacher Ch1 · s.40

Chapter 1 in ten lines

  • Quantum computing is a different model of computation, built on quantum physics.
  • A QPU is a co-processor, like a GPU, not a laptop replacement.
  • Classical chips are near physical limits; some problems grow as 2ⁿ or n!.
  • Simulating n qubits classically needs 2ⁿ numbers.
  • A qubit is a blend of 0 and 1 until measured; measurement gives one random answer.
  • Quantum randomness is intrinsic, not ignorance; it powers QRNGs.
  • Challenges: decoherence, ~1,000 physical qubits per logical one, scaling, extreme cold.
  • NISQ = 50–1,000 noisy qubits, no full error correction; hybrid VQE/QAOA.
  • Supremacy (Sycamore 2019) ≠ advantage (useful) ≠ fault tolerance.
  • Hardware: superconducting, ion trap, photonic, neutral atom, annealer, topological.

Check yourself: Chapter 1

Chapter 2

Basics of Quantum Mechanics

Teacher Ch2 · s.1–30

This is the chapter where we learn the rules of the game. Take it slowly. Everything in Chapters 3 and 4 is just these rules used cleverly.

2.1 What quantum mechanics says

Quantum mechanics is the physics of very small things: atoms, electrons, photons (particles of light). Before it existed, classical physics (Newton's laws) explained footballs and planets perfectly, but it could not explain why atoms only emit certain colours of light, or how light and matter exchange energy.

Three ideas are all you need to start:

  • Quantised: energy comes in fixed packets. An electron in an atom can only sit on certain energy levels, like a ladder with no half-steps. That's why neon signs glow in specific colours.
  • Wave–particle duality: light and electrons arrive at a detector as single dots (like particles), but spread out and interfere (like waves).
  • Probabilistic: the theory usually can't predict exactly what will happen, only the probabilities.
FeatureClassical physicsQuantum physics
ScaleEveryday objectsAtoms and subatomic particles
PredictabilityDeterministic: exact outcomesProbabilistic: likelihoods only
How objects moveDefinite paths"Probability clouds"
Effect of observingNoneMeasurement changes the state (collapse)
ExamplesThrowing a football, Earth's orbit, car enginesSolar panels, microwaves, X-rays, lasers
Where it's used (already, today)
  • Transistors and semiconductors: every chip in your phone works because quantum mechanics explains how electrons move in silicon.
  • Solar cells: light packets (photons) knock electrons loose to make electricity.
  • GPS: satellites carry atomic clocks that tick using atomic energy transitions. Your phone's position depends on timing accurate to billionths of a second.
  • MRI scanners: use the quantum spin of hydrogen nuclei in your body. Electron microscopes use the wave nature of electrons to see tiny structures.

2.2 The double-slit experiment

This is the experiment that broke classical physics, and it explains interference, the most important tool in quantum computing.

Fire particles (electrons or photons) one at a time at a wall with two narrow slits, and record where each lands on a screen behind it. Each particle arrives as a single dot. But after thousands of dots, they form stripes: bright bands where many land and dark bands where almost none land. That stripe pattern is what waves do when they pass through two slits and overlap. So each single particle somehow went "through both slits" and interfered with itself.

Now put a detector at the slits to see which one each particle uses. The stripes disappear. You get two plain blobs. Measuring "which path" destroyed the interference.

Try it

Fire particles at two slits

0 particles detected.
Key idea

Two paths leading to the same spot can add up (bright stripe) or cancel (dark stripe). Quantum algorithms are designed so that the paths to wrong answers cancel and the paths to the right answer add up.

Teacher Ch2 · s.18

2.3 The math toolkit (ten minutes, I promise)

Before writing qubits down, you need three small tools. That's genuinely all the math in this course.

Tool 1: complex numbers as arrows

A complex number \(z = a + bi\) (where \(i^2=-1\)) is just an arrow on a 2D plane. It has a length \(|z| = \sqrt{a^2+b^2}\) and an angle called the phase. The neat way to write an arrow of length 1 pointing at angle θ is Euler's formula:

\[ e^{i\theta} = \cos\theta + i\sin\theta \]

"e to the i theta" is simply "the arrow of length 1 at angle θ". So \(e^{i\pi} = -1\) (pointing left), \(e^{i\pi/2} = i\) (pointing up).

The only thing you'll do with these arrows is add them (head to tail) and then take the squared length \(|z|^2\). That squared length becomes a probability.

Tool 2: vectors and matrices

We write the two basic qubit states as columns of numbers:

\[ |0\rangle = \begin{pmatrix}1\\0\end{pmatrix},\qquad |1\rangle = \begin{pmatrix}0\\1\end{pmatrix},\qquad \alpha|0\rangle+\beta|1\rangle = \begin{pmatrix}\alpha\\ \beta\end{pmatrix} \]

The funny bracket \(|\;\rangle\) is called a ket (Dirac notation). It just means "this is a quantum state".

A gate is a 2×2 matrix, and applying it means matrix × vector. Example, the NOT gate X:

\[ X|0\rangle = \begin{pmatrix}0&1\\1&0\end{pmatrix}\begin{pmatrix}1\\0\end{pmatrix} = \begin{pmatrix}0\cdot1+1\cdot0\\ 1\cdot1+0\cdot0\end{pmatrix} = \begin{pmatrix}0\\1\end{pmatrix} = |1\rangle \]

Row times column: top row (0, 1) · (1, 0) = 0; bottom row (1, 0) · (1, 0) = 1. So X turns |0⟩ into |1⟩.

Tool 3: the tensor product (combining qubits)

Two qubits together have four basic states: |00⟩, |01⟩, |10⟩, |11⟩. You combine single-qubit states with the tensor product ⊗, which multiplies every entry by every entry:

\[ |0\rangle\otimes|1\rangle = \begin{pmatrix}1\\0\end{pmatrix}\otimes\begin{pmatrix}0\\1\end{pmatrix} = \begin{pmatrix}1\cdot0\\1\cdot1\\0\cdot0\\0\cdot1\end{pmatrix} = \begin{pmatrix}0\\1\\0\\0\end{pmatrix} = |01\rangle \]

So n qubits need a column of \(2^n\) numbers. That's the 2ⁿ from Chapter 1.

2.4 The quantum state and measurement

A quantum state holds all the information about a system. For one qubit:

\[ |\psi\rangle = \alpha|0\rangle + \beta|1\rangle, \qquad |\alpha|^2 + |\beta|^2 = 1 \]

"Psi" (ψ) is the name of the state. α (alpha) and β (beta) are complex numbers called amplitudes. They can be negative or complex, which normal probabilities can't.

The Born rule (measurement)

When you measure, you get:

\[ P(0) = |\alpha|^2, \qquad P(1) = |\beta|^2 \]

That's why the squares must add to 1: the probabilities must total 100%. Example: \(|\psi\rangle = 0.6|0\rangle + 0.8|1\rangle\) gives P(0) = 0.36, P(1) = 0.64.

Collapse: after measuring, the blend is gone. If you got 1, the qubit is now |1⟩, and measuring again gives 1 every time.

Think of it like…

A spinning coin on a table is "both" heads and tails. Slap your hand on it and it becomes one of them, and it stays that way. The difference: a quantum coin's blend has signs and angles (amplitudes) that can cancel each other, which a real coin doesn't have.

The Bloch sphere

Because of normalisation (and because an overall phase doesn't matter physically), every single-qubit state can be written with just two angles:

\[ |\psi\rangle = \cos\tfrac{\theta}{2}|0\rangle + e^{i\varphi}\sin\tfrac{\theta}{2}|1\rangle \]

Read θ as latitude and φ as longitude on a globe, and every qubit state is a point on a sphere, the Bloch sphere. North pole = |0⟩, south pole = |1⟩, the equator holds the 50/50 states (|+⟩, |−⟩, |i⟩, |−i⟩) which differ only in phase. Gates become rotations of the arrow.

A sphere with |0⟩ at the north pole, |1⟩ at the south pole, and a state |ψ⟩ marked by angles θ and φ
Teacher Ch2 · s.4The Bloch sphere from the slide.
Careful

The quantum coin in Chapter 1 used cos θ|0⟩ + sin θ|1⟩. On the Bloch sphere, the angle is doubled (θ/2 inside). So the coin's θ = 45° is the Bloch θ = 90°, the equator. Same physics, different bookkeeping.

Teacher Ch2 · s.4, s.9 (Bloch simulators)

2.5 Single-qubit gates

Gates are the steps of a quantum program. Each is a small matrix that changes the state, and every gate is unitary, \(U^\dagger U = I\), which means it can be undone. (The dagger † means "flip rows and columns and take the complex conjugate"; it's the "undo" of a gate.) This is very different from a classical AND gate, where you can't recover the inputs from the output.

GateMatrixWhat it does in plain words
I (identity)\(\begin{pmatrix}1&0\\0&1\end{pmatrix}\)Nothing. Used as a placeholder (e.g. superdense coding bits 00).
X (Pauli-X, NOT)\(\begin{pmatrix}0&1\\1&0\end{pmatrix}\)Flips |0⟩ ↔ |1⟩. Half-turn about the x-axis.
Y (Pauli-Y)\(\begin{pmatrix}0&-i\\i&0\end{pmatrix}\)Flips and adds a phase. Half-turn about y.
Z (Pauli-Z, phase flip)\(\begin{pmatrix}1&0\\0&-1\end{pmatrix}\)Leaves |0⟩ alone, flips the sign of |1⟩. Turns |+⟩ into |−⟩.
H (Hadamard)\(\tfrac{1}{\sqrt2}\begin{pmatrix}1&1\\1&-1\end{pmatrix}\)Makes a 50/50 blend: |0⟩→|+⟩, |1⟩→|−⟩. Applying it twice undoes it.
S = √Z (phase)\(\begin{pmatrix}1&0\\0&i\end{pmatrix}\)Quarter-turn about z (90°). S† is the reverse: \(\mathrm{diag}(1,-i)\).
T (π/8 gate)\(\begin{pmatrix}1&0\\0&e^{i\pi/4}\end{pmatrix}\)Eighth-turn about z (45°). T† reverses it.
√X (SX)\(\tfrac12\begin{pmatrix}1+i&1-i\\1-i&1+i\end{pmatrix}\)Half a NOT: do it twice and you get X.
Rx(θ)\(\begin{pmatrix}\cos\frac\theta2&-i\sin\frac\theta2\\-i\sin\frac\theta2&\cos\frac\theta2\end{pmatrix}\)Rotate by θ about the x-axis.
Ry(θ)\(\begin{pmatrix}\cos\frac\theta2&-\sin\frac\theta2\\ \sin\frac\theta2&\cos\frac\theta2\end{pmatrix}\)Rotate by θ about y. Real amplitudes only, so it's the "biased coin" gate.
Rz(θ)\(\begin{pmatrix}e^{-i\theta/2}&0\\0&e^{i\theta/2}\end{pmatrix}\)Rotate by θ about z.
P(λ) (phase)\(\begin{pmatrix}1&0\\0&e^{i\lambda}\end{pmatrix}\)Adds phase λ to |1⟩. Equals Rz(λ) up to a global phase. The QFT is built from these.
U(θ,φ,λ)\(\begin{pmatrix}\cos\frac\theta2&-e^{i\lambda}\sin\frac\theta2\\e^{i\varphi}\sin\frac\theta2&e^{i(\varphi+\lambda)}\cos\frac\theta2\end{pmatrix}\)The general one-qubit gate: any rotation at all.
Teacher Ch2 · s.5–6, s.10

Gate tables often include a "Native?" column. Native gates are the ones the hardware can do directly (on IBM chips: X, √X, Rz and a two-qubit gate). Everything else, including H, is compiled into native gates by the transpiler before running. That's the "compilation / transpilation" step you'll see in Chapter 3.

Try it

Qubit playground: gates on the Bloch sphere

x → |+⟩ · y → |i⟩ · z → |0⟩
90°
Start from:

Things to try: H then H (back to |0⟩). H then Z then H (lands on |1⟩). H then S then S (S twice = Z). Ry at 60° from |0⟩ (a 75/25 coin).

2.6 Multi-qubit gates

Single-qubit gates can never link two qubits together. For that, we need gates that act on two or three qubits at once. They're written as bigger matrices on the combined (tensor-product) state.

GatePlain ruleTruth table on basis states
CNOT (CX)Flip the target only if the control is 100→00 · 01→01 · 10→11 · 11→10
CZPut a minus sign on |11⟩ only|11⟩ → −|11⟩, others unchanged
SWAPExchange the two qubits01↔10
Toffoli (CCX)Flip the target if both controls are 1110→111 · 111→110
Fredkin (CSWAP)Swap the two targets if the control is 1101→110 · 110→101
\[ \mathrm{CNOT}=\begin{pmatrix}1&0&0&0\\0&1&0&0\\0&0&0&1\\0&0&1&0\end{pmatrix}\qquad \mathrm{SWAP}=\begin{pmatrix}1&0&0&0\\0&0&1&0\\0&1&0&0\\0&0&0&1\end{pmatrix} \]

CNOT's matrix is the identity on the top half (control = 0: do nothing) and an X on the bottom half (control = 1: flip). The Toffoli matrix is the same idea, 8×8, with X only in the last 2×2 block.

Where it's used

CNOT is how we create entanglement (next section). Toffoli is a reversible AND gate: with the target starting at 0, it computes target = a AND b. That proves a quantum computer can do anything a classical one can, so arithmetic inside Shor's algorithm is built from gates like these.

Teacher Ch2 · s.7–8, s.11

2.7 Superposition

Let's look at each phenomenon from three angles: quantum mechanics, physics, and its role in algorithms.

  • Quantum mechanics: any isolated system can be a linear combination of basis states, \(\alpha|0\rangle+\beta|1\rangle\). The qubit is not secretly 0 or 1 that we just don't know. It really is in both until measured.
  • The math behind it: linearity of Hilbert space. If |a⟩ and |b⟩ are allowed states, then \(c_1|a\rangle + c_2|b\rangle\) is also allowed.
  • Physics: a photon polarised at 45° is a superposition of horizontal and vertical. In IBM's chips, a superconducting circuit's two lowest energy levels (from a Josephson junction) form the |0⟩ and |1⟩.
  • Algorithms: applying H to each of n qubits creates an equal superposition of all \(2^n\) inputs:
\[ H^{\otimes n}|0\rangle^{\otimes n} = \frac{1}{\sqrt{2^n}}\sum_{x=0}^{2^n-1}|x\rangle \]

"H on every qubit turns all-zeros into an equal mix of every number from 0 to 2ⁿ−1." With 3 qubits that's |000⟩ through |111⟩, each with amplitude 1/√8. This is the starting move of Deutsch–Jozsa, Grover, Bernstein–Vazirani, QPE and Shor.

A red |0⟩ sphere and a blue |1⟩ sphere combine into one sphere that is a blend of both
Teacher Ch2 · s.13Two basis states combine into one blended state.
Schrödinger's cat in a box with a radioactive source, a hammer and a vial of poison, drawn both alive and dead
Teacher Ch1 · s.16Schrödinger's 1935 thought experiment. He meant it to show how strange this gets if you scale it up to a cat.
Teacher Ch2 · s.13–14

2.8 Entanglement

Definition: a multi-qubit state is entangled if it cannot be written as a product of individual qubit states. You can't describe each qubit on its own.

\[ |\Phi^+\rangle = \tfrac{1}{\sqrt2}\big(|00\rangle + |11\rangle\big) \neq |a\rangle\otimes|b\rangle \]

This is the Bell state (also called an EPR pair). Try to factor it: you'd need a product that gives |00⟩ and |11⟩ but no |01⟩ or |10⟩. Impossible. So the two qubits share one joint state.

Building a Bell pair

StepState of q0 q1What happened
Start\(|00\rangle\)Both qubits at 0
1. H on q0\(\tfrac{1}{\sqrt2}(|00\rangle+|10\rangle)\)q0 is now a 50/50 blend
2. CNOT (q0 controls q1)\(\tfrac{1}{\sqrt2}(|00\rangle+|11\rangle)\)In each branch, q1 copies q0

Measure both: you get 00 or 11, each 50% of the time, and never 01 or 10. Each result on its own is random, but the two always match.

There are four Bell states, and they form a complete basis for two qubits:

\[ |\Phi^\pm\rangle=\tfrac{1}{\sqrt2}(|00\rangle\pm|11\rangle),\qquad |\Psi^\pm\rangle=\tfrac{1}{\sqrt2}(|01\rangle\pm|10\rangle) \]
Careful: no faster-than-light messages

Measuring one qubit instantly tells you what the other will show, even across the galaxy. But you can't choose your result, so you can't send a message with it. The correlation only becomes visible when both sides compare notes over a normal (light-speed) channel.

Think of it like…

A pair of magic dice that always land on the same number, wherever they are rolled. Each roll is still random. You can't make your friend's die show 6, but when you meet later you'll see you always matched. (Real entanglement is even stranger than this: Bell tests prove no hidden "pre-agreed" answer can explain it.)

Physics: entanglement comes from interactions, e.g. spin–spin coupling, or a crystal splitting one photon into an entangled pair (spontaneous parametric down-conversion). Algorithms: it enables teleportation, superdense coding, QKD, and VQE.

Real world

Einstein called this "spooky action at a distance" and suspected the particles had secretly agreed on their answers in advance, like the magic dice being rigged. John Bell worked out in 1964 that this could be tested, and experiments kept showing no such hidden agreement. The 2022 Nobel Prize in Physics went to Aspect, Clauser and Zeilinger for those experiments. So the circuit you're about to run is built on an effect that took a Nobel to confirm.

Teacher Ch2 · s.15–16
Try it

Mini circuit simulator

State (amplitudes)
Measurement probabilities

2.9 Interference

Here's the rule that makes quantum computers different from "just randomness":

The rule

Add the amplitudes first, then square. When two paths lead to the same outcome:

\[ \psi_{\text{total}} = \psi_1 + \psi_2, \qquad P = |\psi_1 + \psi_2|^2 \]

Same sign (in phase): they add up, constructive interference. Opposite sign (phase difference π): they cancel, destructive interference.

Classical probability would add the squares instead, \(|\psi_1|^2 + |\psi_2|^2\), and nothing could ever cancel.

Worked example: H twice

Start with |0⟩. After one H: \(\tfrac{1}{\sqrt2}(|0\rangle+|1\rangle)\). Apply H again. Each of the two branches splits again:

  • |0⟩ branch → \(\tfrac12|0\rangle + \tfrac12|1\rangle\)
  • |1⟩ branch → \(\tfrac12|0\rangle - \tfrac12|1\rangle\)

Now add: |0⟩ gets ½ + ½ = 1, |1⟩ gets ½ − ½ = 0. You always read 0. The two paths to |1⟩ cancelled, just like the dark stripes in the double slit. Put a Z between the two H's and the minus sign moves, so you always read 1 instead.

Try it

Two paths, one outcome

0°
Think of it like…

Noise-cancelling headphones. The headphones play a sound wave that is the exact opposite (phase-shifted by 180°) of the noise. Peak meets trough, and they cancel into silence. Quantum algorithms do this to wrong answers.

Algorithmic role: the Quantum Fourier Transform uses interference to isolate frequencies, and Grover's algorithm amplifies the right answer by constructive interference.

Teacher Ch2 · s.17–19

2.10 The no-cloning theorem

Statement: there is no operation (no unitary U) that copies an unknown quantum state:

\[ \nexists\, U \text{ such that } U\big(|\psi\rangle\otimes|0\rangle\big) = |\psi\rangle\otimes|\psi\rangle \text{ for every } |\psi\rangle \]

Why (a 4-line proof): suppose such a U existed. It must copy the basis states: \(U|0\rangle|0\rangle = |00\rangle\) and \(U|1\rangle|0\rangle = |11\rangle\). Gates are linear, so for \(|\psi\rangle=\alpha|0\rangle+\beta|1\rangle\):

\[ U|\psi\rangle|0\rangle = \alpha|00\rangle + \beta|11\rangle \quad\text{but a real copy is}\quad |\psi\rangle|\psi\rangle = \alpha^2|00\rangle + \alpha\beta|01\rangle + \alpha\beta|10\rangle + \beta^2|11\rangle \]

These only match when α or β is 0. So no machine can copy a general superposition. (Notice the left side is the Bell state: CNOT "tries to copy" and produces entanglement instead.)

Think of it like…

Classical info is like printed text: reading it doesn't change it, so photocopying is free. Quantum info is like super-delicate wet paint: to learn it well enough to copy it, you have to touch (measure) it, and touching smudges the very details you wanted.

A person using a photocopier, next to a copier trying to copy a glowing atom
Teacher Ch2 · s.21Copying a page is easy. Copying a quantum state isn't possible.
Where it's used

Quantum Key Distribution. An eavesdropper on a quantum channel can't copy the qubits passing by. Any attempt to measure them disturbs them and introduces detectable errors. This also blocks counterfeiting in "quantum money".

Teacher Ch2 · s.20–21

2.11 Randomness

Measurement outcomes are probabilistic by the Born rule, \(P(0)=|\alpha|^2,\ P(1)=|\beta|^2\). A photon polarised at 45° gives random horizontal/vertical results. That's fundamentally unpredictable, and Bell tests rule out "hidden variables" that secretly decide the answer.

Dice rollQubit in |+⟩
Only looks random. In theory its motion decides the result.Truly random. Even with perfect knowledge of the state, you can't predict which outcome you'll get.
Where it's used

QRNGs: Monte Carlo simulations, cryptographic key generation, blockchain security, fair lotteries.

Real world

Encryption keys are only as good as their randomness, and computers are bad at producing it. So Cloudflare films a wall of lava lamps at its San Francisco office and feeds the footage in as a source of unpredictability. A quantum generator gets there from physics directly. It's small enough now that a phone can have one: Samsung's Galaxy A Quantum (2020) shipped with a quantum random number chip.

Teacher Ch2 · s.22

2.12 Quantum teleportation

What it does: moves a qubit's state from Alice to Bob without sending the particle itself.

What you need: one shared entangled pair (Alice holds one half, Bob the other), and a normal phone or internet line to send 2 classical bits.

How it works, step by step

  1. Alice has a mystery state |ψ⟩ on q0. Alice and Bob share a Bell pair on q1 (Alice) and q2 (Bob).
  2. Alice applies CNOT (q0 → q1), then H on q0. This is a Bell measurement set-up: it rotates her two qubits so that measuring them in the normal basis tells her which Bell state they were in.
  3. Alice measures q0 and q1, getting two random bits m0 m1. Her original state is destroyed (as no-cloning requires).
  4. She phones Bob the two bits.
  5. Bob fixes his qubit: if m1 = 1 apply X; if m0 = 1 apply Z. His qubit is now exactly |ψ⟩.
Alice's bits m0 m100011011
Bob appliesnothing (I)XZX then Z
The teleportation circuit: a shared EPR pair, Alice's encoding and measurement, and Bob's corrections, shown as a diagram and in a circuit editor
Teacher Ch2 · s.24The steps above as a circuit: encode, measure, send 2 bits, decode.
Try it

Teleport a qubit, one step at a time

State to send: cos(θ/2)|0⟩ + eiφsin(θ/2)|1⟩ 60° 45°
  1. Prepare: q0 = |ψ⟩, q1 = q2 = |0⟩.
  2. H on q1.
  3. CNOT q1 → q2. Now q1 (Alice) and q2 (Bob) share a Bell pair.
  4. CNOT q0 → q1.
  5. H on q0.
  6. Alice measures q0 and q1, then sends the 2 bits to Bob.
  7. Bob applies X (if m1 = 1) and Z (if m0 = 1).
Key points
  • No faster-than-light: Bob can't do anything useful until the 2 classical bits arrive.
  • No copying: Alice's original is gone. The state moved; it wasn't duplicated. That's how teleportation "works around" no-cloning.
  • Why it's useful: it's the basic "send-a-qubit" tool for quantum networks and distributed quantum computing (linking several QPUs).
Teacher Ch2 · s.23–24

2.13 Superdense coding

What it does: Alice sends 2 classical bits to Bob by transmitting only 1 qubit. It's teleportation's mirror image.

  1. Share: Alice and Bob share a Bell pair in advance (q0 Alice, q1 Bob).
  2. Encode: Alice applies one of four gates to her qubit: 00 → I, 01 → X, 10 → Z, 11 → X then Z (often written "XZ"). This turns the pair into one of the four Bell states.
  3. Send: Alice physically sends her one qubit to Bob.
  4. Decode: Bob applies CNOT (q0 → q1) then H on q0, and measures both. He reads Alice's two bits exactly.
The superdense coding circuit with Bob's and Alice's parts labelled, beside the same circuit in an editor
Teacher Ch2 · s.26The superdense coding circuit.
Try it

Send two bits with one qubit

Alice's message:
FeatureTeleportationSuperdense coding
GoalSend a quantum stateSend two classical bits
What's sent2 classical bits1 qubit
Requires1 pre-shared Bell pair1 pre-shared Bell pair
What arrivesThe exact qubit stateTwo classical bits
Why it's coolMoves a qubit state safelyDoubles the info per qubit sent

They are mirror images. Each trades one resource for the other, and both only work because entanglement was shared in advance. Without that pre-shared pair, one qubit can carry at most one classical bit (Holevo's bound).

Teacher Ch2 · s.25–27

2.14 Summary table and the Bell-state lab

ConceptQuantum definitionExampleUsed in
SuperpositionLinear combination of basis statesHadamard stateH gate, every algorithm
EntanglementNon-separable multi-qubit stateEPR / Bell pairsTeleportation, QKD, VQE
InterferencePhase-dependent amplitude additionDouble slit, phase gatesGrover, QFT
No-cloningNo unitary duplicates an unknown stateQKD eavesdrop testInformation security
RandomnessMeasurement obeys the Born ruleQRNGCryptography
TeleportationState transfer via entanglement + 2 bitsTeleportation circuitQuantum networks
Superdense coding2 classical bits via 1 qubitBell-pair communicationQuantum internet links
Teacher Ch2 · s.28

The lab: "Simulate a Bell state, explain the histogram, then insert one more H"

In The Quantum Land you set the number of qubits, drag gates onto wires, the site translates your circuit to QASM code (a text format for circuits), sends it to a server that runs it many times (shots), and draws the averaged results as a histogram. Use the circuit simulator above to check your reasoning; pick the "Lab" examples from its list.

  • Bell state histogram: two bars, 00 and 11, each about 50%. Why: after H + CNOT the state is \(\tfrac{1}{\sqrt2}(|00\rangle+|11\rangle)\); the Born rule gives ½ each, and 01/10 have amplitude 0.
  • Add H on q0 at the end: the state becomes \(\tfrac12(|00\rangle+|01\rangle+|10\rangle-|11\rangle)\). All four bars at 25%. The correlation looks gone in this measurement, but it's hiding in the minus sign on |11⟩ (a phase you can't see in a histogram).
  • Add the extra H on q0 before the CNOT instead: H·H = I by interference, so q0 is back to |0⟩, the CNOT does nothing, and you get 00 with 100%. Where you put a gate matters.
Careful: bit order in the tools

The Quantum Land and Qiskit label bits as q[3] q[2] q[1] q[0], with q0 on the right. For symmetric results like 00/11 it doesn't matter, but for 01 vs 10 it does. The Grover lab code even reverses its strings with k[::-1] to fix this.

Teacher Ch2 · s.12, s.29

Chapter 2 in ten lines

  • State: α|0⟩ + β|1⟩, with |α|² + |β|² = 1.
  • Born rule: P(0) = |α|², P(1) = |β|². Measuring collapses the state.
  • Bloch sphere: every qubit is a point; gates are rotations.
  • Gates are unitary (U†U = I), so they're reversible.
  • H makes superpositions; H⊗ⁿ gives all 2ⁿ inputs at once.
  • CNOT + H makes the Bell state (|00⟩+|11⟩)/√2, which is entangled.
  • Interference: add amplitudes, then square. They can cancel.
  • No-cloning: unknown states can't be copied (linearity).
  • Teleportation: 1 Bell pair + 2 bits moves 1 qubit state.
  • Superdense coding: 1 Bell pair + 1 qubit carries 2 bits.

Check yourself: Chapter 2

Chapter 3

Quantum Algorithms

Teacher Ch4 · s.4–5, s.26–33

3.1 What is a quantum algorithm?

Definition: a quantum algorithm is a set of instructions written to run on a quantum computer. It uses superposition, entanglement, and interference to solve problems in ways classical logic cannot. The goal: measuring at the end gives the correct answer with high probability. The work breaks into four steps:

  1. Initialize qubits: prepare the starting state, often |0⟩.
  2. Apply quantum gates: transform the state (H, CNOT, phase gates, an oracle).
  3. Use quantum interference: design operations so useful outcomes become more likely and unwanted ones less likely.
  4. Measure the qubits: get classical results (0s and 1s) and interpret them.

A point that's easy to miss: the circuit is only one part of the algorithm. The full cycle is Initialize → Operate → Measure → Interpret. Classical set-up before the circuit and classical post-processing after it (like the gcd step in Shor) can matter just as much.

Why quantum algorithms matter now

  • Unlocking quantum potential: hardware is useless without algorithms that give it problems to solve.
  • Quantum speed-up: Shor's and Grover's algorithms show real advantages over classical approaches. Shor breaks public-key crypto (RSA, ECC); Grover speeds up brute-force search, which weakens symmetric keys like AES.
  • Future innovation: better hardware enables more experiments, which leads to better algorithms.

The best one-line summary of the whole field:

Key idea

"A quantum algorithm is a program that choreographs complex probability amplitudes so that right answers interfere constructively and wrong answers cancel out."

FeatureClassical algorithmQuantum algorithm
UnitBit: 0 or 1, definiteQubit: superposition
State spacen bits = one of 2ⁿ statesn qubits = 2ⁿ amplitudes simultaneously
OperationsDeterministic logic gatesUnitary gates (probabilistic at measurement)
OutputSame input → same outputSame input → a distribution of outputs

Or put simply: "Think of it as a program built for quantum hardware, not magic or a faster answer to every problem."

Teacher Ch4 · s.4

Sorting the famous algorithms: The ones covered in this course are Deutsch–Jozsa, Bernstein–Vazirani, Grover, QPE, Shor and VQE. Others you'll hear about: QAOA (optimisation), Simon's algorithm, HHL (linear equations) and quantum walks.

3.2 How a quantum algorithm is developed

Think of it as a winding road with these stops. It's a cycle: when results are inaccurate or noisy, you go round again. A useful split: steps 1–4 happen on paper and on a perfect simulator; steps 5–7 happen on a real, noisy chip.

  1. Problem framing: define the goal, inputs and outputs.
  2. Algorithm design: map the math to quantum primitives (superposition, oracle, QFT…).
  3. Circuit construction: write the circuit with gates and measurements (Qiskit).
  4. Validation on an ideal simulator: check amplitudes and probabilities with no noise.
  5. Compilation / transpilation: rewrite for a specific chip's native gates and wiring; optimise.
  6. Noise modelling and fake back-end: emulate realistic errors with a fake device (e.g. FakePerth).
  7. Execution: run on the chosen back-end with a chosen number of shots.
  8. Result analysis: collect counts, compute metrics (accuracy, fidelity).
  9. Iterate and optimise: reduce circuit depth, refactor sub-circuits.
A winding road map of the development stages from problem framing through to iterating and optimising
Teacher Ch3 · s.5The winding road, from the slide.
Two histograms for a Bell state: an ideal simulator gives only two bars, and a fake device adds small bars from noise
Teacher Ch3 · s.9The same Bell circuit twice. The small extra bars on the right are noise, and they're why step 6 exists.
Teacher Ch4 · s.5
Think of it like…

Normal software development (design → code → test → deploy → monitor), except the "test" step has two levels: a perfect simulator first (unit test), then a noisy fake chip (staging), then the real chip (production).

3.3 Why we transpile: the chip's wiring

Now the step most beginners skip: transpilation. Your circuit assumes any qubit can talk to any other, using any gate. A real chip can't do that, for two reasons:

  • Wiring: qubits are only connected to their neighbours. The map of which qubits are wired together is the coupling map.
  • Native gates: the chip only understands a few gates. IBM Heron chips: CZ, RZ, SX and X. Everything else (H, CNOT, Toffoli…) must be rewritten in those.

Example: IBM's 7-qubit chip. You want a CNOT between qubit 0 and qubit 6, but they aren't wired together. The transpiler moves qubit 0's state step by step with SWAP gates along the route 0 → 1 → 3 → 5, so it ends up next to 6. That's 3 SWAPs, and since each SWAP = 3 CNOTs, that's 9 extra noisy gates. Click two qubits below to see the route.

Try it

Route a CNOT on a 7-qubit chip

Click a control qubit, then a target qubit.

A 7-qubit chip's coupling map and a larger device map with error rates, used for routing
Teacher Ch3 · s.15A real coupling map. Only joined qubits can talk.

The 6 phases of transpilation

Every circuit is rewritten in six phases before it runs:

PhaseWhat it doesExample
1. Virtual optimizationSimplify before thinking about the chip: delete gates that cancel, merge neighbouring rotationsH then H = nothing; CNOT then CNOT = nothing
2. Gate decompositionBreak 3-qubit gates into 1- and 2-qubit gates (chips can't do more)Toffoli → 6 CNOTs + single-qubit gates
3. Placement (layout)Give each circuit qubit (q0, q1…) a physical qubit; pick wired, low-error onesGood placement = fewer SWAPs later
4. RoutingAdd SWAPs when two qubits in a gate aren't neighboursEach SWAP = 3 CNOTs, so each one adds noise
5. TranslationRewrite every gate into the chip's native gatesH, CNOT → CZ, RZ, SX, X on IBM Heron
6. Physical optimizationClean up again now the real layout is known: cut depth and 2-qubit gatesQiskit optimization_level 0–3
A circuit passes through six labelled phases from virtual optimization to physical optimization and comes out changed
Teacher Ch3 · s.10The six phases in order.

That's exactly the line transpile(qc, simulator) in every lab, and the Grover lab uses optimization_level=3. IBM's own tests show the best level depends on the circuit, so compare them.

Think of it like…

Translating a speech for a foreign audience. First you cut the repetition (phase 1), split long sentences (2), assign who reads which part (3), arrange seats so speakers who need to talk to each other sit together, or pass notes along the row (4), translate into the local language (5), then polish the final text (6). Every extra note passed is a chance for a mistake.

Bar chart of fidelity for twelve circuits on an ideal simulator, a fake device and a real device. Real device bars drop to about 0.4 on ghz_state and multiply
Teacher Ch3 · s.18The same circuits on all three. Real hardware drops to about 0.4 fidelity on ghz_state and multiply, and that loss is what a good transpile tries to limit.

3.4 Oracles and quantum parallelism

The oracle

A quantum oracle is a black-box operation used to evaluate a function or check properties of an input without revealing its internal mechanism. You can't look inside; you can only query it. We compare algorithms by counting queries. Think of a locked vending machine: you only learn about it by pressing buttons.

There's a catch: quantum operations must be reversible. A function like AND isn't: if AND outputs 0, you can't tell whether the input was 00, 01 or 10. So the standard oracle keeps the input x and XORs the answer into an extra qubit y:

\[ U_f\,|x\rangle|y\rangle = |x\rangle\,|y\oplus f(x)\rangle \]

"The oracle preserves x and writes f(x) into y using XOR." Applying it twice gives back the original (y ⊕ f ⊕ f = y), so it's its own inverse and a valid unitary. That's why we need the auxiliary qubit.

Quantum parallelism

Quantum parallelism is the ability of a quantum computer to apply an operation to multiple inputs simultaneously by using a superposition of quantum states. Put H on every input qubit, then call the oracle once, with y = 0:

\[ U_f\Big(\frac{1}{\sqrt{2^n}}\sum_x |x\rangle\Big)|0\rangle = \frac{1}{\sqrt{2^n}}\sum_x |x\rangle|f(x)\rangle \]

One call to \(U_f\), and the state now "contains" f(x) for every x. Example with f = AND on 2 bits: after H⊗H and one oracle call the state is \(\tfrac12\big(|00\rangle|0\rangle + |01\rangle|0\rangle + |10\rangle|0\rangle + |11\rangle|1\rangle\big)\). That's all 4 rows of the AND truth table after one call; classically that takes 4 calls.

The catch
  • Outcome ≠ result: measuring gives you one random pair (x, f(x)). You can't read all the values out.
  • Not an O(1) speedup: parallelism doesn't mean solving problems instantly.
  • A building block: it only helps when followed by interference that turns a global property of f (is it constant? what's its period?) into a measurable answer.

Concretely: measuring the AND state above gives one random row, (00, 0), (01, 0), (10, 0) or (11, 1), each with 25%. "One measurement = one random row. No better than one classical query." The fix is to make f(x) show up as a phase (+ or −) instead of a bit flip, so it can interfere. That's phase kickback, next.

3.5 Phase kickback: the trick behind the oracles

Phase kickback is a quantum effect where a controlled operation transfers phase information from the target qubit to the control qubit's superposition. In three steps: control in superposition → controlled operation → relative phase changes. It sounds backwards, but it's how oracles "write" their answer into the qubits we measure. And it's useful because quantum computers can transform phase information into measurable outcomes through interference.

The key fact: the state \(|-\rangle = \tfrac{1}{\sqrt2}(|0\rangle-|1\rangle)\) is unchanged by X except for a sign, \(X|-\rangle = -|-\rangle\). So:

\[ U_f\,|x\rangle|-\rangle = (-1)^{f(x)}\,|x\rangle|-\rangle \]

If f(x) = 1, the oracle flips the target, which just multiplies everything by −1. That minus sign "belongs" to |x⟩. The target is untouched; the information jumped ("kicked back") into the phase of the input register.

A two-line derivation shows it directly with the XOR oracle on target |−⟩:

\[ f(x)=0:\ \tfrac{1}{\sqrt2}\big(|0\rangle-|1\rangle\big) \to \tfrac{1}{\sqrt2}\big(|0\rangle-|1\rangle\big) = +|-\rangle \qquad f(x)=1:\ \tfrac{1}{\sqrt2}\big(|0\rangle-|1\rangle\big) \to \tfrac{1}{\sqrt2}\big(|1\rangle-|0\rangle\big) = -|-\rangle \]
ProtocolGoalWhat's transmittedRole of entanglement
Phase kickbackEncode f's value into the control qubitA relative phase shiftIndirect (via the controlled oracle)
Superdense codingSend 2 classical bits with 1 qubit1 physical qubitPre-shared Bell pair required
TeleportationSend 1 unknown quantum state2 classical bitsPre-shared Bell pair required

In short: teleportation and superdense coding move data between people; phase kickback works inside a circuit to compute.

A demo

  1. Preparation: q0: H → |+⟩. q1: X then H → |−⟩.
  2. Kickback: CNOT (q0 control, q1 target). The control changes from |+⟩ to |−⟩.
  3. Measurement: H on q0 turns |−⟩ into |1⟩. Result: 1 (100%).
A two-qubit circuit: H on the input, X then H on the helper, the oracle U_f, then H and measurement on the input qubit
Teacher Ch3 · s.29The pattern every oracle algorithm repeats.

Load "Phase kickback" in the circuit simulator to see this.

Think of it like…

Pushing off a wall on roller skates. You push the wall (the target), but the wall doesn't move; you do. The control qubit "pushes" on the target and gets the recoil.

Teacher Ch4 · s.20

3.6 Deutsch and Deutsch–Jozsa

The problem

You're given a black-box function f that takes bits and returns 0 or 1. You're promised it's one of two kinds:

  • Constant: same output for every input (all 0s, or all 1s).
  • Balanced: exactly half the inputs give 0, half give 1.

Which kind is it?

Deutsch (1 bit, 1985)

With one input bit there are four possible functions: f(0)=f(1)=0 and f(0)=f(1)=1 are constant; f(x)=x and f(x)=NOT x are balanced. Classically you must test twice (x = 0 and x = 1). Quantum needs once:

  1. Prepare 2 qubits as |0⟩|1⟩.
  2. Apply H to both: \(|+\rangle|-\rangle\).
  3. Apply the oracle. Phase kickback gives \(\tfrac{1}{\sqrt2}\big((-1)^{f(0)}|0\rangle + (-1)^{f(1)}|1\rangle\big)|-\rangle\).
  4. Apply H to the first qubit and measure: you get \(|f(0)\oplus f(1)\rangle\). 0 = constant, 1 = balanced.

⊕ means XOR: it's 0 if f(0) and f(1) are equal (constant), 1 if they differ (balanced). One query answered a question about both values. That's interference at work.

Deutsch–Jozsa (n bits, 1992)

Same idea with n input bits. Classically, in the worst case you must check \(2^{n-1}+1\) inputs (more than half) to be sure. Quantum: one query. After H⊗ⁿ, oracle, H⊗ⁿ, the amplitude of the all-zero outcome is:

\[ \text{amp}\big(|0\cdots0\rangle\big) = \frac{1}{2^n}\sum_{x}(-1)^{f(x)} = \begin{cases}\pm1 & \text{constant}\\ 0 & \text{balanced}\end{cases} \]

If f is constant, all the signs agree and add up to ±1: you see 00…0 with certainty. If balanced, half are + and half are −, so they cancel to exactly 0: you never see 00…0.

The circuit as five boxes (the states ψ₀ to ψ₃ sit between the steps):

  1. Initialize n input qubits to |0⟩ and one target to |1⟩
  2. Create superposition: H on all (target becomes |−⟩)
  3. Apply the oracle \(U_f\): phase \((-1)^{f(x)}\) kicks back
  4. Apply H to the input qubits (interference)
  5. Measure: all 0s → constant, otherwise balanced
Input bits nClassical worst case \(2^{n-1}+1\)Quantum
35 queries1 query
10513 queries1 query
322,147,483,649 queries1 query
64≈ 9.2 × 10¹⁸ (over 9 quintillion)1 query
Try it

Constant or balanced?

A secret function is loaded. Solve it either way.
Why it matters

Nobody needs to know whether a function is constant or balanced. Deutsch–Jozsa matters because it was the first clean proof that a quantum computer can beat a classical one at something (an exponential gap in queries for an exact answer). Its structure (H, oracle, H, measure) is the template for later algorithms. The family tree:

  • Deutsch–Jozsa (1992): first deterministic separation between classical and quantum; pioneered phase kickback.
  • Bernstein–Vazirani (1993/97): finds a hidden n-bit string in 1 query instead of n (Chapter 4).
  • Simon's algorithm (1994): finds a hidden period with exponential speed-up; it directly inspired Shor.
  • Shor (1994) and Grover (1996): the real-world impact, factoring and search.

3.7 Grover's search algorithm

The problem: find a marked item in an unsorted collection of N items. Formally, find x₀ where

\[ f(x) = \begin{cases}1 & x = x_0\\ 0 & \text{otherwise}\end{cases} \]

Picture 1,000 closed boxes, one holds a prize. Classically you open them one by one: about N/2 on average, N in the worst case, so O(N). Grover (1996, Lov Grover) needs only about \(\sqrt N\) queries: a quadratic speed-up. For a million boxes, that's ~785 steps instead of ~500,000.

The four steps

  1. Initialise: H on every qubit. All N items get equal amplitude \(1/\sqrt N\).
  2. Oracle: flips the sign of the marked item's amplitude (multiplies it by −1) and leaves the rest alone. Probabilities don't change yet, because \((-a)^2 = a^2\). It just marks the answer.
  3. Diffusion ("inversion about the mean"): compute the average amplitude, then reflect every amplitude around it: \(a \to 2\bar a - a\). Because the marked one is now negative, it sits far below the mean and gets flung far above it. The others shrink slightly.
  4. Repeat steps 2–3 about \(\frac{\pi}{4}\sqrt{N}\) times, then measure.
\[ k_{\text{opt}} \approx \Big\lfloor \frac{\pi}{4}\sqrt{N} \Big\rfloor, \qquad P_{\text{success}} = \sin^2\!\big((2k+1)\,\theta\big),\quad \sin\theta = \tfrac{1}{\sqrt N} \]

Each oracle + diffusion pair rotates the state a little closer to the answer, by angle 2θ. After about (π/4)√N turns, you're pointing at it. With M marked items, use \(\frac{\pi}{4}\sqrt{N/M}\).

Worked example with real numbers (8 boxes, target |110⟩)

  1. Initialise: 3 qubits, 8 states, each amplitude \(1/\sqrt8 \approx 0.354\), probability 12.5%.
  2. Oracle: |110⟩'s amplitude becomes −0.354. Every probability is still 12.5%.
  3. Mean: \(\bar a = \frac{7(0.354) - 0.354}{8} \approx 0.265\).
  4. Reflect about the mean (\(2\bar a - a\)): wrong answers become \(2(0.265) - 0.354 \approx 0.177\); the target becomes \(2(0.265) + 0.354 \approx 0.884\).
  5. Probabilities: target \(0.884^2 \approx\) 78.1%; each other state \(0.177^2 \approx 3.1\%\).
Iterations0123
P(target), N = 812.5%78.1%94.5%33.0%

Two iterations is the sweet spot (\(\frac\pi4\sqrt8 \approx 2.22 \to 2\)). A third overshoots and the probability crashes to 33%. Reproduce every number above in the lab below (3 qubits, marked item 110).

Grover's circuit: Hadamards, then an oracle and diffuser block repeated about the square root of N times
Teacher Ch2 · s.19The steps as a circuit: the oracle and diffuser block repeats.
Try it

Watch the amplitudes move

Bars show amplitudes: teal above the line is positive, coral below is negative. The dashed gold line is the mean. Keep pressing past the optimum and watch the probability fall again.

Careful: more is not better

Grover overshoots. Past the optimal number of iterations, the success probability goes back down (the probability oscillates). So you must know roughly how many solutions there are. With 2 qubits (N = 4), one iteration gives exactly 100% (try target 10).

Where it's used
  • Speeding up any brute-force search: constraint problems, SAT solvers, database lookups by condition.
  • Cryptography: Grover could search a key space of size N in √N steps. That's why AES-128 is considered weakened (to ~64-bit strength) and AES-256 is recommended for the post-quantum world.
  • Its generalisation, amplitude amplification, is the core of quantum Monte Carlo for finance.
Teacher Ch4 · s.26–29

3.8 Shor's algorithm

Peter Shor, 1994: a quantum algorithm that factors a composite integer N into its primes in polynomial time. It uses Quantum Phase Estimation and the Quantum Fourier Transform to find the period of a modular arithmetic function.

Portrait of Peter Shor with his arms crossed in front of a chalkboard
Peter Shor.
Best classical (General Number Field Sieve)Shor (quantum)
Time\(O\!\left(e^{c\,(\log N)^{1/3}(\log\log N)^{2/3}}\right)\), sub-exponential\(O\big((\log N)^3\big)\), polynomial
This is why everyone cares

RSA encryption (used in HTTPS, banking, SSH, digital signatures) is safe only because multiplying two big primes p × q = N is easy, while recovering p and q from N is astronomically hard for classical computers. A large fault-tolerant quantum computer running Shor would break it. The same algorithm also breaks elliptic-curve crypto. That's why NIST standardised post-quantum algorithms in 2024, and why governments worry about "harvest now, decrypt later" (recording encrypted traffic today to decrypt it in the future).

How close is the threat?

Estimates of how many qubits it would take to break RSA-2048 keep shrinking as algorithms improve, while chips keep growing:

The gap is still huge (thousands of times) and the estimates assume noisy qubits with heavy error correction. In short: Shor breaks RSA/ECC (HTTPS, banking, software updates) because it solves their math fast, but not yet: it needs an error-corrected machine.

The big idea: turn factoring into period finding

Pick a random number a. Look at the powers of a, mod N: \(a^1, a^2, a^3, \dots \pmod N\). This sequence repeats. The length of the repeat is the period (or order) r: the smallest r with \(a^r \equiv 1 \pmod N\). If you know r, a little classical arithmetic gives the factors.

SymbolMeaning
NThe number you want to factor (e.g. 15)
aA random number you pick, 1 < a < N (e.g. 7)
rThe period: smallest positive integer with \(a^r \equiv 1 \pmod N\). Found by the quantum part
p, qThe two factors you're looking for, with p × q = N

Part 1: classical setup and reduction

  1. Pick a random a. Compute gcd(a, N). If it isn't 1, you got lucky: that's already a factor.
  2. Hand a and N to Part 2 to find r.
  3. If r is odd, or \(a^{r/2} \equiv -1 \pmod N\), pick a new a and retry.
  4. Otherwise the factors are \(\gcd(a^{r/2}-1,\,N)\) and \(\gcd(a^{r/2}+1,\,N)\).

Why it works: \(a^r - 1 = (a^{r/2}-1)(a^{r/2}+1)\) is a multiple of N, but (thanks to the checks) neither bracket alone is. So each bracket must share a factor with N, and gcd pulls it out. gcd (greatest common divisor) is fast to compute with Euclid's algorithm.

Part 2: quantum order-finding

  1. Put all exponents x into one superposition (H gates on a "control register").
  2. Compute \(a^x \bmod N\) into a second register for all x at once (controlled modular exponentiation, \(U_a^{2^j}\) gates). The registers become entangled.
  3. Apply the inverse Quantum Fourier Transform to the control register. It turns the repeating pattern into sharp peaks (Chapter 4).
  4. Measure: you get a number m with \(m / 2^t \approx s/r\) for some random s. The continued fractions algorithm turns that fraction into r.

Here's why this is phase estimation. Define the gate "multiply by a": \(M_a|x\rangle = |a x \bmod N\rangle\). Its eigenvalues are \(e^{2\pi i k/r}\) for k = 0 … r−1, so its phases are fractions k/r with the period hidden in the denominator. And the easy start state |1⟩ is an equal mix of all those eigenvectors:

\[ M_a|u_k\rangle = e^{2\pi i k/r}|u_k\rangle, \qquad |1\rangle = \frac{1}{\sqrt r}\sum_{k=0}^{r-1}|u_k\rangle \;\Rightarrow\; \text{QPE measures } \frac{y}{2^m} \approx \frac{k}{r} \]

How many control qubits? \(m = 2\lceil\log_2 N\rceil + 1\). Example: suppose r = 6, so the phase to find is 1/6. With m = 5, the best approximation is y = 5 out of 32 (about a 68% chance), and 32/5 = 6.4 rounds to 6, which is correct. With m = 4, the best is 3/16, and 16/3 = 5.33 rounds to 5, which is wrong. Too few qubits give a wrong period.

Cost and success: each controlled \(M_a^{2^j}\) costs O(n²) gates (n = number of bits in N) and there are O(n) of them, so O(n³) in total. One run fails (r odd, or trivial gcd) with probability at most ½, so a few repeats are enough. The powers \(a^2, a^4, \dots \bmod N\) are computed on a normal computer first.

Worked example: factoring 15

N = 15, pick a = 7. gcd(7, 15) = 1, so no lucky shortcut. Powers of 7 mod 15:

x7ˣ7ˣ mod 15
177
2494
334313
424011 → r = 4

r = 4 is even. \(7^{2} = 49\). Then \(\gcd(48, 15) = 3\) and \(\gcd(50, 15) = 5\). So 15 = 3 × 5.

Same number, different a

Now use a = 2. Step 1: gcd(2, 15) = 1, so use order finding. Step 2: 2¹ = 2, 2² = 4, 2³ = 8, 2⁴ = 16 ≡ 1 (mod 15), so r = 4. Step 3: x = 2^{r/2} = 2² = 4. Step 4: gcd(4 − 1, 15) = 3 and gcd(4 + 1, 15) = 5. Different a, same period, same factors. (This is exactly what the Shor lab prints for N = 15.)

Try it

Shor's recipe on any small number

Try 15, 21, 35, 55, 77, 91, 143
The power sequence aˣ mod N (the pattern the quantum computer finds)
What the quantum measurement would look like (8 counting qubits after inverse QFT)
Careful: a common mix-up

It's tempting to say "r = (p−1)(q−1)". That number is Euler's totient φ(N), which RSA uses to build its private key. The period r that Shor finds is the order of a specific a, which divides φ(N) but is usually smaller. For N = 15: φ(15) = 2 × 4 = 8, while the order of 7 is 4. The conclusion is the same: find r, break RSA.

Teacher Ch4 · s.30–32

3.9 Algorithms for today's chips: VQE and QAOA

Shor and Grover need big, error-corrected machines. What can we run now, on 50 to a few hundred noisy qubits where circuits must stay short? The answer is the hybrid loop:

  1. Quantum chip runs a short circuit with some rotation angles θ and measures a cost
  2. Classical computer (an optimizer) picks better angles
  3. Repeat until the cost stops improving
  • VQE (Variational Quantum Eigensolver): finds the lowest energy (the "ground state") of a molecule.
  • QAOA (Quantum Approximate Optimization Algorithm): finds good answers to optimisation problems like routing and scheduling.

VQE in detail

Input: a Hamiltonian H (the energy operator of the system) and a parametrized circuit (the "ansatz" or variational form) that prepares a trial state \(|\psi(\theta)\rangle\). Cost: the energy of that trial state:

\[ C(\theta) = \langle\psi(\theta)|\,H\,|\psi(\theta)\rangle \]

"The average energy you'd measure in the state the circuit makes." By the variational principle, it can never be lower than the true ground energy, so pushing it down gets you closer to the answer.

  1. Start from |0⟩ and prepare a reference state (IBM's example: X on qubit 0).
  2. Apply the variational form \(U_V(\theta)\) (IBM's example: RZ and RY on each qubit plus one CX, 8 angles in total).
  3. Estimate C(θ) on the quantum computer. H is written as a weighted sum of parts (e.g. weights 2, −2, 3, −3); each part is measured and the results are added up.
  4. A classical optimizer (e.g. COBYLA) picks the next angles.
  5. Repeat until it converges.

In IBM's run, the simulator found a cost of about −6.0 after 136 evaluations; the real hardware ended several percent off after 96. Every new set of angles means running the circuit again, so IBM groups all runs in one session to queue only once.

Try it

A one-qubit VQE

Hamiltonian \(H = Z + 0.8\,X\). Trial state \(R_y(\theta)|0\rangle\), so the cost is \(C(\theta) = \cos\theta + 0.8\sin\theta\). Move θ yourself, or let the "classical optimizer" take gradient steps.

20°
Careful

Timeline: now (NISQ) is VQE, QAOA and simulation; later (error-corrected) is Shor and Grover, with IBM targeting about 2029. VQE and QAOA can get stuck in local minima or "barren plateaus", so their advantage over classical methods is not yet proven.

3.10 Limitations and comparison

AlgorithmClassicalQuantumSpeed-up
Deutsch–JozsaUp to \(2^{n-1}+1\) queries to be sure1 queryExponential (in queries)
QFTFast Fourier Transform: about \(n\cdot2^n\) stepsAbout \(n^2\) gatesExponential (but output is hidden in amplitudes)
GroverAbout N stepsAbout \(\sqrt N\) stepsQuadratic
ShorGNFS: sub-exponentialPolynomial, \(O((\log N)^3)\)Exponential

Two families of algorithms

Fault-tolerant
Shor, Grover, QPE (phase estimation), HHL (linear equations).
Clear theoretical speed-ups, but they need a big, reliable machine that doesn't exist yet.
NISQ
VQE (chemistry), QAOA (optimisation).
Small noisy machines working with a normal computer. They run today, but their advantage over classical methods is unproven.

Hardware limits

  • Noise: qubits lose their state quickly, and gates make errors.
  • Error correction: one logical qubit may need hundreds to thousands of physical qubits.
  • Scale: today's machines have hundreds to a few thousand qubits. Shor on RSA-2048 needs close to a million noisy qubits (Gidney, 2025, "less than a million").

Algorithm challenges

  • Few real speed-ups: only structured problems benefit. Grover's quadratic gain is often eaten by slow quantum clock speeds and error-correction overhead.
  • Input and output: loading classical data into qubits can cost as much as the speed-up saves, and each measurement gives very little information.
  • No guarantees: VQE and QAOA can get stuck in local minima and "barren plateaus" (flat landscapes where training stalls). Classical methods keep matching claimed advantages.
  • Practical limits: deep circuits are destroyed by noise, qubit connectivity is limited, and debugging is hard (you can't peek at a state without destroying it).

Five limits

  1. Noise limits circuit size; reliable machines around 2029
  2. Speed-ups only for special problems, not everything
  3. Measurement gives one answer per shot
  4. Loading big data into qubits is slow
  5. Expensive: extreme cooling (near −273 °C), many physical qubits per logical qubit

Side by side

GroverQPEShorVQE
ProblemFind one item in an unsorted listFind the rotation (phase) of a gateBreak a number into factorsFind the lowest energy of a system
Key gatesH, oracle, diffusionH, controlled-U, inverse QFTQPE with U = multiply by a (mod N)X, RZ, RY, CX
OutputThe marked itemThe phaseThe order r, then the factorsThe lowest energy and best angles
Hardware needsRepeat oracle + diffusion a fixed number of timesDeep: controlled-U count doubles per extra qubitMany qubits, deep circuits (≈ n³)Short circuit, many repeated runs with a classical optimizer

Chapter 3 in twelve lines

  • Initialize → gates → interference → measure (→ interpret). Wrong answers cancel.
  • Development: frame, design, build, simulate, transpile, fake-noise, run, analyse, iterate.
  • Transpiling: optimize, decompose, place, route (SWAPs), translate to native gates, optimize.
  • Oracle: \(U_f|x\rangle|y\rangle = |x\rangle|y\oplus f(x)\rangle\), reversible thanks to XOR.
  • VQE/QAOA: hybrid loop of a short circuit plus a classical optimizer; runs on NISQ today.
  • Parallelism evaluates f on all inputs, but you can only read one: you need interference.
  • Phase kickback: \(U_f|x\rangle|-\rangle = (-1)^{f(x)}|x\rangle|-\rangle\).
  • Deutsch–Jozsa: constant vs balanced in 1 query (classical: \(2^{n-1}+1\)).
  • Grover: oracle flips sign, diffusion reflects about mean; ~(π/4)√N iterations.
  • Grover overshoots if you iterate too long.
  • Shor: factoring → finding the period r of aˣ mod N.
  • Factors = gcd(a^{r/2} ± 1, N); retry if r is odd or a^{r/2} ≡ −1.
  • Fault-tolerant algorithms (Shor, Grover, QPE, HHL) vs NISQ (VQE, QAOA).

Check yourself: Chapter 3

Chapter 4

Quantum Fourier Transform

Teacher Ch4 · s.1–35Labs: QPE, Grover, Shor

Chapter 4 does two jobs. It introduces the Quantum Fourier Transform (QFT), the engine inside Shor and phase estimation. Then it revisits the algorithms as hands-on labs: QFT-3, BV-8, QPE, Grover on 3 qubits, and Shor. Let's open with a game.

4.1 Game: find the hidden beat

Goal: discover the "hidden period" in a repeating pattern, just like the QFT finds hidden periodicities in quantum data. Listen (or watch the dots), then guess how many claps make up one repeat. The loud clap marks the start of each repeat.

Play

Find the Hidden Beat!

Period =
Press "Play pattern".

When the period is 3, you hear it instantly. When it's 10, you need to concentrate. And if the pattern is long and noisy, your ears give up. The QFT is a mathematical ear that finds the period of a pattern hidden inside 2ⁿ amplitudes, using only about n² gates.

Teacher Ch4 · s.6–9

4.2 The classical Fourier transform

The Fourier Transform (FT) expresses a signal as a sum of sine waves with different frequencies. It converts a signal from the time domain ("what happens when") into the frequency domain ("which rhythms are in it").

Think of it like…

A smoothie and its recipe. The time signal is the blended smoothie. The Fourier transform un-blends it and tells you: 50% banana, 30% mango, 20% milk. In sound: a chord goes in, and out come the individual notes.

A jagged red signal over time splits into separate waves, and those waves become bars on a frequency axis
One messy signal, split into its waves, read off as frequencies.

For a list of N numbers \(x = (x_0, \dots, x_{N-1})\), the Discrete Fourier Transform (DFT) produces a new list \(y = (y_0, \dots, y_{N-1})\):

\[ y_k = \frac{1}{\sqrt N}\sum_{j=0}^{N-1} x_j\, e^{2\pi i\, jk/N} \]

For each frequency k, walk through the signal, spin each sample \(x_j\) by angle \(2\pi jk/N\), and add everything up. If the signal really repeats at that frequency, the spins line up and add to something big. If not, they point in random directions and cancel. Interference again.

Where it's used (classically, everywhere)

MP3 and JPEG compression, Shazam song recognition, Wi-Fi and 4G/5G signals, MRI image reconstruction, audio equalisers, earthquake analysis. The fast algorithm for it, the FFT, is one of the most important algorithms ever written.

Teacher Ch4 · s.10

4.3 The Quantum Fourier Transform

In quantum computing, the amplitudes \(\alpha_j\) of the basis states \(|j\rangle\) play the role of the classical numbers \(x_j\). The QFT does the DFT on those amplitudes. On a single basis state:

\[ \mathrm{QFT}\,|j\rangle = \frac{1}{\sqrt N}\sum_{k=0}^{N-1} e^{2\pi i\, jk/N}\,|k\rangle, \qquad N = 2^n \]

Every output |k⟩ gets the same size, 1/√N, so a single input becomes a perfectly even superposition. The information is in the phases: output k's arrow is turned by j·k/N of a full circle.

  • N: total number of basis states (2ⁿ for n qubits). j: input basis-state index. k: index of each output state.
  • 1/√N: normalisation, keeps total probability = 1.
  • \(e^{2\pi ijk/N}\): the phase factor applied to each output state.

It changes the computational basis (|0⟩, |1⟩, …) into the Fourier basis (states with evenly spaced phases). And the QFT matrix is unitary (\(U^\dagger U = I\)), so it's a valid quantum gate.

For one qubit (N = 2) the QFT is just the Hadamard gate. For two qubits (N = 4, and \(e^{2\pi i/4} = i\)):

\[ \mathrm{QFT}_4 = \frac12\begin{pmatrix}1&1&1&1\\1&i&-1&-i\\1&-1&1&-1\\1&-i&-1&i\end{pmatrix} \]
Four dials for QFT|01⟩: |00⟩ at 0 degrees, |01⟩ at 90, |10⟩ at 180 and |11⟩ at 270
QFT|01⟩: every output has the same size, and only the dial turns. It's a picture of what you're about to play with.

Below, each dial is one output amplitude. Pick an input |j⟩ and watch how fast the hands turn as k increases. The bigger j, the faster they spin. That "spin speed" encodes j.

Try it

QFT phase clocks (3 qubits)

The product form: why it's cheap

The QFT output turns out to be a product of single-qubit states, one per qubit:

\[ \mathrm{QFT}\,|j\rangle = \bigotimes_{l=1}^{n} \frac{|0\rangle + e^{2\pi i\, j/2^{l}}\,|1\rangle}{\sqrt2} \]

Each output qubit is an equal blend of |0⟩ and |1⟩ with its own phase. One qubit turns j/2 of a circle, the next j/4, the next j/8, like the hands of a clock: second hand, minute hand, hour hand. Because each qubit only needs one H and a few phase rotations, the whole circuit is small.

"Exponential compression": the QFT acts on all 2ⁿ amplitudes at once using only ~n² gates, while the classical FFT needs ~n·2ⁿ steps. But remember the catch from Chapter 3: you can't read all the amplitudes out. The QFT is only useful as a step inside algorithms where one measurement is enough, like period finding.

Teacher Ch4 · s.10–11

4.4 Building the QFT circuit, and its inverse

Goal: analyse the periodicity (repeating patterns) encoded in quantum states. The construction for n qubits:

  1. For each qubit j from 0 to n−1:
    • Apply H to qubit j.
    • For each later qubit k > j: apply a controlled rotation \(R_m\) with qubit k as control and j as target, where \(m = k - j + 1\).
  2. Finally, reverse the order of the qubits with SWAPs (the "bit reversal").
\[ R_m = \begin{pmatrix}1&0\\0&e^{2\pi i/2^m}\end{pmatrix} = P\!\left(\tfrac{2\pi}{2^m}\right) \]

R₂ is a 90° phase (π/2), R₃ is 45° (π/4), R₄ is 22.5°, and so on: smaller and smaller twists.

The 2-qubit QFT

  1. H on q0
  2. Controlled-P(π/2) from q1 → q0
  3. H on q1
  4. SWAP q0 and q1
A 3-qubit QFT circuit: H, controlled phases, H, controlled phase, H, then a swap of the outer qubits
The same recipe with 3 qubits.

Gate count: n Hadamards + n(n−1)/2 controlled rotations + about n/2 swaps = O(n²). For 3 qubits: 3 H + 3 CP + 1 SWAP.

Inverse QFT (QFT⁻¹ or QFT†)

\[ \mathrm{QFT}^{-1}|k\rangle = \frac{1}{\sqrt N}\sum_{j=0}^{N-1} e^{-2\pi i\, jk/N}\,|j\rangle \]
  • Same as the QFT but with negative phase rotations.
  • Circuit: reverse the gate order of the QFT, and replace each \(R_k\) by \(R_k^\dagger\) (negative angle). Swaps go at the start (they're their own inverse).
  • \(R_k R_k^\dagger = I\), and \(\mathrm{QFT}\cdot\mathrm{QFT}^{-1} = I\).

Lab demo: build the 2-qubit QFT and verify the inverse. QFT then QFT⁻¹ on |00⟩ gives |00⟩ with 100%: a single bar of 1024 counts. Load "QFT then inverse QFT" in the circuit simulator to confirm.

Why we usually need the inverse

In Shor and QPE, the information arrives as phases on the control qubits (via phase kickback), in exactly the "Fourier basis" form. The inverse QFT converts those phases back into a plain binary number you can measure. So in practice, QFT⁻¹ is the one you'll actually use most.

Teacher Ch4 · s.12, 14–18

4.5 Finding a hidden period with the QFT

Example: the repeating sequence [1, 2, 3, 1, 2, 3, 1, 2, 3, …] has true period r = 3. In a quantum computer, we encode a period like this: a state that has equal amplitude on every r-th basis state (e.g. |0⟩, |3⟩, |6⟩, …) and zero elsewhere. Apply the QFT, and the output has sharp peaks at multiples of N/r.

\[ \text{input: } \sum_{m} |x_0 + m r\rangle \;\xrightarrow{\;\mathrm{QFT}\;}\; \text{peaks at } k \approx 0,\ \tfrac{N}{r},\ \tfrac{2N}{r},\ \dots \]

Measure, and you get one of those peaks. From the spacing between peaks (or from k/N ≈ s/r) you work out r. The offset x₀ only changes phases, not where the peaks are, which is why it doesn't matter where the pattern starts.

Try it

Period finder

4 0
Input: probability of each |x⟩ (the periodic pattern)
After the QFT: probability of measuring each |k⟩

Does the number of qubits matter? Yes.

Running the QFT on n qubits means working in a space of size N = 2ⁿ. The peaks land at multiples of N/r, so you need N to be big enough compared with r. For period r = 4:

Qubits nN = 2ⁿPeriod rN / rWhat you see
1240.5Too small: the pattern doesn't even fit once
2441Only one repeat: a single peak at 0, no information
3842Peaks at 0, 2, 4, 6
41644Peaks at 0, 4, 8, 12
53248Peaks at 0, 8, 16, 24

What if N isn't a multiple of r (like r = 3 with N = 16)? The peaks get blurry: probability leaks into neighbouring k's. More qubits make the peaks sharper and the estimate of r more accurate. That's exactly why Shor uses about 2·log₂N counting qubits. Try r = 3 above with 3 qubits and then 7 qubits.

What if we don't know the period? One last example, [1,2,3,1,2,3,1,2,3,1, 1,2,3,…], hides a bigger repeat (length 10) inside a smaller one. The QFT still finds it: it reveals every rhythm present, which is something your ears struggled with in the game.

Teacher Ch4 · s.13, s.19Lab practice · s.17–18 (QFT-3 with periods 2, 3, 4)

4.6 Bernstein–Vazirani (BV)

The problem: a black box hides a secret bit string a. When you query it with x, it returns the dot product mod 2:

\[ f(x) = a\cdot x \bmod 2 = (a_1x_1 + a_2x_2 + \dots + a_nx_n) \bmod 2 \]

It counts how many positions are 1 in both a and x, and tells you whether that count is odd.

  • Classical: n queries. Ask x = 100…0 to learn a₁, then 010…0 to learn a₂, etc. One bit per query.
  • Quantum: 1 query, no matter how long a is.

Circuit

  1. Initialise \(|0\rangle^{\otimes n}|1\rangle\) and apply H to all qubits (the last one becomes |−⟩).
  2. Apply \(U_f\): a CNOT from each input qubit where \(a_i = 1\) to the last qubit. Phase kickback gives \(\frac{1}{\sqrt{2^n}}\sum_x (-1)^{a\cdot x}|x\rangle\).
  3. Apply H again to the first n qubits and measure. The result is exactly a.

Why: H⊗ⁿ is its own inverse, and H⊗ⁿ|a⟩ is exactly \(\frac{1}{\sqrt{2^n}}\sum_x (-1)^{a\cdot x}|x\rangle\). So the last H's turn the state back into |a⟩. Interference concentrates 100% of the probability on the secret.

The lab example uses secret_number = '1011001' (7 bits), so 7 + 1 = 8 qubits and 7 classical bits. That's the "BV-8" lab. BV is an extension of Deutsch–Jozsa: both use an oracle and phase kickback.

Try it

BV-8: type a secret and recover it in one query

1–10 bits of 0/1
Classical: n queries
Quantum: 1 query
Careful: bit order again

In a Qiskit drawing for '1011001', the CNOTs come from q0, q3, q4 and q6. That's because Qiskit reads the string right-to-left (q0 = last character). Here I draw q0 = first character, so the CNOTs sit on q0, q2, q3, q6. Both are correct, just mirrored.

Teacher Ch4 · s.20–23

4.7 Quantum Phase Estimation (QPE)

The problem: you have a gate U and one of its eigenstates |ψ⟩, a special state that U doesn't change except for a phase:

\[ U|\psi\rangle = e^{2\pi i\varphi}\,|\psi\rangle, \qquad 0 \le \varphi \lt 1 \]

Find φ. (Eigen = "own" in German: |ψ⟩ is U's "own" state, and \(e^{2\pi i\varphi}\) is its eigenvalue.)

The circuit

  1. Two registers: n counting qubits in |0⟩ and the target register in |ψ⟩: \(|0\rangle^{\otimes n}\otimes|\psi\rangle\).
  2. H on every counting qubit.
  3. For each counting qubit j (0 to n−1): apply \(U^{2^j}\) to the target, controlled by qubit j. By phase kickback, counting qubit j picks up phase \(e^{2\pi i\,2^j\varphi}\).
  4. Apply the inverse QFT to the counting register.
  5. Measure: you get an integer m, and \(\varphi \approx m/2^n\).

After step 3 the counting register is exactly in "QFT form" with j replaced by \(2^n\varphi\). The inverse QFT un-does it and hands you \(2^n\varphi\) as a binary number. With n counting qubits you get φ to n binary digits.

The lab: U = P(2π·0.25), target |1⟩, so φ = 0.25. With n = 4 counting qubits the result is 0100 = 4, and 4/16 = 0.25. Exact, because 0.25 = 0.0100 in binary fits in 4 bits.

Try it

Estimate a phase

0.250

Example: finding the T gate's rotation. The T gate turns |1⟩ by 1/8 of a full circle (\(e^{i\pi/4} = e^{2\pi i\cdot 1/8}\)). Can QPE find 1/8? Step 1: an X gate turns the target into |1⟩. Step 2: H on 3 counting qubits. Step 3: apply controlled-T 1, 2 and 4 times (1/8, 2/8, 4/8 of a turn). Step 4: the inverse QFT turns those rotations into bits. Measured 001 = 1, and 1/8 = φ. Try the "T gate" button.

Accuracy and cost: when φ doesn't fit in n bits (try 1/3), the histogram spreads, and QPE returns the closest n-bit value at least ~40% of the time (exactly \(4/\pi^2 \approx 40.5\%\)). So run it several times and take the most common answer. More counting qubits give a sharper peak, but the number of controlled-U applications doubles with each extra qubit, and deep circuits suffer on noisy hardware. Classically, estimating a phase to n bits this way would take about 2ⁿ uses of U; QPE needs O(n) qubits.

Where it's used
  • Shor's algorithm: order-finding is QPE, with U = "multiply by a mod N". Its phases are s/r, so QPE reveals the period r.
  • Quantum chemistry: with U = time evolution under a molecule's Hamiltonian (energy operator), the phases are the molecule's energy levels. That's the fault-tolerant way to compute reaction energies for drugs and catalysts (Chapter 7).
  • HHL (solving linear equations) uses QPE to invert a matrix.
Teacher Ch4 · s.24–25Lab · QPE

4.8 Grover in the lab

You know how Grover works from Chapter 3. Here's how the lab actually builds it for 3 qubits with marked_state = "101".

The oracle (flip the sign of |101⟩ only)

  1. Apply X to every qubit where the target bit is 0. This maps |101⟩ to |111⟩.
  2. Apply a multi-controlled Z on |111⟩, built as H · MCX (multi-controlled X, Toffoli for 3 qubits) · H on the last qubit.
  3. Undo the X gates.

The diffuser (inversion about the mean)

H on all → X on all → (H · MCX · H on the last qubit) → X on all → H on all. Mathematically this is \(2|s\rangle\langle s| - I\), where |s⟩ is the equal superposition: "reflect about the average".

How many iterations?

\[ k = \Big\lfloor \tfrac{\pi}{4}\sqrt{8} \Big\rfloor = \lfloor 2.22 \rfloor = 2 \;\Rightarrow\; P(101) = \sin^2(5\theta) \approx 0.945 \]

So about 945 of 1024 shots land on 101. The lab prints "Optimal Grover iterations: 2" and then reverses each result string (k[::-1]) to undo Qiskit's bit order before plotting.

Plot success probability against the fraction of marked items M/N: classical random guessing is a straight line, while Grover with one iteration (\(\sin^2 3\theta\), with \(\sin^2\theta = M/N\)) reaches 100% at M/N = ¼ and drops back to 0 at ¾. With too many solutions, Grover can do worse than guessing.

Teacher Ch4 · s.26–29Lab · Grover

4.9 Shor in the lab

The full recipe:

  1. Choose a random a < N with gcd(a, N) = 1.
  2. Define the periodic function \(f(x) = a^x \bmod N\).
  3. Find the period r with a quantum circuit: Hadamards → controlled modular exponentiation (\(U_a^{2^0}, U_a^{2^1}, \dots\)) → inverse QFT → measure.
  4. Compute r from the measurement by classical post-processing (continued fractions).
  5. Factors: \(p = \gcd(a^{r/2}-1, N)\), \(q = \gcd(a^{r/2}+1, N)\).

Look closely and you'll see step 3 is exactly QPE, with U = multiplication by a mod N. That's why the lab's quantum_order_estimation is literally a QPE circuit: H on 6 counting qubits, phase rotations \(2\pi\cdot 2^q/r\), inverse QFT, measure. (It "cheats" by computing the true r classically to set the phases, since a full modular-exponentiation circuit is too big for a lab.)

Reading the lab output

Factoring N = 15 Attempt 1: using a = 2 Estimated period (r) = 4 Factors found: (3, 5) Factoring N = 55 Attempt 1: using a = 36 Estimated period (r) = 5 → r is odd, retrying... Attempt 2: using a = 39 Estimated period (r) = 11 → r is odd, retrying... Found trivial factor: 5 → Factors found: (5, 11)
  • For 15 with a = 2: \(2^4 = 16 \equiv 1\), so r = 4. \(2^2 = 4\); gcd(3, 15) = 3, gcd(5, 15) = 5.
  • For 55 with a = 36: the true order is 5 (odd), so it retries. For a = 39 the true order is 10, but 6 counting qubits estimated 11. Estimates can be wrong, and that's one reason Shor is a repeat-until-success algorithm. In the end, a random a happened to share a factor with 55 (the "lucky gcd" step), giving 5 × 11.

Compare the number of operations against the number of digits: the classical curve shoots up towards 10³⁰ for 300-digit numbers, while Shor's stays low and nearly flat. That gap is the exponential speed-up.

Teacher Ch4 · s.30–32Lab · Shor

4.10 Comparison and lab summary

AlgorithmProblemClassicalQuantumOutput / insight
QFTChange basis of quantum amplitudesFFT: O(n·2ⁿ)O(n²) = O((log N)²) gatesBasis change; reveals periods
BVFind hidden bit string an queries1 queryReveals a
QPEEstimate eigenphase φ in \(U|\psi\rangle = e^{2\pi i\varphi}|\psi\rangle\)~2ⁿ applications for n bitsO(n) counting qubitsControlled-U + inverse QFT
GroverSearch unsorted dataO(N)O(√N), quadraticTarget found with high probability
ShorFactor N via period findingSub-exponential in log NPolynomial in log N, exponential speed-upPrime factors of N

Lab summary

  • Lab 1, QFT-3: build a 3-qubit QFT; create hidden periods 2, 3, 4; simulate; plot histograms (use the period finder above to predict them).
  • Lab 2, BV-8: 7-bit secret + 1 ancilla; let the user type the secret; check the output equals it.
  • Lab 3, Grover on 3 qubits: oracle, diffuser, 2 iterations, histogram.
  • Lab 4, Shor's factoring: choose a, find r with QPE, compute factors of a user-supplied N.
  • Bonus: run each on FakePerth (a noisy copy of IBM's 7-qubit Perth chip) vs. the ideal simulator and compare fidelity: how close the noisy histogram is to the ideal one. Expect bars to "leak" into wrong answers on the fake device. That's Chapter 5 (errors and noise) knocking.
Teacher Ch4 · s.16–18, 22–23, 25, 28–29, 32–34

Chapter 4 in ten lines

  • The FT turns "when" into "which rhythms"; the DFT formula is \(y_k = \frac{1}{\sqrt N}\sum_j x_j e^{2\pi ijk/N}\).
  • QFT does the same to amplitudes: \(|j\rangle \to \frac{1}{\sqrt N}\sum_k e^{2\pi ijk/N}|k\rangle\).
  • On 1 qubit, QFT = H. Circuit: H + controlled-Rk + swaps, O(n²) gates.
  • Inverse QFT: reverse order, negative angles. QFT·QFT⁻¹ = I.
  • Periodic input → peaks at multiples of N/r. More qubits = sharper peaks.
  • BV: f(x) = a·x mod 2; finds a in 1 query (classical: n).
  • QPE: H, controlled-U^{2^j}, inverse QFT; φ ≈ m/2ⁿ.
  • Grover lab: X-sandwiched multi-controlled Z oracle; diffuser = reflect about mean; ⌊π/4·√N⌋ iterations.
  • Shor's quantum part is QPE on "multiply by a mod N".
  • Test on FakePerth to see noise reduce fidelity.

Check yourself: Chapter 4

Chapter 5

Quantum Errors and Noise

Teacher Ch5 · s.1–30Labs: Error, QEM (Mitiq)

Every algorithm so far assumed perfect qubits. Real ones aren't. Heat, vibration, stray fields and imperfect pulses nudge them all the time, and Chapter 1 already warned that this noise is the biggest thing standing between today's chips and Shor on real keys. This chapter is about fighting back. We start with how ordinary computers deal with errors, see why qubits make that much harder, and then meet the three answers: correct errors, mitigate them, or suppress them before they happen.

5.1 Errors before qubits: classical error correction

Classical bits go wrong too: electrical noise, imperfect circuits, a signal that fades on its way down a cable. The errors come in three shapes.

Three 8-bit words sent and received: one with a single flipped bit, one with two scattered flips, and one with a run of neighbouring flips
A single-bit error, a multiple-bit error, and a burst error, where neighbouring bits go wrong together.

The first question is always: how do you even know something went wrong? You can't compare against the original, because the receiver never had it. The answer is to send a little extra, called redundancy, and check that it still agrees with itself. The slides show three ways.

The 3-repetition code

Send every bit three times: 0 becomes 000 and 1 becomes 111. The receiver takes a majority vote. One flipped copy is outvoted by the other two, so the error is detected and corrected. Two flips win the vote, and the answer comes out wrong.

CaseOriginalSentReceivedMajorityResult
No error000000000
One error111111011 (fixed)
One error000001000 (fixed)
Two errors111100100 (wrong)

If each copy flips independently with probability p, the vote fails only when two or three copies flip:

\[ P_{\text{fail}} = 3p^2(1-p) + p^3 = 3p^2 - 2p^3 \]

With p = 0.1, one bit alone is wrong 10% of the time, but the vote is wrong only 2.8% of the time. The code helps only while p is below 0.5. Past that, the copies are more likely wrong than right, and voting makes things worse.

Try it

Majority vote under noise

10%

Parity check

Add one parity bit so the total number of 1s is always even. 100011 has three 1s, which is odd, so append 1. 110011 has four, so append 0. The receiver recounts. An odd total means something flipped, so it rejects the data and asks again. A parity bit detects a single error but can't say which bit it was, so it can't correct it. Two flips cancel out and go unnoticed.

Sender computes a parity bit for 100011, sends 1000111; the receiver recomputes parity, accepts even data and rejects odd data
The sender adds a parity bit; the receiver recomputes it and accepts or rejects the data.

Hamming codes

Richard Hamming's trick is to use several parity bits, each checking a different, overlapping group of positions. Put them at positions 1, 2 and 4, the powers of 2. When one bit flips, the pattern of failed checks, called the syndrome, spells out the bad position in binary. Then you flip it back. Hamming(7,4) protects 4 data bits with only 3 extra bits, where repetition would need 8.

Try it

Hamming(7,4): find the flipped bit

Set the 4 data bits, then tap any received bit to flip it, the way noise would. The receiver's three checks point at the bad position.

Data
Received

Try flipping two bits. The syndrome still points somewhere, but at the wrong place, and the "fix" adds a third error. Every code has a limit on how many errors it can handle.

Real world

Hamming worked at Bell Labs in the 1940s and was fed up with weekend computer jobs crashing on a single bad bit. His codes, published in 1950, still protect the memory in most servers today: "ECC RAM" fixes single-bit errors silently. QR codes and CDs use stronger cousins, which is why a scratched disc still plays.

Teacher Ch5 · s.4–8

5.2 Why quantum errors are harder

Qubits do their job through superposition and entanglement. Those are exactly the properties that make them sensitive to their environment, so errors aren't a rare accident. They are constant. To build reliable machines we have to detect, correct, mitigate and suppress them. Three things from Chapter 2 make that hard:

Classical errorsQuantum errors
Bits are discrete: 0 or 1, so an error is a clean flipQubits are continuous complex states, so an error can be any tiny drift of the arrow
Bits are easy to copy, so repetition is freeThe no-cloning theorem forbids copying an unknown state
You can look at a bit directly to check itMeasurement collapses the state, so looking destroys what you're protecting
Top row: a prepared state 01 measured with noise, then mitigated so 01 dominates again. Bottom row: the same noisy measurement, then corrected back to 01
The goal in a picture: noise spreads the answer across wrong outcomes, and we want the right bar back.
Key idea

Quantum error correction can't copy the qubit and can't look at it. It works anyway by entangling the qubit with others and measuring only parities, questions like "do these two agree?". Those answers reveal the error without revealing the data. You'll see how in 5.7.

Teacher Ch5 · s.9, s.14

5.3 Types of quantum noise

Picture the qubit as an arrow on the Bloch sphere from Chapter 2. Each kind of noise does something different to that arrow.

Error typeWhat it doesOn the Bloch sphere
Bit flip (X error)Swaps |0⟩ ↔ |1⟩Turns the arrow upside down about the x-axis
Phase flip (Z error)Multiplies the |1⟩ part by −1Turns the arrow half way round the vertical axis
Bit-phase flip (Y error)Both at onceDamages both the values and the phase
DepolarizingWith some chance, replaces the state with a completely random oneShrinks the arrow towards the centre
Amplitude dampingEnergy leaks out: |1⟩ relaxes to |0⟩Pulls the arrow towards the north pole, |0⟩
Phase dampingPhase information leaks out, but no energy is lostSquashes the arrow onto the vertical axis

A shrunken arrow is a qubit that's partly random. The length of the arrow is how much "quantumness" is left: 1 means a pure state, and 0 is a fair coin with no phase at all. Try each channel on different starting states, and notice that some errors can't touch some states.

Try it

Noise channels on the Bloch sphere

0.30
Start in
Think of it like…

A compass needle in a noisy room. A bit flip is someone flipping the compass over. A phase flip spins it half a turn around its pin. Depolarizing is someone shaking the box so the needle could be pointing anywhere. Amplitude damping is the needle slowly settling towards magnetic north. Phase damping blurs which way round it was pointing, but not whether it points up or down.

Teacher Ch5 · s.10Visualizer: gui.quantumcodes.io

5.4 Coherence, decoherence, T₁ and T₂

Coherence is a qubit's ability to stay in superposition. Every algorithm depends on it. Decoherence is the environment (heat, vibration, radiation, magnetic fields) leaking into the qubit and destroying that quantum information. Hardware quotes two clocks for it:

ParameterMeaningMatches
T₁, relaxation timeHow long before an excited |1⟩ decays to |0⟩Amplitude damping
T₂, dephasing timeHow long before the superposition's phase is lostPhase damping (plus T₁ decay)
\[ P_{1}(t) = e^{-t/T_1}, \qquad \text{coherence}(t) \propto e^{-t/T_2} \]

After one T₁, a qubit that started in |1⟩ is still there only about 37% of the time. T₂ can never be longer than 2T₁, because losing energy also destroys the phase.

On today's hardware both are only tens to hundreds of microseconds. That is the real limit on circuit depth: every gate takes time, and the whole algorithm has to finish before the qubits forget. It's why the deep circuits in Shor are out of reach and short ones like VQE are not.

Teacher Ch5 · s.11

5.5 Detecting quantum errors and noise

Before you can fight noise you have to measure it. The slides list four techniques:

  • Fidelity: how close an actual output state or distribution is to the ideal, from 0 to 1.
  • Randomized benchmarking: run long random sequences of gates that should multiply out to "do nothing", and see how fast the result decays. That gives the average gate fidelity, without being fooled by state preparation or readout errors.
  • Quantum process tomography: feed in many known states, measure in many bases, and reconstruct the whole operation a gate actually performs, imperfections included. It's thorough but expensive, so it's only practical for one or two qubits.
  • Hardware error reports: providers publish calibration data for every qubit and connection, refreshed many times a day.
IBM Quantum dashboard for ibm_pittsburgh, a 156-qubit Heron r3 processor: 2-qubit error 1.55E-3, readout error 4.03E-3, T1 300 microseconds, T2 324 microseconds, with a map of the qubit lattice
An IBM hardware report: ibm_pittsburgh, a 156-qubit Heron r3 chip, and its calibration map.

Reading the report

From this dashboard: 2-qubit (CZ) error ≈ 1.55 × 10⁻³, single-qubit (SX) error ≈ 1.8 × 10⁻⁴, readout error ≈ 4.0 × 10⁻³, T₁ ≈ 300 µs, T₂ ≈ 324 µs. Two-qubit gates are almost ten times worse than one-qubit gates, which is why transpilers (Chapter 3) work so hard to cut CNOTs.

A quick rule of thumb: if errors are independent, a circuit succeeds roughly when every operation does, so multiply the success chances.

\[ P_{\text{success}} \approx \prod_i (1-\varepsilon_i) \]

A circuit with 100 CZs, 200 SX gates and 5 readouts on this chip: 0.99845¹⁰⁰ ≈ 0.857, times 0.99982²⁰⁰ ≈ 0.965, times 0.99597⁵ ≈ 0.980, which is about 0.81. One run in five is spoiled before you even start, and doubling the CZ count drops it to about 0.70.

Teacher Ch5 · s.12–13

5.6 Lab: watching noise in Qiskit

The first lab notebook (Error.ipynb) adds noise to a small circuit on purpose and compares the results. The steps:

  1. Build the circuit: put q0 in |1⟩, copy it into q1 and q2 with two CNOTs (the repetition code), then decode with two CNOTs and a Toffoli that flips q0 back if q1 and q2 both disagree with it.
  2. Simulate it ideally (no error).
  3. Simulate it with a bit-flip noise model, pauli_error([("X", p), ("I", 1 − p)]), with p = 0.30.
  4. Compare the two histograms.
  5. Repeat at transpiler optimization levels 0, 1, 2 and 3.
qc = QuantumCircuit(3, 1) qc.x(0) # logical |1⟩ qc.cx(0, 1); qc.cx(0, 2) # encode: |111⟩ # ... noise happens here in a real device ... qc.cx(0, 1); qc.cx(0, 2) # decode qc.ccx(1, 2, 0) # majority vote onto q0 qc.measure(0, 0)

The results: ideal gives 1 in all 1,024 shots. With noise, about 70% 1 and 30% 0 (e.g. 724 vs 300). Optimization levels 0–3 give 748, 718, 682 and 715 ones: no real pattern, just shot noise.

Careful: why didn't the code help?

Look at where the noise model attaches: add_quantum_error(bit_flip_error, ["x", "id"], [0]). That puts the 30% flip on the X gate on q0, before encoding. A wrong input is copied faithfully into all three qubits, so the vote agrees on the wrong answer, and the failure rate stays at p = 0.3. A code only protects against errors that happen after encoding. Move the noise onto the encoded qubits and the failure rate drops to 3p² − 2p³ ≈ 0.22 at p = 0.3, or to 0.028 at p = 0.1. The optimization level can't help either, because the noisy X gate is in every version of the circuit.

Teacher Ch5 · s.15Lab: Error.ipynb

5.7 Quantum error correction (QEC)

Goal: protect quantum information by spreading one logical qubit across many physical qubits.

ConceptWhat it means
RedundancyEncode the logical qubit using several physical qubits
StabilizersParity checks, measured through helper qubits, that reveal errors without revealing the data. The results are the syndrome.
Fault toleranceCircuits keep working correctly even when the correction steps themselves have small errors

The 3-qubit bit-flip code

Two CNOTs entangle the qubit with two fresh |0⟩s. Nothing is copied, so no-cloning is safe:

\[ \alpha|0\rangle + \beta|1\rangle \;\longrightarrow\; \alpha|000\rangle + \beta|111\rangle \]

Now measure two parities with ancilla qubits: does q0 agree with q1 (\(Z_0Z_1\)), and does q1 agree with q2 (\(Z_1Z_2\))? Both branches, |000⟩ and |111⟩, give the same parity answers, so α and β are never disturbed. Only the error shows up:

q0 = q1?q1 = q2?DiagnosisFix
yesyesNo errorNothing
noyesq0 flippedX on q0
nonoq1 flippedX on q1
yesnoq2 flippedX on q2

Phase flips get the same treatment after a layer of Hadamards, because H turns Z errors into X errors. Peter Shor combined the two in 1995 to make the first code that handles any single-qubit error, using 9 physical qubits. Modern chips aim for the surface code, a grid of qubits with parity checks all over it. This is where Chapter 1's "about 1,000 physical qubits per logical qubit" comes from.

A loop between an agent, a quantum memory and classical control: the agent reads code structure and chooses actions, with a reward signal
Decoding as a loop: something reads the syndrome, decides on a fix, and acts. Some research uses machine-learning agents for this.
Real world

There's a threshold: if physical errors are rare enough, making the code bigger makes the logical qubit better. Above it, extra qubits only add more places to fail. Google's Willow chip (2024) was the first to show the logical error rate falling as the surface code grew, which is the "below threshold" line from Chapter 1's NISQ chart.

Teacher Ch5 · s.16

5.8 Quantum error mitigation (QEM)

Error mitigation is a collection of tricks that reduce the effect of noise on your results, without the extra qubits that full correction needs. It doesn't fix the qubits. It runs the noisy circuit cleverly, many times, and post-processes the numbers to estimate what a perfect machine would have said. That makes it the practical choice for today's NISQ devices. The slides cover four techniques: zero-noise extrapolation, readout-error mitigation, probabilistic error cancellation and Pauli twirling.

Zero-noise extrapolation (ZNE)

You can't turn noise down, but you can turn it up on purpose. Run the circuit at noise levels λ = 1, 1.5, 2, 2.5, 3, measure your answer each time, fit a curve through the points, and follow it back to λ = 0: the zero-noise answer that no machine can run.

Mitiq ZNE workflow: the user's program becomes noise-scaled circuits, which run on hardware; the noisy results are combined into an error-mitigated expectation value
Mitiq's ZNE workflow: generate noise-scaled circuits, run them, then infer the zero-noise value.

How do you scale noise without touching the hardware? Unitary folding. Replace a gate U with U U† U. Mathematically that's still U, because U†U = I, but the chip now runs three gates, so roughly three times the noise. Fold the whole circuit (global folding), single gates (local folding), or insert identities (identity folding). Folding only some gates gives in-between factors like 1.5.

An original circuit U next to three folded versions: local unitary folding, global unitary folding U U-dagger U, and identity folding
Folding: the logic stays the same while the gate count, and so the noise, goes up.
\[ U \;\to\; U\,(U^\dagger U)^k, \qquad \lambda = 2k + 1 \]

This lab mirrors the second notebook (QEM.ipynb): 10 X gates on one qubit, which multiply out to "do nothing", so the ideal result is P(0) = 1. Each gate has depolarizing noise.

Try it

Zero-noise extrapolation

2.0%

The notebook's run with 2% noise got P(0) = 0.913 unmitigated and 0.961 after linear ZNE with scale factors 1 to 3. That's much closer to 1, but not all the way: the real decay is a curve, and a straight line underestimates it. Try the exponential fit, then try Richardson with shot noise on.

Careful: more is not better

A higher-degree fit passes through every point, including the shot noise. Extrapolating that wiggly curve back to λ = 0 can land further from the truth than a straight line. ZNE trades bias (a too-simple curve) against variance (amplified noise), and the cost of reducing either is more shots.

The other mitigation techniques

  • Readout-error mitigation: first prepare each basis state and record how often it's misread, to build a "confusion matrix". Then undo that matrix on your real results. It's cheap, and it fixes the 0.4% readout errors in the report above.
  • Probabilistic error cancellation (PEC): characterise the noise, then write the ideal gate as a weighted mix of noisy operations, some with negative weights. Randomly sample circuits from that mix and recombine the results with the weights. On average the noise cancels. The price is that the number of runs grows exponentially with circuit size.
  • Pauli twirling: sandwich gates between random Pauli gates that cancel out logically. That turns messy, coherent errors into simple random Pauli flips, which the other methods handle much better.
Headphone speaker waves plus ambient noise waves cancel to a flat line
PEC, as the slides put it: like noise-cancelling headphones adding the opposite wave.

Mitigation versus correction

Three panels: quantum error correction monitors and detects errors; catch and reverse anticipates them from a tell signal; error mitigation doesn't monitor and leaves errors undetected
Correction watches and fixes errors as they happen. Mitigation never sees them, and cleans up the statistics afterwards.
Error correction (QEC)Error mitigation (QEM)
Extra qubitsMany (hundreds per logical qubit)None
Extra costQubits and fast classical decodingMore circuit runs and post-processing
What you getA protected qubit you can keep computing withA better estimate of an average (an expectation value)
WhenThe long-term route to large algorithms like ShorToday, on NISQ hardware
Teacher Ch5 · s.17–23Lab: QEM.ipynb

5.9 Error suppression and dynamical decoupling

Error suppression works before errors happen. It builds resilience into the hardware and the operations themselves, with better-shaped control pulses and circuit designs that avoid trouble. The slides compare it to compressing a file: the information is all still there, but packed into a form that's less exposed.

The classic example is dynamical decoupling (DD). Qubits that sit idle while others work still drift, because of slow, unwanted phase from the environment. DD fills those idle windows with pulse pairs such as X then X, which multiply to the identity. Halfway through, the X turns the drift around, so the second half undoes the first. Sequences go from a plain X–X echo to XY4 (X–Y–X–Y) and XY8.

A 4-qubit circuit timeline with idle windows filled by DD sequences, and a table of sequences: CP, CPMG, XY4, XY8
Digital dynamical decoupling: idle windows (grey) are filled with pulse sequences that multiply to I.
Think of it like…

Runners on a track who have drifted apart because some are faster. At the whistle everyone turns round and runs back. The fast ones have further to go, and everyone reaches the start line together. The X pulse is the whistle.

Where it's used

The same "echo" trick, invented by Erwin Hahn in 1950, is how MRI scanners get sharp images: a refocusing pulse reverses the dephasing of hydrogen spins in your body. IBM's runtime can insert DD sequences into your circuits automatically.

Teacher Ch5 · s.24–26

5.10 Putting it together, and the Mitiq lab

Noise is the central challenge in building large quantum computers, and no single tool beats it. We combine all four:

ApproachRoleExample
Error correction (QEC)Long-term, scalableSurface code, logical qubits
Error mitigation (QEM)Short-term, practicalZNE, PEC, readout mitigation
Error suppressionHardware-level preventionDynamical decoupling, better pulses
Benchmarking and tomographyMeasuring the problemRandomized benchmarking, hardware reports

The Mitiq lab

Mitiq is an open-source Python library for error mitigation from the Unitary Foundation. It implements ZNE, PEC and DDD, and it works with Qiskit, Cirq and Braket. The notebook QEM.ipynb:

  1. Build the circuit: 10 X gates on one qubit, then measure. The ideal answer is 0 every time.
  2. Simulate it ideally: {'0': 1024}.
  3. Add depolarizing noise (initialized_depolarizing_noise(noise_level=0.02)) and run it: P(0) ≈ 0.913.
  4. Run ZNE with LinearFactory(scale_factors=[1.0, 1.5, 2.0, 2.5, 3.0]): P(0) ≈ 0.961.
  5. Plot ideal, noisy and mitigated side by side.
from mitiq import zne from mitiq.zne.inference import LinearFactory factory = LinearFactory(scale_factors=[1.0, 1.5, 2.0, 2.5, 3.0]) mitigated_p0 = zne.execute_with_zne(circuit, executor, factory=factory) # executor(circuit) runs the circuit and returns P(0)

The key design choice is the executor: a function you write that takes a circuit and returns one number, here P(0). Mitiq folds the circuit, calls your executor at each scale factor, and extrapolates. The notebook can switch to a real IBM back-end with USE_REAL_HARDWARE = True, and then the noise is the chip's own.

Teacher Ch5 · s.27–29Lab: QEM.ipynb

Chapter 5 in ten lines

  • Classical codes add redundancy: repetition votes, parity detects, Hamming locates the bad bit with a syndrome.
  • 3-copy repetition fails with \(3p^2-2p^3\), which helps only while p < 0.5.
  • Qubits are harder: errors are continuous, states can't be copied, and looking collapses them.
  • Noise types: bit flip X, phase flip Z, Y, depolarizing (shrinks), amplitude damping (falls to |0⟩), phase damping (loses phase).
  • T₁ = energy relaxation, T₂ = dephasing; tens to hundreds of µs, which limits circuit depth.
  • Measure noise with fidelity, randomized benchmarking, tomography and hardware reports; success ≈ \(\prod(1-\varepsilon_i)\).
  • QEC: one logical qubit in many physical ones; parity checks (stabilizers) give a syndrome without touching the data.
  • QEM: no extra qubits. ZNE folds U → UU†U to scale noise, then extrapolates to zero.
  • Suppression prevents errors: dynamical decoupling echoes away drift in idle windows.
  • Combine all four; Mitiq does ZNE, PEC and DDD on Qiskit circuits.

Check yourself: Chapter 5

Final

Final Exam

A long paper on its own page, covering every chapter. No feedback until you hand it in, then a score per section and a full review.

60Questions
134Marks
120Minutes

Open the final exam

Cheat sheet

Formula sheet and glossary

WhatFormula
Qubit state\(|\psi\rangle=\alpha|0\rangle+\beta|1\rangle,\ |\alpha|^2+|\beta|^2=1\)
Born rule\(P(0)=|\alpha|^2,\ P(1)=|\beta|^2\)
Bloch form\(\cos\frac\theta2|0\rangle+e^{i\varphi}\sin\frac\theta2|1\rangle\)
Euler\(e^{i\theta}=\cos\theta+i\sin\theta\)
Unitary\(U^\dagger U=I\)
Hadamard\(H|0\rangle=|+\rangle,\ H|1\rangle=|-\rangle,\ H^2=I\)
All inputs at once\(H^{\otimes n}|0\rangle^{\otimes n}=\frac{1}{\sqrt{2^n}}\sum_x|x\rangle\)
Bell state\(|\Phi^+\rangle=\frac{1}{\sqrt2}(|00\rangle+|11\rangle)\)
Interference\(P=|\psi_1+\psi_2|^2\)
Phase kickback\(U_f|x\rangle|-\rangle=(-1)^{f(x)}|x\rangle|-\rangle\)
Deutsch–Jozsa\(\text{amp}(0^n)=\frac{1}{2^n}\sum_x(-1)^{f(x)}\)
Grover\(k\approx\frac\pi4\sqrt N,\ P=\sin^2((2k+1)\theta),\ \sin\theta=\frac{1}{\sqrt N}\)
Shor\(a^r\equiv1 \pmod N\); factors \(\gcd(a^{r/2}\pm1,N)\)
DFT\(y_k=\frac{1}{\sqrt N}\sum_j x_je^{2\pi ijk/N}\)
QFT / inverse\(|j\rangle\to\frac{1}{\sqrt N}\sum_k e^{\pm2\pi ijk/N}|k\rangle,\ N=2^n\)
Controlled rotation\(R_m=\mathrm{diag}(1,e^{2\pi i/2^m})\)
Bernstein–Vazirani\(f(x)=a\cdot x \bmod 2\)
QPE\(U|\psi\rangle=e^{2\pi i\varphi}|\psi\rangle,\ \varphi\approx m/2^n\)
3-copy repetition code\(P_{\text{fail}}=3p^2-2p^3\) (helps only if \(p<\tfrac12\))
Bit-flip code\(\alpha|0\rangle+\beta|1\rangle\to\alpha|000\rangle+\beta|111\rangle\); checks \(Z_0Z_1,\ Z_1Z_2\)
T₁ and T₂ decay\(P_1(t)=e^{-t/T_1},\ \text{coherence}\propto e^{-t/T_2},\ T_2\le2T_1\)
Circuit success\(P_{\text{success}}\approx\prod_i(1-\varepsilon_i)\)
ZNE folding\(U\to U(U^\dagger U)^k,\ \lambda=2k+1\); extrapolate to \(\lambda=0\)
Noise on the Bloch vectordepolarizing \(\vec r\to(1-p)\vec r\); \(P(0)=\tfrac{1+z}{2}\)

Glossary

AmplitudeThe complex number in front of a basis state; its squared size is a probability.
Amplitude dampingEnergy loss: |1⟩ relaxes to |0⟩. Measured by T₁.
AncillaA helper qubit (e.g. the |−⟩ qubit in BV and Deutsch–Jozsa).
Basis state|0⟩, |1⟩ for one qubit; |00⟩…|11⟩ for two; the "plain" states.
Bit flip / phase flipAn unwanted X (swaps |0⟩ and |1⟩) or Z (puts a minus sign on |1⟩) error.
CollapseAfter measurement, the state becomes the outcome you saw.
DecoherenceThe environment leaking into qubits and destroying superposition.
Depolarizing noiseWith some chance, the state is replaced by a random one; shrinks the Bloch arrow.
Dynamical decouplingPulse pairs in idle windows that echo away slow drift (error suppression).
EigenstateA state that a gate only multiplies by a phase.
Error mitigation (QEM)Post-processing tricks (ZNE, PEC, readout correction) that improve noisy results without extra qubits.
FidelityHow close an actual result or state is to the ideal (1 = perfect).
gcdGreatest common divisor; fast with Euclid's algorithm.
Logical vs physical qubitAn error-corrected qubit built from many noisy hardware qubits.
MitiqOpen-source Python library for error mitigation (ZNE, PEC, DDD).
NISQNoisy Intermediate-Scale Quantum: today's 50–1,000 qubit devices.
OracleA black-box gate that computes a function you're trying to learn about.
PECProbabilistic error cancellation: sample noisy circuits with signed weights so the noise averages out.
PhaseThe angle of an amplitude's arrow; invisible in one measurement, crucial for interference.
Phase dampingLoss of phase without energy loss; measured by T₂.
QASMA text language for quantum circuits (OpenQASM).
Randomized benchmarkingLong random gate sequences that should do nothing; their decay gives average gate fidelity.
Readout errorMeasuring 0 when the qubit was 1, or the reverse.
ShotsHow many times a circuit is run to build a histogram.
Stabilizer / syndromeParity checks that reveal an error without revealing the data; their results are the syndrome.
T₁ / T₂Relaxation time (|1⟩ → |0⟩) and dephasing time (phase lost).
TranspileRewrite a circuit into a specific chip's native gates and wiring.
UnitaryA reversible, probability-preserving operation; all quantum gates are unitary.
ZNEZero-noise extrapolation: run at boosted noise levels, then extrapolate back to zero noise.

Course materials

The original files this page was built from. Tap one to download it.

Lecture decks (Ms. Heng Sovanmonynuth)

Lab notebooks

Simulations on this page run a small, exact quantum state simulator in your browser. Figures are cropped from the course slides. Facts in the "Real world" boxes are from general knowledge, not the slides, so check them before quoting them in an assignment.