Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

qcfront

qcfront is a Rust quantum computing framework built on roqoqo for circuit construction and QuEST (via roqoqo-quest) for high-performance statevector simulation.

This site is the published documentation for the project. It is generated with mdBook from the sources in the docs/ directory of the repository.

Status

The book is just getting started — most of the project's design notes currently live in the notes/ directory of the repository and will be migrated here as they are polished.

Source

Quantum Gates

A reference for the quantum gates used in qcfront — what they do mathematically and when to use them. For how gates map to physical hardware operations (microwave pulses, lasers, etc.), see GatePhysics.md.

All gates are available in roqoqo as roqoqo::operations::*.

Qubit Basics

A qubit has two basis states: |0⟩ and |1⟩. A general qubit state is α|0⟩ + β|1⟩ where α and β are complex numbers with |α|² + |β|² = 1. |α|² is the probability of measuring 0, |β|² of measuring 1.

The Bloch sphere visualizes a qubit as a point on a unit sphere:

  • |0⟩ is the north pole
  • |1⟩ is the south pole
  • |+⟩ = (|0⟩+|1⟩)/√2 is on the equator

Gates are rotations and reflections on this sphere.

Bloch Sphere

Open bloch.html for an interactive 3D visualization. Drag to rotate, scroll to zoom, apply gates to see how they move the state vector.

  • Z axis: |0⟩ (north) ↔ |1⟩ (south). Rz rotates around this axis.
  • X axis: |+⟩ ↔ |−⟩. Rx rotates around this axis.
  • Y axis: |+i⟩ ↔ |−i⟩. Ry rotates around this axis.
  • Hadamard: reflects through the XZ plane (swaps Z and X axes).

Single-Qubit Gates

Pauli Gates

PauliX (X gate, NOT gate, bit-flip)

Flips the qubit: , . Like a classical NOT gate. On the Bloch sphere: 180° rotation around X.

#![allow(unused)]
fn main() {
circuit += PauliX::new(0); // flip qubit 0
}

PauliY (Y gate)

Flips the qubit and adds a phase: , . 180° rotation around Y axis. Rarely used directly; appears in decompositions.

PauliZ (Z gate, phase-flip)

Doesn't change measurement probabilities — only flips the phase of |1⟩. , . 180° rotation around Z.

