Skip to main content
KetQat

Appearance

Lesson 11 h

Grover's algorithm

Amplitude amplification derived geometrically, implemented and checked against the SDK.

After this lesson you can

  • Describe the oracle model and count the oracle queries an algorithm makes
  • Derive the Grover iteration as a rotation by 2θ in a two-dimensional plane
  • Compute the success probability sin²((2k+1)θ) and choose an iteration count for known N and M, including when the floor rule and the nearest-integer rule disagree
  • Explain over-rotation and why iterating longer can make the answer worse
  • Generalise Grover search to amplitude amplification of an arbitrary preparation circuit
  • State the BBBV lower bound and what it does and does not imply
  • Implement Grover search with NumPy and verify it against the KetQat SDK grover-search product

Read first: Quantum gates and unitary transformations, Measurement and probability, Multiple qubits and entanglement, Introductory quantum algorithms

The problem Grover's algorithm solves

Suppose you can recognise a solution but have no structure that tells you where to look. You have a function f:{0,1}n→{0,1}f:\{0,1\}^n \to \{0,1\} on N=2nN = 2^n inputs, of which MM are marked (f(x)=1f(x)=1), and the only thing you may do with ff is evaluate it. A classical algorithm that tries inputs in random order needs on average (N+1)/(M+1)(N+1)/(M+1) evaluations, and any classical algorithm needs order N/MN/M of them to succeed with constant probability. Grover showed that a quantum computer can find a marked input with order N/M\sqrt{N/M} evaluations (Grover 1996).

Two points deserve emphasis before any mathematics. First, the speed-up is quadratic, not exponential. Second, it is a statement about the number of evaluations of ff, which is only a useful proxy for running time if evaluating ff is the expensive part. The lesson on complexity and advantage later in this course returns to what that proxy hides.

The oracle model

We assume that ff is available as a quantum circuit, the oracle. The most convenient form is a phase oracle,

Of∣x⟩=(−1)f(x)∣x⟩,O_f \ket{x} = (-1)^{f(x)} \ket{x},

which multiplies marked basis states by −1-1 and leaves the rest alone. If you are given the more common bit oracle ∣x⟩∣y⟩↦∣x⟩∣y⊕f(x)⟩\ket{x}\ket{y} \mapsto \ket{x}\ket{y \oplus f(x)} instead, prepare the target qubit in ∣−⟩=(∣0⟩−∣1⟩)/2\ket{-} = (\ket{0}-\ket{1})/\sqrt2. Then ∣y⊕f(x)⟩\ket{y\oplus f(x)} is ∣−⟩\ket{-} when f(x)=0f(x)=0 and −∣−⟩-\ket{-} when f(x)=1f(x)=1, so the sign moves onto ∣x⟩\ket{x} and the target is left unchanged. This is the phase-kickback trick you met in Foundations, in the lesson on first quantum algorithms.

In the query model we count only the uses of OfO_f. Everything else (Hadamards, reflections, classical post-processing) is free. That makes lower bounds provable, which is why the model is popular, but it also means a query count is not a gate count.

The algorithm

Start in the uniform superposition ∣s⟩=H⊗n∣0⟩⊗n=N−1/2∑x∣x⟩\ket{s} = H^{\otimes n}\ket{0}^{\otimes n} = N^{-1/2}\sum_x \ket{x} and apply the Grover iteration G=D OfG = D\,O_f repeatedly, where

D=2∣s⟩⟨s∣−ID = 2\ketbra{s}{s} - I

is the diffusion operator. On amplitudes, DD maps each amplitude axa_x to 2aˉ−ax2\bar a - a_x, where aˉ\bar a is the mean amplitude: it reflects every amplitude about the mean. As a circuit, D=H⊗n(2∣0⟩⟨0∣−I)H⊗nD = H^{\otimes n}(2\ketbra{0}{0} - I)H^{\otimes n}, and the middle reflection can be built from XX gates and a multi-controlled ZZ. The diagram shows one iteration on three qubits; the controlled ZZ is written as a Toffoli conjugated by Hadamards on its target.

