Simple Algorithm
Quantum Computing · Excited State · 22 min

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 XX and YY.
  • 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:

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.

python
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 = 11

A Bell pair in Cirq: different syntax, identical abstraction.

Shots, counts and expectation values

A backend returns counts: how often each bit string occurred in NN shots. Everything else is estimated from them. For a ZZ-type Pauli string such as Z⊗ZZ\otimes Z, every shot yields an eigenvalue ±1\pm1: the parity of the measured bits.

DerivationEstimating a Pauli expectation value
  1. P^=1N∑k=1Nxk,E[P^]=p+−p−=⟨P⟩\hat P=\frac1N\sum_{k=1}^Nx_k,\qquad \mathbb E[\hat P]=p_+-p_-=\expval{P}

    Measuring a Pauli string PP in its eigenbasis returns xk∈{+1,−1}x_k\in\{+1,-1\} on shot kk; for ZZ-type strings xk=(−1)parity of the measured bitsx_k=(-1)^{\text{parity of the measured bits}}. The sample mean is unbiased:

  2. Var⁡(xk)=E[xk2]−⟨P⟩2=1−⟨P⟩2\operatorname{Var}(x_k)=\mathbb E[x_k^2]-\expval{P}^2=1-\expval{P}^2

    Because xk2=1x_k^2=1, the single-shot variance is fixed by the mean:

  3. ΔP^=1−⟨P⟩2N  ≤  1N\Delta\hat P=\sqrt{\frac{1-\expval{P}^2}{N}}\;\le\;\frac{1}{\sqrt N}

    Shots are independent, so the standard error is

  4. N  ≥  2ε2ln⁡2δN\;\ge\;\frac{2}{\varepsilon^2}\ln\frac2\delta

    For a guarantee rather than a typical error, Hoeffding's inequality gives Pr⁡[∣P^−⟨P⟩∣≥ε]≤2e−Nε2/2\Pr\big[\abs{\hat P-\expval{P}}\ge\varepsilon\big]\le2e^{-N\varepsilon^2/2}, so accuracy ε\varepsilon with confidence 1−δ1-\delta needs

Hardware measures only in the computational basis. To measure XX, first rotate its eigenbasis onto ZZ's with HH; for YY, apply S†S^\dagger and then HH. For the Bell state ∣Φ+⟩\ket{\Phi^+}, rotating both qubits and reading parities gives ⟨XX⟩=+1\expval{XX}=+1, ⟨YY⟩=−1\expval{YY}=-1 and ⟨ZZ⟩=+1\expval{ZZ}=+1. Check the surprising sign:

Predict before you look

You need ⟨Z⟩\expval{Z} of a state with ⟨Z⟩≈0\expval{Z}\approx0 to a standard error of 0.010.01. How many shots?

Show the answer

10000 shots

Δ=(1−0)/N=0.01\Delta=\sqrt{(1-0)/N}=0.01 gives N=104N=10^4. Every extra decimal digit of precision costs a factor of 100 in shots.

python
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 = 1

An 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:

  1. Unroll high-level gates into the basis, e.g. {RZ,X,X,CX}\{R_Z,\sqrt X,X,\text{CX}\} or {RZ,X,CZ}\{R_Z,\sqrt X,\text{CZ}\} on superconducting chips; trapped ions typically offer arbitrary one-qubit rotations and a Mølmer–Sørensen XXXX-type gate.
  2. Layout: assign logical qubits to physical ones, ideally so that interacting pairs are neighbors.
  3. Routing: insert SWAPs where they are not.
  4. Optimize: cancel inverse pairs, merge rotations, resynthesize blocks.
  5. Schedule: assign start times, respecting gate durations.
DerivationA Hadamard from native gates
  1. RX(π2) RZ(π2)=12(e−iπ/4−ieiπ/4−ie−iπ/4eiπ/4)R_X(\tfrac\pi2)\,R_Z(\tfrac\pi2)=\tfrac{1}{\sqrt2}\begin{pmatrix}e^{-i\pi/4}&-ie^{i\pi/4}\\-ie^{-i\pi/4}&e^{i\pi/4}\end{pmatrix}

    With RZ(α)=diag⁡(e−iα/2,eiα/2)R_Z(\alpha)=\diag(e^{-i\alpha/2},e^{i\alpha/2}) and X=eiπ/4RX(π/2)\sqrt X=e^{i\pi/4}R_X(\pi/2), where RX(π2)=12(1−i−i1)R_X(\tfrac\pi2)=\tfrac{1}{\sqrt2}\begin{pmatrix}1&-i\\-i&1\end{pmatrix}, multiply out:

  2. RZ(π2) RX(π2) RZ(π2)=12(−i−i−ii)=−i HR_Z(\tfrac\pi2)\,R_X(\tfrac\pi2)\,R_Z(\tfrac\pi2)=\tfrac{1}{\sqrt2}\begin{pmatrix}-i&-i\\-i&i\end{pmatrix}=-i\,H

    Multiplying by RZ(π/2)R_Z(\pi/2) on the left scales the rows by e∓iπ/4e^{\mp i\pi/4}:

  3. H  ≃  RZ(π2) X RZ(π2)H\;\simeq\;R_Z(\tfrac\pi2)\,\sqrt X\,R_Z(\tfrac\pi2)

    So, up to an unobservable global phase, one physical pulse and two virtual ZZ rotations (which cost no time) make a Hadamard. In the same way every one-qubit unitary needs at most two X\sqrt X pulses: RZ X RZ X RZR_Z\,\sqrt X\,R_Z\,\sqrt X\,R_Z.

