Programming Quantum Computers
From circuits in code to jobs on real hardware.
Between qc.h(0) in a notebook and a microwave pulse inside a dilution refrigerator sit a compiler, a coupling map and thousands of repetitions. This lesson follows a program all the way down, and teaches you to read what comes back.
What you’ll learn
- Write small circuits as Qiskit- or Cirq-style code and translate between code and circuit diagrams.
- Estimate Pauli expectation values from shot counts with error bars, including basis changes for and .
- Explain transpilation: decomposition into a native gate set, layout and routing on a coupling map, optimization and scheduling.
- Compare statevector, sampling, noisy and structured simulators with hardware execution, and estimate simulation memory.
Circuits as code
Quantum SDKs such as Qiskit (IBM) and Cirq (Google) share one abstraction: a circuit object on numbered qubits and classical bits, to which you append gates. Here is a three-qubit GHZ state in Qiskit-style Python:
from qiskit import QuantumCircuit
qc = QuantumCircuit(3, 3) # 3 qubits, 3 classical bits
qc.h(0) # |+> on qubit 0
qc.cx(0, 1) # CNOT, control 0, target 1
qc.cx(1, 2) # CNOT, control 1, target 2
qc.measure([0, 1, 2], [0, 1, 2])
print(qc.draw())Each method call appends one instruction. Nothing runs until you hand the circuit to a simulator or a backend.
import cirq
q0, q1 = cirq.LineQubit.range(2)
circuit = cirq.Circuit([
cirq.H(q0),
cirq.CNOT(q0, q1),
cirq.measure(q0, q1, key="m"),
])
result = cirq.Simulator().run(circuit, repetitions=1000)
print(result.histogram(key="m")) # integer keys: 0 = 00, 3 = 11A Bell pair in Cirq: different syntax, identical abstraction.
Shots, counts and expectation values
A backend returns counts: how often each bit string occurred in shots. Everything else is estimated from them. For a -type Pauli string such as , every shot yields an eigenvalue : the parity of the measured bits.
Measuring a Pauli string in its eigenbasis returns on shot ; for -type strings . The sample mean is unbiased:
Because , the single-shot variance is fixed by the mean:
Shots are independent, so the standard error is
For a guarantee rather than a typical error, Hoeffding's inequality gives , so accuracy with confidence needs
Hardware measures only in the computational basis. To measure , first rotate its eigenbasis onto 's with ; for , apply and then . For the Bell state , rotating both qubits and reading parities gives , and . Check the surprising sign:
You need of a state with to a standard error of . How many shots?
Show the answer
10000 shots
gives . Every extra decimal digit of precision costs a factor of 100 in shots.
from qiskit import QuantumCircuit
from qiskit.quantum_info import SparsePauliOp
from qiskit.primitives import StatevectorEstimator
bell = QuantumCircuit(2)
bell.h(0)
bell.cx(0, 1)
H = SparsePauliOp.from_list([("XX", 1.0), ("YY", 1.0), ("ZZ", 1.0)])
job = StatevectorEstimator().run([(bell, H)])
print(job.result()[0].data.evs) # exact value: 1 - 1 + 1 = 1An Estimator primitive takes (circuit, observable) pairs and returns expectation values. A hardware Estimator performs the basis changes, groups compatible terms and averages shots for you.
Transpilation: native gates and coupling maps
A device exposes a native gate set and a coupling map: a graph whose edges are the qubit pairs that can share a two-qubit gate. The transpiler runs a pipeline of passes:
- Unroll high-level gates into the basis, e.g. or on superconducting chips; trapped ions typically offer arbitrary one-qubit rotations and a Mølmer–Sørensen -type gate.
- Layout: assign logical qubits to physical ones, ideally so that interacting pairs are neighbors.
- Routing: insert SWAPs where they are not.
- Optimize: cancel inverse pairs, merge rotations, resynthesize blocks.
- Schedule: assign start times, respecting gate durations.
With and , where , multiply out:
Multiplying by on the left scales the rows by :
So, up to an unobservable global phase, one physical pulse and two virtual rotations (which cost no time) make a Hadamard. In the same way every one-qubit unitary needs at most two pulses: .
Two-qubit gates are where the hardware bites. A SWAP costs three CNOTs; on a line , a CNOT between the end qubits needs either a SWAP or the four-CNOT bridge (operators act right to left), which leaves qubit 1 untouched.
from qiskit import QuantumCircuit, transpile
from qiskit.transpiler import CouplingMap
qc = QuantumCircuit(3)
qc.h([0, 1, 2])
qc.rzz(0.4, 0, 1)
qc.rzz(0.4, 1, 2)
qc.rzz(0.4, 0, 2) # a triangle of interactions
qc.rx(0.6, [0, 1, 2])
line = CouplingMap.from_line(3) # physical edges 0-1 and 1-2 only
tqc = transpile(qc, coupling_map=line,
basis_gates=["rz", "sx", "x", "cx"],
optimization_level=3, seed_transpiler=1)
print(tqc.count_ops())Compare count_ops() with and without coupling_map, or across seeds. Layout, routing and optimization are heuristics: the output is not unique, and rarely provably optimal.
Your circuit has two-qubit gates between all three pairs of qubits 0, 1, 2. The coupling map is a line . Can a well-chosen initial layout alone make every two-qubit gate act on neighboring physical qubits?
- Yes: map logical qubit 1 to the middle qubit
- Yes, provided the gates are reordered
- No: a triangle is not a subgraph of a path, so some pair is always non-adjacent and the compiler must add SWAPs or bridges, or resynthesize around the missing edge
- No, because CNOTs can never act on neighboring qubits
Show the answer
C. No: a triangle is not a subgraph of a path, so some pair is always non-adjacent and the compiler must add SWAPs or bridges, or resynthesize around the missing edge
A layout needing no extra gates exists exactly when the interaction graph embeds in the coupling graph. Here the interaction graph is a triangle and a path contains no triangle, so the two logical qubits placed at the ends interact across a missing edge.
Simulators, hardware, and going deeper
Before spending hardware time you simulate, and different simulators answer different questions:
| Simulator | Represents | Cost | Use it for |
|---|---|---|---|
| Statevector | All amplitudes | bytes (complex128) | Exact amplitudes and expectation values: about 30 qubits on a workstation, mid-40s on supercomputers |
| Sampling | A statevector plus random draws | Same, plus samples | Realistic counts with shot noise |
| Noisy | A density matrix ( entries) or many sampled trajectories | bytes for the density matrix | Predicting the effect of noise models, on roughly half as many qubits |
| Stabilizer, tensor network | Clifford tableaux; low-entanglement tensor networks | Polynomial for Clifford circuits; set by entanglement for tensor networks | Large Clifford circuits (error-correction studies); shallow or weakly entangled circuits |
How much memory does a 30-qubit statevector need at 16 bytes per complex amplitude? Answer in GiB ( bytes).
Show the answer
16 GiB
bytes GiB. Each extra qubit doubles it: 40 qubits need 16 TiB and 50 qubits 16 PiB. This exponential wall is why generic, highly entangled circuits beyond about 50 qubits cannot be simulated directly.
On hardware, a job waits in a queue, is compiled against the device's current calibration, and returns counts. Expect three differences from an ideal simulator:
- gate errors and decoherence pull outputs toward noise;
- readout errors, often at the percent level, misreport as or vice versa;
- drift: calibrations change over hours, so results vary between runs.
Common remedies are readout-error correction, dynamical decoupling during idle periods, and error-mitigation techniques such as zero-noise extrapolation. Modern stacks also run dynamic circuits: mid-circuit measurement with classical feed-forward, expressed in OpenQASM 3.
Key takeaways
- SDKs build circuits as code; check the bit-ordering convention before reading counts.
- Expectation values come from parities of shots, with standard error ; and need basis changes first.
- Transpilers unroll to native gates, lay out and route on the coupling map (a SWAP costs three CNOTs), optimize and schedule. The results are heuristic, not unique.
- Statevector simulation costs bytes; hardware adds gate, readout and drift errors on top of shot noise.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
A two-qubit circuit returns counts in 1000 shots (qubit 0 on the left). What is the estimate of ?
Show the answer
B.
Each shot contributes : even parity (, ) gives , odd parity gives . So , with standard error .
Why do compilers for superconducting qubits like to move work into rotations?
- rotations commute with every other gate
- gates are the only gates that can run in parallel
- rotations do not change measurement probabilities, so they can be deleted
- is implemented virtually, as a phase shift of all later pulses, so it takes no time and adds essentially no error
Show the answer
D. is implemented virtually, as a phase shift of all later pulses, so it takes no time and adds essentially no error
A rotation changes the qubit's phase relative to the drive. Instead of applying a pulse, the controller updates the phase of every subsequent pulse on that qubit (McKay et al., 2017): a software update, not a physical operation.
On a line of qubits your program needs one CNOT between qubits 0 and 3, and the compiler uses SWAPs only (three CNOTs each). What is the minimum total number of CNOTs, including the gate itself?
- 4
- 7
- 10
- 3
Show the answer
B. 7
The qubits are at distance 3. Each SWAP reduces the distance between them by at most one, so two SWAPs are needed to make them adjacent: CNOTs.
Why can't a statevector simulator handle a generic 60-qubit circuit, even though 60-qubit devices exist?
- It would need amplitudes: about bytes at 16 bytes each
- Simulators cannot represent entangled states
- Floating-point numbers cannot store complex amplitudes
- Simulators are limited to the coupling map of a real device
Show the answer
A. It would need amplitudes: about bytes at 16 bytes each
amplitudes times 16 bytes is about 18 exabytes. Methods that exploit structure (stabilizer, tensor networks) can go further for special circuits, but generic deep, highly entangled circuits remain out of reach. Quantum-advantage experiments are built on exactly this gap.
Go deeper
- Compilation: Routing & Optimization · Mapping logical circuits onto constrained hardware.
- OpenQASM 3 & Intermediate Representations · The assembly language of quantum computers.
- Pulse-Level Control · Below the gate: shaping microwave and laser pulses.
Further reading
- M. A. Nielsen & I. L. Chuang, Quantum Computation and Quantum Information, ch. 4 (Cambridge, 10th anniv. ed., 2010).
- A. Javadi-Abhari et al., "Quantum computing with Qiskit" (2024).
- D. C. McKay, C. J. Wood, S. Sheldon, J. M. Chow & J. M. Gambetta, "Efficient Z gates for quantum computing", Phys. Rev. A 96, 022330 (2017).