Quantum circuit on 3 wires (q0, q1, q2). step 1: Oracle on q0, q1, q2. step 2: H on q0; H on q1; H on q2. step 3: X on q0; X on q1; X on q2. step 4: H on q2. step 5: Toffoli, controls q0 and q1, target q2. step 6: H on q2. step 7: X on q0; X on q1; X on q2. step 8: H on q0; H on q1; H on q2.q0q1q2OracleHHHXXXHHXXXHHH
One Grover iteration on three qubits: the oracle, then the diffusion operator. The X–CCZ–X block equals I − 2|000⟩⟨000|, which is the reflection 2|000⟩⟨000| − I up to a global sign.

After kk iterations, measure in the computational basis.

The geometry: a rotation in a plane

The whole analysis lives in a two-dimensional subspace. Define the normalised states

∣β⟩=1M∑x: f(x)=1∣x⟩,∣α⟩=1N−M∑x: f(x)=0∣x⟩.\ket{\beta} = \frac{1}{\sqrt M}\sum_{x:\,f(x)=1}\ket{x}, \qquad \ket{\alpha} = \frac{1}{\sqrt{N-M}}\sum_{x:\,f(x)=0}\ket{x}.

They are orthogonal, and the starting state is a combination of them:

∣s⟩=N−MN ∣α⟩+MN ∣β⟩=cos⁡θ ∣α⟩+sin⁡θ ∣β⟩,sin⁡θ=M/N.\ket{s} = \sqrt{\tfrac{N-M}{N}}\,\ket{\alpha} + \sqrt{\tfrac{M}{N}}\,\ket{\beta} = \cos\theta\,\ket{\alpha} + \sin\theta\,\ket{\beta}, \qquad \sin\theta = \sqrt{M/N}.

So θ\theta is the angle between ∣s⟩\ket{s} and the unmarked direction ∣α⟩\ket{\alpha}. Now look at the two operators restricted to this plane.

  • The oracle flips the sign of the ∣β⟩\ket{\beta} component and keeps ∣α⟩\ket{\alpha}: within the plane it is the reflection about the line through ∣α⟩\ket{\alpha}.
  • The diffusion operator 2∣s⟩⟨s∣−I2\ketbra{s}{s}-I keeps ∣s⟩\ket{s} and flips any vector orthogonal to ∣s⟩\ket{s}: it is the reflection about the line through ∣s⟩\ket{s}.

Both operators map the plane to itself, so the state never leaves it. A basic fact of plane geometry finishes the argument: the product of two reflections about lines that meet at angle θ\theta is a rotation by 2θ2\theta. Hence each Grover iteration rotates the state by 2θ2\theta towards ∣β⟩\ket{\beta}, and after kk iterations

Gk∣s⟩=cos⁡((2k+1)θ)∣α⟩+sin⁡((2k+1)θ)∣β⟩.G^k\ket{s} = \cos\big((2k+1)\theta\big)\ket{\alpha} + \sin\big((2k+1)\theta\big)\ket{\beta}.

Measuring gives a marked item with probability

pk=sin⁡2((2k+1)θ).p_k = \sin^2\big((2k+1)\theta\big).

This formula is exact for every NN, MM and kk; nothing has been approximated yet. Your exercise checks it against a direct simulation to ten decimal places.

Choosing the number of iterations

We want (2k+1)θ(2k+1)\theta as close to π/2\pi/2 as possible, so the ideal real-valued iteration count is k~=π/(4θ)−1/2\tilde k = \pi/(4\theta) - 1/2. Two integer rules are in use.

The nearest-integer rule k∗=round⁡(π/(4θ)−1/2)k^\ast = \operatorname{round}(\pi/(4\theta) - 1/2) satisfies ∣k∗−k~∣≤1/2\abs{k^\ast - \tilde k} \le 1/2, so the final angle misses π/2\pi/2 by at most θ\theta and

pk∗≥cos⁡2θ=1−MN.p_{k^\ast} \ge \cos^2\theta = 1 - \frac{M}{N}.

This is a guarantee, with a one-line proof.

The floor rule k=⌊π4N/M⌋k = \lfloor \tfrac{\pi}{4}\sqrt{N/M}\rfloor is what most texts quote and what the KetQat SDK uses by default. It replaces 1/θ1/\theta by 1/sin⁡θ=N/M1/\sin\theta = \sqrt{N/M}, which is accurate when M≪NM \ll N, and in most cases it gives the same integer as the nearest-integer rule. It is not always the same. For N=128N = 128 and M=19M = 19, sin⁡θ=19/128\sin\theta = \sqrt{19/128} gives θ≈0.3955\theta \approx 0.3955; the floor rule picks k=2k=2 with p2≈0.8435p_2 \approx 0.8435, while the nearest-integer rule picks k=1k=1 with p1≈0.8595p_1 \approx 0.8595. The bound 1−M/N≈0.85161 - M/N \approx 0.8516 sits between them. When M/NM/N is not small, compute θ\theta exactly rather than trusting the floor rule.

