|q⟩ Bad Qubits

intermediate · Programming · Amplitude Amplification

Counting Solutions

Grover's algorithm searches for one or more marked items but requires you to know MM — the number of solutions — in advance so that you can run the right number of iterations. Quantum counting removes that assumption by estimating MM directly, using phase estimation on the Grover iterate.

The spectrum of the Grover iterate

Every Grover iteration G=DUfG = D \, U_f is a rotation by 2θ2\theta in the two-dimensional plane spanned by the good and bad states, where

sinθ=MN,N=2n.\sin\theta = \sqrt{\frac{M}{N}}, \qquad N = 2^n.

Because GG is a rotation by exactly 2θ2\theta, its eigenvalues are the complex numbers e±2iθe^{\pm 2i\theta} (Nielsen and Chuang, §6.3). Quantum phase estimation (QPE) can extract θ\theta from these eigenvalues. Once we have an estimate θ^\hat\theta of θ\theta, the number of marked items follows from inverting the formula:

M^=Nsin2 ⁣θ^.\hat{M} = N \sin^2\!\hat\theta.

The counting circuit

The full quantum counting algorithm uses two registers:

  1. A phase register of tt ancilla qubits prepared in Ht0tH^{\otimes t}|0^t\rangle. More ancilla qubits give a more accurate estimate of θ\theta.
  2. A target register of nn data qubits initialised to the uniform superposition Hn0nH^{\otimes n}|0^n\rangle (an approximate eigenstate of GG).

Controlled applications of G20,G21,,G2t1G^{2^0}, G^{2^1}, \ldots, G^{2^{t-1}} entangle the phase register with the eigenvalue. An inverse QFT on the phase register then concentrates probability on the bitstring nearest to 2t(2θ/2π)=2tθ/π2^t \cdot (2\theta / 2\pi) = 2^t \theta / \pi. Reading that bitstring gives θ^\hat\theta and therefore M^\hat{M}.

Error analysis

With tt ancilla qubits the estimate satisfies θ^θπ/2t|\hat\theta - \theta| \leq \pi / 2^t. The resulting error in M^\hat{M} is bounded by

M^M2πMN/2t+π2N/4t,|\hat{M} - M| \leq 2\pi \sqrt{M N} / 2^t + \pi^2 N / 4^t,

which decreases exponentially as tt grows (Nielsen and Chuang, §6.3). For a given absolute precision ε\varepsilon it suffices to take t=O ⁣(log ⁣(N/ε))t = O\!\left(\log\!\left(\sqrt{N}/\varepsilon\right)\right) ancilla qubits.

A worked example

Take n=2n = 2 qubits so N=4N = 4, with M=1M = 1 marked item. Then

θ=arcsin ⁣1/4=arcsin(1/2)=π/6.\theta = \arcsin\!\sqrt{1/4} = \arcsin(1/2) = \pi/6.

A phase estimation run that perfectly resolves θ\theta returns θ^=π/6\hat\theta = \pi/6. Plugging into the counting formula:

M^=4sin2(π/6)=4(1/2)2=41/4=1.\hat{M} = 4 \cdot \sin^2(\pi/6) = 4 \cdot (1/2)^2 = 4 \cdot 1/4 = 1.

The estimate is exact here because θ=π/6\theta = \pi/6 is a rational multiple of π\pi and can be represented exactly.

Try it

The exercise asks you to implement the counting formula. You are given N=4N = 4 and a QPE output θ=π/6\theta = \pi/6 — compute and return the estimated number of marked items.

Run your code to see the quantum state.

Sign in on the full site to ask questions and join the discussion.