Key insight: Z does nothing to basis states individually (they're eigenstates). It matters in superposition: .

Hadamard Gate

Hadamard (H gate)

Creates superposition from a basis state: , .

The most important gate in quantum computing — almost every algorithm starts with H on all qubits. (self-inverse).

#![allow(unused)]
fn main() {
// Create equal superposition over all 3-qubit states
for q in 0..3 {
    circuit += Hadamard::new(q);
}
}

Used in: Grover (initialization), Shor/QPE (counting register), Deutsch-Jozsa, Bernstein-Vazirani, teleportation.

Rotation Gates

RotateX(θ), RotateY(θ), RotateZ(θ)

Rotate the qubit by angle θ around the X, Y, or Z axis of the Bloch sphere. These are the continuous-parameter gates — any single-qubit gate can be decomposed into a sequence of rotations.

changes amplitudes (measurement probabilities). changes only phases (no effect on probabilities). This is why Möttönen state preparation uses for amplitude trees and for phase trees.

How rotations move states on the Bloch sphere

Try these in bloch.html: start from |0⟩ and apply gates.

Key intuition:

  • Ry(θ) changes how much |0⟩ vs |1⟩ — it moves the state between the poles. This controls measurement probabilities. Ry(π/2) takes |0⟩ → |+⟩ → |1⟩ → |−⟩ → |0⟩.
  • Rz(θ) changes the phase between |0⟩ and |1⟩ without changing probabilities. It spins the state around the equator. Rz(π/2) takes |+⟩ → |+i⟩ → |−⟩ → |−i⟩ → |+⟩.
  • Rx(θ) is like Ry but in the Z-Y plane.

This is why Möttönen state preparation uses Ry for amplitudes (setting probabilities) and Rz for phases (setting interference patterns).

Common rotation angles

Angle effect effect
IdentityIdentity
Slight tilt toward equator45° phase rotation
(equal superposition)
(full flip) (like Z)
Back to start (with phase)Back to start (with phase)

Note: is the rotation angle, but the state-vector coefficients use (half-angle). produces .

Special cases:

  • (same as X up to global phase)
#![allow(unused)]
fn main() {
use qoqo_calculator::CalculatorFloat;
// Rotate qubit 0 by π/4 around Y axis: tilt toward equator
circuit += RotateY::new(0, CalculatorFloat::Float(std::f64::consts::PI / 4.0));

// Rotate qubit 1 by π/2 around Z axis: add 90° relative phase
circuit += RotateZ::new(1, CalculatorFloat::Float(std::f64::consts::FRAC_PI_2));
}

Used in: State preparation (Möttönen decomposition uses Ry and Rz trees).

Phase Gates

SGate (√Z, phase gate)

Adds a phase to |1⟩. .

TGate (π/8 gate)

Adds a phase to |1⟩. . Important for universal gate sets and fault-tolerant quantum computing (T gate is the expensive one to implement with error correction).

PhaseShiftGate1(θ)

General phase shift. , , .

Two-Qubit Gates

CNOT (Controlled-NOT, CX)

Flips the target qubit if the control qubit is : . The fundamental entangling gate.

#![allow(unused)]
fn main() {
circuit += CNOT::new(0, 1); // control=0, target=1
}

Bell state creation: then creates . This is the "hello world" of entanglement.

Used in: Everything — Bell states, teleportation, Grover diffusion, QPE controlled unitaries, state preparation (Möttönen decomposition), error correction.

ControlledPauliZ (CZ)

Phase-flips only . Symmetric: . .

#![allow(unused)]
fn main() {
circuit += ControlledPauliZ::new(0, 1);
}

Used in: Grover phase oracle (multi-CZ marks solutions).

SWAP

Exchanges two qubit states: . Built from 3 CNOTs: .

Used in: Shor (controlled modular multiplication swaps work qubits).

Three-Qubit Gates

Toffoli (CCX, CCNOT)

Flips the target only when both controls are . Classical AND gate made reversible. Universal for classical computation.

#![allow(unused)]
fn main() {
// roqoqo convention: first arg is TARGET
circuit += Toffoli::new(2, 0, 1); // target=2, ctrl1=0, ctrl2=1
}

⚠️ roqoqo convention: Toffoli::new(target, control_1, control_2) — the first argument is the target, not a control. This differs from some other frameworks.

Used in: SAT oracle (clause evaluation), modular arithmetic.

ControlledControlledPauliZ (CCZ)

Phase-flips only . Symmetric in all three qubits. .

Used in: Multi-target Grover oracle (marks multiple solutions).

Composite Operations

QFT (Quantum Fourier Transform)

Not a single gate but a built-in roqoqo operation that emits the full QFT circuit (Hadamards + controlled phase rotations + swaps).

#![allow(unused)]
fn main() {
let qubits = vec![0, 1, 2, 3];
circuit += QFT::new(qubits, true, true); // inverse=true, swap=true
}

Used in: Shor/QPE (inverse QFT extracts phase from counting register).

MeasureQubit

Collapses a qubit to |0⟩ or |1⟩ and records the classical result. Irreversible — destroys superposition.

#![allow(unused)]
fn main() {
circuit += MeasureQubit::new(0, "result".to_string(), 0);
//                          qubit  register_name     bit_index
}

PragmaGetStateVector

QuEST-specific: extracts the full state vector without measurement. Deterministic (no collapse). Used for verification/debugging.

#![allow(unused)]
fn main() {
circuit += DefinitionComplex::new("sv".to_string(), dim, true);
circuit += PragmaGetStateVector::new("sv".to_string(), None);
}

Ancilla Qubits

An ancilla (Latin: "servant") is a helper qubit added to a circuit that doesn't hold input or output data. Ancillas serve as scratch space for computations that can't be done directly on the data qubits.

Why ancillas are needed

Quantum gates are reversible — every gate has an inverse. But many useful operations (like AND, OR, multi-controlled gates) are irreversible classically. To make them reversible for a quantum circuit, we store intermediate results in ancilla qubits and uncompute them afterward.

Example: a 5-qubit controlled-Z can't be built from 1- and 2-qubit gates alone. The V-chain decomposition uses 3 ancilla qubits as a "Toffoli ladder" to cascade the AND of controls:

controls: ─●──●─────────────────●──●─
           │  │                 │  │
           ├──┤                 ├──┤
controls: ─●──┼──●──────────●──┼──●─
              │  │          │  │
ancilla₀: ───⊕──●──────────●──⊕─── (back to |0⟩)
              │  │          │  │
ancilla₁: ──────⊕──●────●──⊕────── (back to |0⟩)
                    │    │
ancilla₂: ─────────⊕─CZ─⊕──────── (back to |0⟩)
                      │
target:   ────────────●──────────── (phase flipped)
           forward    ↑   reverse
           pass      gate  pass

The golden rule: clean up after yourself

Ancillas must be returned to |0⟩ after use. If an ancilla is left entangled with the data qubits, subsequent operations (like the diffuser in Grover's algorithm) will act on the wrong subspace, silently producing wrong results.

The standard pattern is compute → use → uncompute:

  1. Compute: fill ancillas with intermediate results
  2. Use: apply the target operation (e.g., phase flip)
  3. Uncompute: run the compute steps in reverse to erase ancillas

Since every quantum gate is its own inverse or has a known inverse, uncomputation is always possible — just replay the gates backward.

Common uses in qcfront

WhereAncilla purposeCount
build_multi_czToffoli V-chain for n-qubit CZmax(0, n−2)
build_multi_cxToffoli V-chain for n-qubit CNOTmax(0, n−2)
CnfOracleClause evaluation + MCZ/MCX scratchc + max(mcx, mcz)
Grover diffuserShares MCZ pattern with oraclemax(0, n−2)

Ancilla vs workspace vs scratch

These terms are used interchangeably in the literature. In qcfront:

  • ancilla = any non-data qubit
  • The Oracle trait's num_ancillas() reports total scratch needed
  • The driver allocates ancillas and passes them via apply()

Gate Universality

Any quantum computation can be built from:

  • — universal gate set (discrete)
  • — universal gate set (continuous)

qcfront's state preparation uses . The algorithms use for clarity.

Quick Reference

GateQubitsroqoqoEffect
X1PauliXBit flip
Y1PauliYBit + phase flip
Z1PauliZPhase flip
H1HadamardCreate superposition
S1SGateπ/2 phase
T1TGateπ/4 phase
Ry(θ)1RotateYY-axis rotation
Rz(θ)1RotateZZ-axis rotation
CNOT2CNOTControlled NOT
CZ2ControlledPauliZControlled phase
SWAP2SWAPExchange qubits
Toffoli3ToffoliDoubly-controlled NOT
CCZ3ControlledControlledPauliZDoubly-controlled phase

Gate Physics

How abstract quantum gates map to physical operations on real hardware. This doc connects the math in Gates.md to what actually happens inside a quantum computer.

The Abstraction Stack

Algorithm level:    circuit += Hadamard::new(0)
                         ↓
Gate level:         H = (1/√2)[[1,1],[1,-1]]    ← Gates.md lives here
                         ↓
Pulse level:        microwave pulse, 25 ns, 5.1 GHz
                         ↓
Physics level:      electromagnetic field rotates electron spin

Quantum software (including qcfront) works at the gate level. The hardware provider's compiler translates gates into physical pulses. This doc explains that bottom layer.

How Each Hardware Realizes Gates

Superconducting Qubits (IBM, Google, Rigetti)

Qubit: a tiny superconducting circuit (transmon) cooled to 15 mK. Two lowest energy levels of an anharmonic oscillator serve as |0⟩ and |1⟩. The energy gap corresponds to a microwave frequency, typically 4–6 GHz.

Single-qubit gates: Apply a calibrated microwave pulse at the qubit's resonance frequency. The pulse parameters control which gate is performed:

Gate parameterPhysical control
Rotation axis (X, Y, Z)Pulse phase (0°, 90°, or virtual-Z via frame tracking)
Rotation angle Pulse duration × amplitude (area under the pulse envelope)
  • = full-power pulse at 0° phase for ~25 ns
  • = same pulse for half the duration (or half amplitude)
  • = no physical pulse needed — implemented by shifting the phase reference frame of all subsequent pulses (virtual-Z gate, ~0 ns)

Two-qubit gates (CNOT, CZ): Enabled by coupling two transmons through a resonator bus or direct capacitive coupling:

  • Cross-resonance (IBM): Drive qubit A at qubit B's frequency. The off-resonant drive creates an effective ZX interaction.
  • Tunable coupler (Google Sycamore): Flux-tune a coupler between two qubits to turn the interaction on/off.
  • Typical CNOT duration: 200–400 ns (much slower than single-qubit gates).

Why CNOT is expensive: Single-qubit gates take ~25 ns with >99.9% fidelity. Two-qubit gates take ~300 ns with ~99–99.5% fidelity. This is why gate counts (especially CNOT counts) matter for circuit depth.

Trapped Ions (IonQ, Quantinuum)

Qubit: a single ion (e.g., Yb⁺, Ba⁺, Ca⁺) trapped in an electromagnetic field. Two hyperfine or optical energy levels serve as |0⟩ and |1⟩.

Single-qubit gates: Focused laser beams drive transitions between the two levels (Rabi oscillation):

Gate parameterPhysical control
Rotation axisLaser beam phase and polarization
Rotation angle Pulse duration × Rabi frequency (laser intensity)

: laser pulse of duration where is the Rabi frequency (~MHz range). Typical gate time: 1–10 μs.

Two-qubit gates (Mølmer-Sørensen / XX gate): Two laser beams create a spin-dependent force on the ion chain's shared vibrational mode (phonon bus). The ions' motion mediates entanglement:

  1. Lasers excite the collective motion of two ions
  2. Spin-motion coupling entangles the internal states
  3. Motion returns to ground state, leaving only spin entanglement

Gate time: 50–200 μs. Fidelity: 99–99.9%.

Key difference from superconducting: All-to-all connectivity — any ion can interact with any other ion (no nearest-neighbor restriction). But gates are much slower (~1000× longer than superconducting).

Photonic (Xanadu, PsiQuantum)

Qubit: a single photon. Unlike other platforms where the qubit persists in a trap or circuit, a photonic qubit is short-lived — it is generated on demand, flies through optical components at the speed of light, and is destroyed upon detection. The entire computation happens during the photon's flight (~nanoseconds).

PropertyPhotonicOther platforms
Qubit lifetime~ns (flight time)μs to hours
DecoherenceNone (photons don't interact with environment)Major challenge
Main error sourcePhoton loss (absorption/scattering in waveguide)Decoherence
ReusabilityDestroyed on measurementCan be re-measured (but collapses)

Photon source: Single photons are generated from quantum dots, spontaneous parametric down-conversion (SPDC) crystals, or four-wave mixing in silicon waveguides. Generating truly single photons reliably is itself a major engineering challenge.

Encoding varies:

  • Polarization: horizontal |H⟩ = |0⟩, vertical |V⟩ = |1⟩
  • Path: photon in upper waveguide = |0⟩, lower = |1⟩
  • Time-bin: early arrival = |0⟩, late = |1⟩

Single-qubit gates: Optical elements manipulate the photon in flight:

GatePhysical element
Phase shifter (voltage-controlled refractive index change)
Beamsplitter with tunable reflectivity
50:50 beamsplitter
Waveguide crossing or polarization rotator

Two-qubit gates: The hard part. Photons don't naturally interact. Approaches:

  • Measurement-based (KLM protocol): Entangle via post-selected measurements on ancilla photons. Probabilistic — requires many attempts.
  • Fusion gates: Merge photonic resource states via Bell measurements.

Because two-qubit gates are probabilistic, many photonic quantum computers use measurement-based quantum computing (MBQC) instead of the circuit model: generate a large entangled cluster state of many photons, then compute by measuring individual photons in chosen bases. The computation emerges from the measurement pattern, not from applying gates in sequence.

Neutral Atoms (QuEra, Pasqal)

Qubit: individual atoms (Rb, Cs) held in optical tweezers (focused laser beams). Hyperfine ground states or Rydberg excited states encode |0⟩ and |1⟩.

Single-qubit gates: Raman transitions via laser pulses (similar to trapped ions).

Two-qubit gates (Rydberg blockade): Excite one atom to a highly excited Rydberg state. The enormous electric dipole of the Rydberg atom shifts the energy levels of a nearby atom, preventing double excitation:

  • If atom A is in Rydberg state, atom B cannot be excited → CZ gate
  • Blockade radius: ~5–10 μm
  • Gate time: ~0.5–1 μs

Gate Fidelities by Platform (approximate, 2024)

Platform1-qubit fidelity2-qubit fidelityGate time (2Q)
Superconducting99.9%99–99.5%200–400 ns
Trapped ions99.99%99–99.9%50–200 μs
Neutral atoms99.5%97–99%0.5–1 μs
Photonic99.9%~90–95% (heralded)~ns (but probabilistic)

These numbers determine how many gates you can apply before errors accumulate. With 99.5% two-qubit fidelity, a 100-CNOT circuit has expected fidelity ~0.995¹⁰⁰ ≈ 0.61 — already marginal.

Native Gate Sets

Hardware doesn't implement arbitrary gates directly. Each platform has a native gate set — the physically calibrated operations. The compiler decomposes your circuit into these:

PlatformNative gatesCNOT decomposition
IBM (Eagle+), , CXnative
Google (Sycamore), , 2 native gates
IonQ (Aria), , , XX1 XX + single-qubit
Quantinuum (H2), , ZZ1 ZZ + single-qubit
Rigetti (Ankaa), , CZH·CZ·H

Virtual-Z optimization: On most superconducting platforms, is "free" — it's implemented by changing the software phase reference, not by applying a physical pulse. Compilers exploit this aggressively.

Measurement

Standard measurement: Project onto Z basis (|0⟩ or |1⟩).

PlatformHow measurement worksTime
SuperconductingProbe dispersive shift of readout resonator~300 ns
Trapped ionsFluorescence detection —1⟩ scatters photons,
PhotonicSingle-photon detector (click =1⟩, no click =
Neutral atomsFluorescence imaging on CCD camera~1 ms

Measuring in other bases: To measure in the X basis, apply H before measuring in Z. To measure in an arbitrary basis defined by angles , apply before measuring. The detector doesn't rotate — the state does.

Why This Matters for Software

  1. Gate count → circuit fidelity: More gates = more error accumulation. Our Möttönen state preparation uses O(2ⁿ) CNOTs — only practical for small qubit counts on current hardware.

  2. Connectivity constraints: Superconducting qubits have nearest-neighbor connectivity. A CNOT between distant qubits requires SWAP gates to move data — the transpiler adds these automatically. Trapped ions don't have this problem.

  3. Native gate translation: When we export QIR for Azure Quantum, the hardware provider's compiler handles translation to native gates. Our circuit uses {H, CNOT, Ry, Rz, Toffoli} which all decompose cleanly.

  4. Virtual-Z means Rz is free: Circuit optimizations that convert gates into Rz equivalents save real time on superconducting hardware.

Beyond Qubits: Qudits

Qubits use 2 energy levels, but physical systems often have more. A qudit uses d levels (qutrit for d=3, ququart for d=4). A single qutrit carries bits — more information per particle, potentially fewer particles and fewer two-particle gates.

SystemLevels usedWho
Transmon higher levels3–4Google, Yale
Trapped ion Zeeman statesup to 7Innsbruck, Duke
Photon orbital angular momentumunboundedVienna

Why qubits still dominate: Error correction for d>2 is harder — each additional level adds decay and leakage channels. The entire software stack (algorithms, compilers, cloud APIs) assumes d=2. Superconducting transmons actively avoid their third level by engineering the anharmonicity so the 0↔1 transition frequency differs from 1↔2. The marginal information gain from d=3 doesn't yet justify rebuilding the ecosystem.

qcfront and roqoqo are qubit-only, matching the industry standard.

Sources

  • Krantz et al., "A Quantum Engineer's Guide to Superconducting Qubits", arXiv:1904.06560 (2019)
  • Bruzewicz et al., "Trapped-ion quantum computing: Progress and challenges", arXiv:1904.04178 (2019)
  • Saffman, "Quantum computing with neutral atoms", National Science Review (2019)
  • IBM Quantum documentation: https://docs.quantum.ibm.com
  • Google Quantum AI: https://quantumai.google

Grover's Algorithm

A beginner-friendly guide to Grover's quantum search — what it does, why it's faster than classical search, and how it works step by step. For gate definitions used below, see Gates.md.

The Core Question: How Many Queries Does It Take?

Suppose you have a black-box function that answers "yes" or "no" for each input. You want to find an where . The only way to learn anything about is to query it — feed in an and read the answer. Every query costs time (and on real hardware, money).

The goal is to minimize the number of queries.

Classically, if there are possible inputs and only one correct answer, you have no choice but to try inputs one at a time. On average you need queries, and in the worst case all .

Grover's algorithm solves this with only queries by exploiting quantum superposition — querying the function on all inputs simultaneously and then amplifying the answer that comes back "yes."

Inputs ()Classical queriesGrover queries
100~50~8
10,000~5,000~79
1,000,000~500,000~785

This is a quadratic speedup. Not exponential like Shor's factoring algorithm, but it applies to any problem that can be phrased as "search for an input satisfying some condition" — database lookup, constraint satisfaction (SAT), optimization, cryptographic key search, and more. That generality makes Grover one of the most broadly useful quantum algorithms.

The Oracle: A Quantum Yes/No Black Box

There are two layers to understand:

  1. — the abstract function that defines the problem. It maps each input to 0 ("no") or 1 ("yes"). For example, "is a prime factor of 21?" This is pure math — it says what you're searching for.

  2. — the oracle circuit that implements on a quantum computer. It's the physical realization — a sequence of quantum gates that evaluates on a superposition of all inputs at once.

You don't need to know the internals of to understand Grover's algorithm — it works with any yes/no function. That's why is called a "black box."

The key trick is how reports its answer. Instead of writing a classical 0 or 1 to an output register, it flips the phase (sign) of solution states:

  • If (not a solution): the state is unchanged
  • If (a solution): the amplitude gets a minus sign

This is called a phase oracle. The minus sign is invisible if you measure immediately — — but it creates a pattern that the rest of the algorithm can exploit.

Why a phase flip instead of a bit flip? Because Grover's algorithm works by interference. The negative amplitude of the solution state interferes constructively with itself during the diffuser step (below), causing its probability to grow. A classical 0/1 output can't produce this interference effect.

Building real oracle circuits: For a simple "find value 5" search, is just a few X and multi-controlled-Z gates (shown in the walkthrough below). For harder problems like SAT, encodes the entire formula as a reversible circuit — see sat_grover.rs for a working example.

Key Idea: Amplitude Amplification

Quantum states carry amplitudes (complex numbers whose squares give probabilities). Grover's algorithm works by manipulating amplitudes:

  1. Start with all items equally likely (uniform superposition)
  2. Repeatedly shrink the amplitude of wrong answers and grow the amplitude of right answers
  3. Measure — the right answer pops out with high probability

Each "shrink + grow" cycle is one Grover iteration. After iterations (where is the number of solutions), the success probability is nearly 100%.

The Circuit

     ┌───┐ ┌────────┐ ┌─────────┐       ┌────────┐ ┌─────────┐ ┌───┐
|0⟩──┤ H ├─┤        ├─┤         ├─ ... ─┤        ├─┤         ├─┤ M ├
     └───┘ │        │ │         │       │        │ │         │ └───┘
     ┌───┐ │ Oracle │ │ Diffuser│       │ Oracle │ │ Diffuser│ ┌───┐
|0⟩──┤ H ├─┤  U_f   ├─┤  U_s    ├─ ... ─┤  U_f   ├─┤  U_s    ├─┤ M ├
     └───┘ │        │ │         │       │        │ │         │ └───┘
     ┌───┐ │        │ │         │       │        │ │         │ ┌───┐
|0⟩──┤ H ├─┤        ├─┤         ├─ ... ─┤        ├─┤  U_s    ├─┤ M ├
     └───┘ └────────┘ └─────────┘       └────────┘ └─────────┘ └───┘
           ├────── one iteration ──────┤
                    × k iterations

Three stages:

  1. Initialization — Hadamard on every qubit → uniform superposition
  2. Grover iterations — repeat (Oracle + Diffuser) times
  3. Measurement — read out the answer

Step-by-Step Walkthrough (3 qubits, target = 5)

Step 1: Superposition

Apply to :

Every state has amplitude . Probability of measuring any specific state is .

Step 2: Oracle () — "Mark" the Winner

The oracle flips the sign (phase) of the solution:

For target :

StateBefore oracleAfter oracle
through
,

No measurement probabilities change yet — the minus sign is hidden in the phase. But it sets up the diffuser to amplify the target.

How the oracle circuit works

To flip only :

  1. Apply to qubits where the target bit is 0 (qubit 1) — this maps
  2. Apply a multi-controlled- gate (MCZ) — flips the phase of
  3. Undo the gates

In qcfront, MCZ is built from Toffoli + CZ gates via a V-chain decomposition (see multi_cz.rs).

Step 3: Diffuser () — "Amplify" the Winner

The diffuser reflects every amplitude about the mean:

where is the uniform superposition.

Concrete math for our example:

After the oracle, the mean amplitude is:

The diffuser maps each amplitude :

  • Non-targets:
  • Target :

After 1 iteration, the target has amplitude , giving .

How the diffuser circuit works

Implemented as: H on all → X on all → MCZ → X on all → H on all.

This is the same MCZ gate used in the oracle, but sandwiched in Hadamard + X gates to reflect about instead of .

Step 4: More Iterations

For , , :

AfterTarget amplitude(target)
Init0.35412.5%
1 iteration0.88478.1%
2 iterations0.97394.5%

Our implementation uses for 3 qubits, achieving >94% success.

Step 5: Measure

Measure all qubits → read out the binary string → decode as integer. With 94.5% probability, you get 5 ().

The Geometry

Grover's algorithm has an elegant geometric interpretation in a 2D plane spanned by:

  • = the target state (or uniform superposition of all targets)
  • = the uniform superposition of non-targets

The initial state makes angle with where .

Each Grover iteration rotates the state by toward :

        |w⟩
         ↑
         |   /  ← after 2 iterations (angle 5θ/2)
         |  /
         | /  ← after 1 iteration (angle 3θ/2)
         |/
    ─────┼───── |w⊥⟩
   θ/2 ↗
  |s⟩ = initial state

After iterations, the angle is . The algorithm works best when this angle is close to (pointing at ).

Overshooting: If you apply too many iterations, the state rotates past and success probability drops. This is why the optimal iteration count matters — Grover is not "more iterations = better."

Multiple Solutions

When there are solutions, the optimal iteration count drops:

Note
3812Standard case
3821Fewer iterations needed
3841Even fewer
3870Nearly all states are solutions — no iteration needed

When , random measurement is already likely to succeed, so (no Grover iterations at all).

Oracle Complexity

The oracle is the expensive part. Grover's speedup is measured in oracle queries, not total gates. A single oracle query for our simple "find value " costs just gates (X gates + one MCZ). But for real problems (SAT, optimization), the oracle encodes problem logic and can be much more complex.

SAT oracle example: Given a CNF formula, the oracle computes the formula on a superposition of all assignments. If the formula is satisfiable, Grover finds a satisfying assignment in oracle calls instead of exhaustive search. See sat_grover.rs for a working example.

What Grover Cannot Do

  • Unknown : If you don't know how many solutions exist, you can't compute the optimal iteration count. Workaround: quantum counting (QPE on the Grover operator) to estimate first, or randomized approaches with expected queries.

  • Unstructured search only: Problems with structure (sorting, graph search) often have better classical algorithms. Grover shines when the only access to the problem is a black-box oracle.

  • No exponential speedup: The speedup is provably optimal for unstructured search (BBBV theorem). No quantum algorithm can do better with black-box oracle access.

qcfront Implementation

See GroverSearch.md for implementation details, API reference, and the Oracle trait design.

Further Reading

  • Grover, L. K. (1996). "A fast quantum mechanical algorithm for database search." Proceedings of STOC '96, pp. 212–219.
  • Nielsen & Chuang, Quantum Computation and Quantum Information, Chapter 6: "Quantum search algorithms."
  • Boyer et al. (1998). "Tight bounds on quantum searching." Fortschritte der Physik, 46(4-5), pp. 493–505.

Bloch Sphere

An interactive 3D visualization of single-qubit states on the Bloch sphere. Click the link below to open it in a new tab — it uses three.js loaded from a CDN to render the sphere and animate gate operations.

Open the interactive Bloch sphere →

What it shows

  • The unit sphere with at the north pole and at the south pole.
  • The state vector for a single qubit, with controls to apply , , , , , and gates and watch the vector rotate.
  • The mapping between gate operations and rotations of the sphere (see Gate Physics for the underlying math).

Source

The source is a single self-contained HTML file at docs/theory/bloch.html in the repository.