Worked example: N=8N=8, one marked item

Here sin⁡θ=1/8\sin\theta = 1/\sqrt8, so θ=arcsin⁡(0.35355)≈0.36137\theta = \arcsin(0.35355) \approx 0.36137 rad. Then π/(4θ)−1/2≈1.673\pi/(4\theta) - 1/2 \approx 1.673, and both rules give k=2k = 2. The success probability is sin⁡2(5θ)=sin⁡2(1.80684)≈0.94531\sin^2(5\theta) = \sin^2(1.80684) \approx 0.94531, against 1/8=0.1251/8 = 0.125 for a single random guess. One iteration would give sin⁡2(3θ)=0.78125\sin^2(3\theta) = 0.78125, and three would give sin⁡2(7θ)≈0.33008\sin^2(7\theta) \approx 0.33008: past the optimum the probability falls again. For N=4N = 4 and M=1M = 1, θ=π/6\theta = \pi/6 exactly and one iteration lands on 3θ=π/23\theta = \pi/2, so the search succeeds with certainty.

Over-rotation

Because the state keeps rotating, pkp_k is periodic in kk with period about π/(2θ)\pi/(2\theta). Iterating twice as long as optimal rotates almost all the way back: for N=64N = 64 and M=1M = 1, the optimum k=6k = 6 gives p6≈0.99659p_6 \approx 0.99659, while k=12k = 12 gives p12≈7×10−5p_{12} \approx 7\times10^{-5}. "Run it longer to be safe" is exactly wrong for Grover search. If MM is unknown, choosing a random iteration count from a growing range still finds a marked item with an expected O(N/M)O(\sqrt{N/M}) queries (Boyer, Brassard, Høyer and Tapp 1998); alternatively you can first estimate MM with phase estimation, which the phase estimation lesson prepares.

Amplitude amplification

Nothing in the geometry used the Hadamard transform specifically. Let AA be any circuit that prepares

A∣0⟩=sin⁡θ ∣good⟩+cos⁡θ ∣bad⟩,A\ket{0} = \sin\theta\,\ket{\text{good}} + \cos\theta\,\ket{\text{bad}},

where "good" means "in a subspace you can recognise with a phase oracle SχS_\chi". Define S0=I−2∣0⟩⟨0∣S_0 = I - 2\ketbra{0}{0} and

Q=−A S0 A† Sχ.Q = -A\,S_0\,A^\dagger\,S_\chi .

Since −AS0A†=2A∣0⟩⟨0∣A†−I-A S_0 A^\dagger = 2A\ketbra{0}{0}A^\dagger - I is the reflection about A∣0⟩A\ket0, QQ is again a product of two reflections, and the same argument gives QkA∣0⟩=sin⁡((2k+1)θ)∣good⟩+cos⁡((2k+1)θ)∣bad⟩Q^k A\ket0 = \sin((2k+1)\theta)\ket{\text{good}} + \cos((2k+1)\theta)\ket{\text{bad}} (Brassard, Høyer, Mosca and Tapp 2002).

The consequence is general and useful: if a procedure succeeds with probability a=sin⁡2θa = \sin^2\theta, classical repetition needs about 1/a1/a runs, while amplitude amplification needs about 1/a1/\sqrt a runs of AA and A†A^\dagger. Grover search is the special case A=H⊗nA = H^{\otimes n} and a=M/Na = M/N. The exercise asks you to check the formula with a random unitary as AA.

Optimality: the BBBV bound

Can a cleverer algorithm beat N\sqrt N? No. Bennett, Bernstein, Brassard and Vazirani proved that any quantum algorithm that finds a single marked item among NN with bounded error must query the oracle Ω(N)\Omega(\sqrt N) times (BBBV 1997). Zalka later showed that Grover's iteration count is optimal even in the constant factor (Zalka 1999).