Two-qubit gates are where the hardware bites. A SWAP costs three CNOTs; on a line 0−1−20-1-2, a CNOT between the end qubits needs either a SWAP or the four-CNOT bridge CX0→2=CX1→2 CX0→1 CX1→2 CX0→1\text{CX}_{0\to2}=\text{CX}_{1\to2}\,\text{CX}_{0\to1}\,\text{CX}_{1\to2}\,\text{CX}_{0\to1} (operators act right to left), which leaves qubit 1 untouched.

SWAP=CX1→2 CX2→1 CX1→2:(a,b)↦(a,a⊕b)↦(b,a⊕b)↦(b,a)\text{SWAP}=\text{CX}_{1\to2}\,\text{CX}_{2\to1}\,\text{CX}_{1\to2}:\qquad (a,b)\mapsto(a,a\oplus b)\mapsto(b,a\oplus b)\mapsto(b,a)
Three alternating CNOTs exchange two qubits; track a basis state ∣a,b⟩\ket{a,b} to see it.
python
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.

Check your understanding

Your circuit has two-qubit gates between all three pairs of qubits 0, 1, 2. The coupling map is a line a−b−ca-b-c. Can a well-chosen initial layout alone make every two-qubit gate act on neighboring physical qubits?

  1. Yes: map logical qubit 1 to the middle qubit bb
  2. Yes, provided the gates are reordered
  3. 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
  4. 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:

SimulatorRepresentsCostUse it for
StatevectorAll 2n2^n amplitudes16⋅2n16\cdot2^n bytes (complex128)Exact amplitudes and expectation values: about 30 qubits on a workstation, mid-40s on supercomputers
SamplingA statevector plus random drawsSame, plus NN samplesRealistic counts with shot noise
NoisyA density matrix (4n4^n entries) or many sampled trajectories16⋅4n16\cdot4^n bytes for the density matrixPredicting the effect of noise models, on roughly half as many qubits
Stabilizer, tensor networkClifford tableaux; low-entanglement tensor networksPolynomial for Clifford circuits; set by entanglement for tensor networksLarge Clifford circuits (error-correction studies); shallow or weakly entangled circuits
Predict before you look

How much memory does a 30-qubit statevector need at 16 bytes per complex amplitude? Answer in GiB (1 GiB=2301\ \text{GiB}=2^{30} bytes).

Show the answer

16 GiB

230×162^{30}\times16 bytes =16=16 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 11 as 00 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 (1−⟨P⟩2)/N≤1/N\sqrt{(1-\langle P\rangle^2)/N}\le1/\sqrt N; XX and YY 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 16⋅2n16\cdot2^n 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.

Question 1

A two-qubit circuit returns counts {00: 430, 01: 70, 10: 50, 11: 450}\{00{:}\,430,\ 01{:}\,70,\ 10{:}\,50,\ 11{:}\,450\} in 1000 shots (qubit 0 on the left). What is the estimate of ⟨Z⊗Z⟩\expval{Z\otimes Z}?

  1. 0.880.88
  2. 0.760.76
  3. 0.000.00
  4. −0.76-0.76
Show the answer

B. 0.760.76

Each shot contributes (−1)b0⊕b1(-1)^{b_0\oplus b_1}: even parity (0000, 1111) gives +1+1, odd parity gives −1-1. So (880−120)/1000=0.76(880-120)/1000=0.76, with standard error (1−0.762)/1000≈0.02\sqrt{(1-0.76^2)/1000}\approx0.02.

Question 2

Why do compilers for superconducting qubits like to move work into RZR_Z rotations?

  1. RZR_Z rotations commute with every other gate
  2. RZR_Z gates are the only gates that can run in parallel
  3. RZR_Z rotations do not change measurement probabilities, so they can be deleted
  4. RZR_Z 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. RZR_Z is implemented virtually, as a phase shift of all later pulses, so it takes no time and adds essentially no error

A ZZ 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.

Question 3

On a line of qubits 0−1−2−30-1-2-3 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?

  1. 4
  2. 7
  3. 10
  4. 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: 2×3+1=72\times3+1=7 CNOTs.

Question 4

Why can't a statevector simulator handle a generic 60-qubit circuit, even though 60-qubit devices exist?

  1. It would need 2602^{60} amplitudes: about 1.8×10191.8\times10^{19} bytes at 16 bytes each
  2. Simulators cannot represent entangled states
  3. Floating-point numbers cannot store complex amplitudes
  4. Simulators are limited to the coupling map of a real device
Show the answer

A. It would need 2602^{60} amplitudes: about 1.8×10191.8\times10^{19} bytes at 16 bytes each

260≈1.15×10182^{60}\approx1.15\times10^{18} 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

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).