What the theorem says: in the black-box query model, unstructured search has quantum query complexity Θ(N)\Theta(\sqrt N). What it does not say: it does not say NP-complete problems need Ω(2n)\Omega(\sqrt{2^n}) time on a quantum computer, because a real problem is not a black box; structure might be exploited by other algorithms. It is evidence, not proof, that quantum computers do not solve NP-complete problems efficiently.

The intuition behind the bound is that one query can change the state by only a small amount for most possible positions of the marked item, and you need the final states for different marked positions to be nearly orthogonal. The proof is in the paper; this course does not reproduce it.

Implementing it

A statevector implementation needs only three operations on a vector of NN amplitudes: a sign flip on marked indices, a reflection about the mean, and the Born rule.

import numpy as np

n, marked = 3, [5]
N = 2**n
state = np.full(N, 1 / np.sqrt(N))
for k in range(1, 4):
    state[marked] *= -1                  # oracle
    state = 2 * state.mean() - state     # diffusion: reflect about the mean
    print(k, round(float(np.sum(state[marked] ** 2)), 5))

It prints 1 0.78125, 2 0.94531, 3 0.33008: the worked example above. The KetQat SDK offers the same simulation as a catalog product that also samples seeded measurement counts (KetQat SDK):

from ketqat_runner import catalog

record = catalog.run("[email protected]", seed=7, n_qubits=6, marked=[5], shots=1000)
print(record.result["iterations"], round(record.result["success_probability"], 6))

This prints 6 0.996586. A run writes a small record under $KETQAT_HOME (by default ~/.ketqat). The product applies the diffusion as 2∣s⟩⟨s∣−I2\ketbra{s}{s}-I directly, so it reports a success probability, not a gate count; it also models no noise.

Exercise: Grover from scratch

In grover-from-scratch you implement the oracle, the diffusion operator, the iteration rules and amplitude amplification. The checks compare your simulation with the formula sin⁡2((2k+1)θ)\sin^2((2k+1)\theta) for many (n,M,k)(n, M, k), compare your diffusion with its gate construction H⊗n(2∣0⟩⟨0∣−I)H⊗nH^{\otimes n}(2\ketbra00 - I)H^{\otimes n}, test the 1−M/N1 - M/N guarantee of the nearest-integer rule for every M≤N/2M \le N/2 up to nine qubits, and compare your success probabilities with the SDK's [email protected] product.

Common mistakes

  • Iterating "until it works". The success probability oscillates; past the optimum it falls. Fix the iteration count from θ\theta before you run.
  • Using the floor rule when M/NM/N is large. It can land below 1−M/N1 - M/N; compute θ\theta exactly. When M>N/2M > N/2, simply sampling at random already succeeds more often than not.
  • Counting gates as queries. A query bound says nothing about the cost of the oracle circuit. If evaluating ff takes 10610^6 gates, every Grover iteration costs at least that much.
  • Forgetting the sign of the diffusion. H⊗nX⊗n(CCZ)X⊗nH⊗nH^{\otimes n}X^{\otimes n}(\text{CCZ})X^{\otimes n}H^{\otimes n} equals −(2∣s⟩⟨s∣−I)-(2\ketbra{s}{s}-I). A global sign is harmless, but if you build a controlled Grover iteration (as in amplitude estimation) the sign becomes a relative phase and matters.
  • Reading BBBV as a statement about NP. It is a query lower bound for black-box search.

Summary

Grover search alternates two reflections, one about the unmarked states (the oracle) and one about the start state (diffusion). Their product rotates the state by 2θ2\theta with sin⁡θ=M/N\sin\theta = \sqrt{M/N}, so after kk iterations the success probability is exactly sin⁡2((2k+1)θ)\sin^2((2k+1)\theta). Roughly π4N/M\tfrac{\pi}{4}\sqrt{N/M} iterations are optimal, the nearest-integer rule guarantees at least 1−M/N1-M/N, and overshooting lowers the probability. Amplitude amplification extends the same quadratic improvement to any procedure whose success can be recognised. In the query model this is optimal, but a quadratic query advantage turns into a practical advantage only when the oracle is cheap enough, a theme the complexity and advantage lesson develops. The next lesson builds the quantum Fourier transform, the other workhorse of this module.

Exercises

Run these on your own computer. Each comes with automated checks: python -m pytest test_exercise.py. Nothing you write is sent to KetQat.

Grover search and amplitude amplification from scratch

intermediate · about 45 min · needs numpy, pytest, ketqat[algorithms]

Implement Grover's algorithm as a NumPy statevector simulation, then generalise it to amplitude amplification, and check both against independent values.

Basis states are integers 0 .. 2**n - 1. When you print bit strings, qubit 0 is the most significant bit (the course convention); the SDK prints the same order for this product.

Functions to implement in starter.py

Function Contract
uniform_state(n) the vector H⊗n∣0…0⟩H^{\otimes n}\ket{0\dots0}
apply_oracle(state, marked) a new vector with the marked amplitudes negated
apply_diffusion(state) (2∣s⟩⟨s∣−I)(2\ketbra{s}{s} - I) applied to state (reflection about the mean)
grover_state(n, marked, iterations) the state after iterations rounds of oracle then diffusion
success_probability(state, marked) total Born-rule probability of the marked indices
floor_rule_iterations(N, M) ⌊π4N/M⌋\lfloor \tfrac{\pi}{4}\sqrt{N/M} \rfloor
rounded_iterations(N, M) round⁡(π/(4θ)−1/2)\operatorname{round}(\pi/(4\theta) - 1/2) with sin⁡θ=M/N\sin\theta = \sqrt{M/N}
amplitude_amplification(A, good, iterations) QkA∣0⟩Q^k A\ket{0} with Q=−AS0A†SχQ = -A S_0 A^\dagger S_\chi for a unitary matrix A

What the checks verify

  • Your diffusion equals the gate construction H⊗n(2∣0⟩⟨0∣−I)H⊗nH^{\otimes n}(2\ketbra{0}{0} - I)H^{\otimes n} on random vectors.
  • Your simulated success probability equals sin⁡2((2k+1)θ)\sin^2((2k+1)\theta) for several (n,M)(n, M) and every kk up to twice the optimum (independent closed form).
  • The nearest-integer rule reaches at least 1−M/N1 - M/N for every M≤N/2M \le N/2 and n≤9n \le 9.
  • Over-rotation: doubling the optimal iteration count for N=64N = 64, M=1M = 1 drops the success probability below 0.05.
  • Amplitude amplification with a seeded random unitary A follows sin⁡2((2k+1)θ)\sin^2((2k+1)\theta) with sin⁡2θ\sin^2\theta the good-state probability of A|0>, and with A = Hadamards it reproduces Grover's state up to a global phase.
  • Your success probability equals the one reported by the KetQat SDK product [email protected] (statevector simulation) for three instances, including an over-rotated one. This check is skipped if the SDK is not installed.

Run the checks

python -m pytest test_exercise.py

The SDK check writes a run record into a temporary directory, not into your home directory.

Going further

Print the table of (N,M)(N, M) with N≤210N \le 2^{10} for which the floor rule and the nearest-integer rule disagree. What do these cases have in common?

Terminal
python -m pip install numpy pytest "ketqat[algorithms]"

starter.py

Python
"""Starter: Grover search and amplitude amplification with NumPy.

Basis states are indexed by integers 0 .. 2**n - 1. Bit strings are written
most significant bit first, so qubit 0 is the most significant bit (the course
convention). Only integer indices enter these functions, so the convention
matters only when you print bit strings.
"""

import math

import numpy as np


def uniform_state(n):
    """Return the n-qubit uniform superposition H^{(x)n}|0...0> as a complex vector."""
    raise NotImplementedError


def apply_oracle(state, marked):
    """Phase oracle: flip the sign of every marked basis amplitude. Returns a new vector."""
    raise NotImplementedError


def apply_diffusion(state):
    """Diffusion operator 2|s><s| - I applied to `state`, with |s> the uniform state."""
    raise NotImplementedError


def grover_state(n, marked, iterations):
    """State after `iterations` Grover iterations (oracle, then diffusion) on the uniform state."""
    raise NotImplementedError


def success_probability(state, marked):
    """Probability that a computational-basis measurement returns a marked state."""
    raise NotImplementedError


def floor_rule_iterations(N, M):
    """The textbook rule floor(pi/4 * sqrt(N/M))."""
    raise NotImplementedError


def rounded_iterations(N, M):
    """Nearest integer to pi/(4 theta) - 1/2 with sin(theta) = sqrt(M/N).

    This is the rule that guarantees a success probability of at least 1 - M/N.
    """
    raise NotImplementedError


def amplitude_amplification(A, good, iterations):
    """Return Q^k A|0> for the amplitude-amplification operator Q = -A S_0 A^dagger S_good.

    A is a unitary matrix (a state-preparation circuit), `good` the list of good
    basis indices. S_good flips the sign of good basis states; S_0 flips the sign
    of |0...0>.
    """
    raise NotImplementedError

test_exercise.py

Python
import importlib.util
import os
from pathlib import Path

def _load_target():
    name = os.environ.get("KETQAT_COMMONS_TARGET", "starter")
    path = Path(__file__).with_name(f"{name}.py")
    spec = importlib.util.spec_from_file_location(f"{Path(__file__).parent.name}_{name}", path)
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    return module

target = _load_target()

import math

import numpy as np
import pytest


def analytic(N, M, k):
    """Independent value: sin^2((2k+1) theta) with sin(theta) = sqrt(M/N)."""
    theta = math.asin(math.sqrt(M / N))
    return math.sin((2 * k + 1) * theta) ** 2


def hadamard_diffusion(n):
    """Diffusion built from gates, H^n (2|0><0| - I) H^n, as a dense matrix."""
    h = np.array([[1, 1], [1, -1]]) / math.sqrt(2)
    hn = np.array([[1.0]])
    for _ in range(n):
        hn = np.kron(hn, h)
    reflect = -np.eye(2**n)
    reflect[0, 0] = 1
    return hn @ reflect @ hn


def test_uniform_state_is_normalised_and_flat():
    s = target.uniform_state(4)
    assert s.shape == (16,)
    assert np.isclose(np.linalg.norm(s), 1)
    assert np.allclose(np.abs(s), 0.25)


def test_oracle_flips_only_marked_signs():
    s = target.uniform_state(3)
    out = target.apply_oracle(s, [2, 5])
    expected = s.copy()
    expected[[2, 5]] *= -1
    assert np.allclose(out, expected)
    assert np.allclose(s, target.uniform_state(3)), "apply_oracle must not modify its input"


def test_diffusion_equals_its_gate_construction():
    rng = np.random.default_rng(1)
    for n in (1, 2, 3, 5):
        v = rng.normal(size=2**n) + 1j * rng.normal(size=2**n)
        assert np.allclose(target.apply_diffusion(v), hadamard_diffusion(n) @ v)


@pytest.mark.parametrize("n,marked", [(2, [3]), (4, [0, 9]), (6, [5]), (7, [1, 2, 3]), (8, [100, 200])])
def test_simulation_matches_the_rotation_formula(n, marked):
    N, M = 2**n, len(marked)
    for k in range(0, 2 * target.floor_rule_iterations(N, M) + 2):
        state = target.grover_state(n, marked, k)
        assert np.isclose(np.linalg.norm(state), 1, atol=1e-12)
        assert np.isclose(target.success_probability(state, marked), analytic(N, M, k), atol=1e-10)


def test_iteration_rules():
    assert target.floor_rule_iterations(64, 1) == 6
    assert target.floor_rule_iterations(1024, 3) == 14
    assert target.rounded_iterations(4, 1) == 1
    assert target.rounded_iterations(2**20, 1) == 804


def test_rounded_rule_guarantees_one_minus_m_over_n():
    for n in range(2, 10):
        N = 2**n
        for M in range(1, N // 2 + 1):
            k = target.rounded_iterations(N, M)
            assert analytic(N, M, k) >= 1 - M / N - 1e-12, (N, M, k)


def test_over_rotation_lowers_the_success_probability():
    n, marked = 6, [5]
    k_opt = target.floor_rule_iterations(64, 1)
    p_opt = target.success_probability(target.grover_state(n, marked, k_opt), marked)
    p_double = target.success_probability(target.grover_state(n, marked, 2 * k_opt), marked)
    assert p_opt > 0.99
    assert p_double < 0.05


def test_amplitude_amplification_with_a_random_preparation():
    rng = np.random.default_rng(42)
    dim = 8
    z = rng.normal(size=(dim, dim)) + 1j * rng.normal(size=(dim, dim))
    A, _ = np.linalg.qr(z)
    good = [1, 6]
    a = float(np.sum(np.abs(A[good, 0]) ** 2))
    theta = math.asin(math.sqrt(a))
    for k in range(6):
        out = target.amplitude_amplification(A, good, k)
        assert np.isclose(np.linalg.norm(out), 1)
        assert np.isclose(np.sum(np.abs(out[good]) ** 2), math.sin((2 * k + 1) * theta) ** 2, atol=1e-10)


def test_amplitude_amplification_with_hadamards_is_grover():
    n, marked = 4, [3]
    h = np.array([[1, 1], [1, -1]]) / math.sqrt(2)
    A = np.array([[1.0]])
    for _ in range(n):
        A = np.kron(A, h)
    for k in range(4):
        aa = target.amplitude_amplification(A, marked, k)
        gr = target.grover_state(n, marked, k)
        # Equal up to a global phase.
        overlap = abs(np.vdot(aa, gr))
        assert np.isclose(overlap, 1, atol=1e-10)


@pytest.fixture
def ketqat_home(tmp_path, monkeypatch):
    monkeypatch.setenv("KETQAT_HOME", str(tmp_path / "ketqat-home"))


@pytest.mark.parametrize("n,marked,iterations", [(6, [5], None), (5, [3, 17], 6), (8, [7, 64, 200], 2)])
def test_agrees_with_the_ketqat_sdk(ketqat_home, n, marked, iterations):
    catalog = pytest.importorskip("ketqat_runner.catalog")
    record = catalog.run("[email protected]", seed=7, n_qubits=n, marked=marked, iterations=iterations, shots=200)
    assert record.status == "succeeded"
    k = record.result["iterations"]
    if iterations is None:
        assert k == target.floor_rule_iterations(2**n, len(marked))
    ours = target.success_probability(target.grover_state(n, marked, k), marked)
    assert np.isclose(ours, record.result["success_probability"], atol=1e-10)

Check your understanding

  1. In the plane spanned by the unmarked state ∣α⟩\ket{\alpha} and the marked state ∣β⟩\ket{\beta}, what does one Grover iteration G=D OfG = D\,O_f do?

    1 pt
  2. Run your grover-from-scratch solution with n = 6, marked = [5] and the floor-rule iteration count. What is the success probability? (No randomness is involved.)

    1 pt

    Computed by running exercise “grover-from-scratch” on your computer.

  3. Same instance (N=64N = 64, one marked item), but with k=12k = 12 iterations, twice the optimum. Compute the success probability.

    1 pt

    Computed by running exercise “grover-from-scratch” on your computer.

  4. For N=128N = 128 and M=19M = 19, the floor rule gives k=2k = 2 and the nearest-integer rule gives k=1k = 1. Which statement is right?

    1 pt
  5. A preparation circuit AA succeeds with probability a=0.04a = 0.04. How many applications of the amplitude-amplification operator QQ maximise the success probability (use the nearest-integer rule)?

    1 pt
  6. Which statements follow from the BBBV lower bound and Zalka's result? Select all that apply.

    1 pt

    Select all that apply.

Sign in with GitHub to check answers and save progress. Reading stays free without an account.

References

  1. Lov K. Grover (1996). A fast quantum mechanical algorithm for database search. Proceedings of the 28th Annual ACM Symposium on Theory of Computing (STOC '96), 212-219. doi:10.1145/237814.237866
  2. Michel Boyer et al. (1998). Tight bounds on quantum searching. Fortschritte der Physik 46, 493-505. arXiv:quant-ph/9605034
  3. Gilles Brassard et al. (2002). Quantum amplitude amplification and estimation. Quantum Computation and Quantum Information, AMS Contemporary Mathematics 305, 53-74. doi:10.1090/conm/305/05215
  4. Charles H. Bennett et al. (1997). Strengths and weaknesses of quantum computing. SIAM Journal on Computing 26(5), 1510-1523. doi:10.1137/S0097539796300933
  5. Christof Zalka (1999). Grover's quantum searching algorithm is optimal. Physical Review A 60, 2746. doi:10.1103/PhysRevA.60.2746
  6. Michael A. Nielsen, Isaac L. Chuang (2010). Quantum Computation and Quantum Information (10th Anniversary Edition). Cambridge University Press. doi:10.1017/CBO9780511976667
  7. KetQat contributors (2026). KetQat SDK (open source, Apache-2.0), catalog products used at main 2cedabb.