qalgora-Q Docs Hub量子文档 ✦ Ask AI✦ 问问文档

Grover's Algorithm

Search an unstructured space of N items in O(√N) queries — a quadratic speedup over the classical O(N). It is the canonical example of amplitude amplification.

The problem it solves

Imagine a function f(x) that returns 1 for exactly one "winning" input and 0 for every other. You have no structure to exploit — no sorting, no index, just the ability to test inputs. A classical computer can do no better than trying them one at a time: on average N/2 tests, and N in the worst case. Grover finds the winner in about √N tests.

The speedup is quadratic, and it compounds at scale:

Search space NClassical (worst case)Grover (≈√N)
100100~10
1,000,0001,000,000~1,000
2⁶⁴ (a 64-bit key)1.8 × 10¹⁹~4.3 × 10⁹

Note: the “≈√N” column is the order of magnitude of the query complexity, not the exact iteration count; the optimal number of iterations is ⌊(π/4)·√N⌋.

Geometric intuition — amplitude amplification

The whole algorithm lives in a 2-D plane spanned by two vectors: the winning state |w⟩ and an equal mixture of all the losers, |s'⟩. The starting uniform superposition |s⟩ sits almost on top of |s'⟩, leaning toward |w⟩ by only a tiny angle θ — because a random guess has just a 1/N chance of being right.

Each Grover iteration performs two reflections, and two reflections make a rotation. Specifically, every iteration rotates the state by toward |w⟩. Repeat enough times and the state swings around to point almost exactly at |w⟩, so a measurement returns the winner with high probability.

Why √N iterations — and why not more

The initial lean satisfies sin θ = 1/√N, so for large N the angle is θ ≈ 1/√N (in radians). Each step adds , and we need to travel from ≈0 to π/2 (the |w⟩ axis). That takes about

(π/2) / (2θ) ≈ (π/4)·√N iterations.

This is why Grover is periodic, not monotonic: keep iterating past the optimum and the state rotates past |w⟩, and the success probability falls again. More shots help; more iterations do not.

The two operators

OperatorWhat it does
Oracle (phase flip)Flips the sign of the winner's amplitude: |w⟩ → −|w⟩, leaving losers untouched. It recognises the answer — it does not reveal or "know" it.
Diffusion (inversion about the mean)Reflects every amplitude about their average. After the oracle has pushed the winner below the mean, this reflection lifts it far above the rest.

Oracle then diffusion = one rotation by 2θ. That pairing, repeated, is the engine of the algorithm.

Recognising vs. knowing
The oracle is just an efficient test for "is this a solution?". Grover never needs someone to tell it the answer — if you already knew the winner you would not be searching. This is why it applies to problems like inverting a hash or checking a SAT assignment, where verifying a guess is cheap but finding one is hard.

What it is — and isn't — good for

  • Quadratic, not exponential. Grover does not "break" hard problems the way Shor breaks factoring; it just square-roots the cost of brute force.
  • The oracle must be a cheap quantum function. Loading N unstructured classical records into an oracle itself costs O(N) — which would erase the speedup. The win comes when the oracle is a compact rule (a hash, a constraint check), not a literal database.
  • It is provably optimal. No quantum algorithm beats O(√N) for truly unstructured search, so this is the end of the road for this problem — not a stepping stone to more.
  • It generalises. The same reflect-and-rotate trick, called amplitude amplification, is a reusable building block inside larger algorithms.

The algorithm, step by step

  1. Prepare a uniform superposition with Hadamards — the starting state |s⟩.
  2. Apply the oracle to phase-flip the marked state.
  3. Apply the diffusion operator to amplify its amplitude (one rotation of 2θ).
  4. Repeat about (π/4)·√N times, rounded to the nearest integer, then measure.

Seeing it in code

The kernel below makes the marked state the all-ones string 11…1. Read it against the theory above: h(q) builds the uniform superposition; the multi-controlled z.ctrl(...) is the oracle that phase-flips that one state; the h(q); x(q) … x(q); h(q) sandwich is the diffusion operator; and iters is the nearest integer to (π/4)·√N. The optimal count is more precisely k ≈ round(π/(4θ) − 1/2) — the nearest integer, since the success probability sin²((2k+1)θ) peaks at k = π/(4θ) − 1/2 — with sin θ = 1/√N.

This implementation differs from the standard diffusion operator D = 2|s⟩⟨s| − I by at most a global phase / equivalent convention, which does not affect measurement probabilities.

The example assumes n ≥ 2; for n = 1 the semantics of a multi-controlled gate with an empty control list is framework-dependent.

import qalgora, math

@qalgora.kernel
def grover(n: int, iterations: int):
    q = qalgora.qvector(n)
    h(q)
    for _ in range(iterations):
        # oracle: mark the all-ones state
        z.ctrl(q[0:n-1], q[n-1])
        # diffusion operator
        h(q); x(q)
        z.ctrl(q[0:n-1], q[n-1])
        x(q); h(q)
    mz(q)

n = 3
iters = round(math.pi / 4 * math.sqrt(2 ** n))
print(qalgora.sample(grover, n, iters))   # peaks at "111"
Try it yourself
Vary iters away from the optimum and watch the "111" peak shrink — a direct, hands-on demonstration of Grover's periodicity. The phase-estimation and QAOA pages reuse the same superposition-and-interference ideas.

References

  • L. K. Grover, "A fast quantum mechanical algorithm for database search," Proc. 28th ACM STOC, 212-219 (1996). arXiv:quant-ph/9605043

Grover 算法

在 N 个无结构项的空间中以 O(√N) 次查询完成搜索——相较经典 O(N) 实现平方级加速。它是振幅放大最经典的范例。

它解决的问题

设想一个函数 f(x),仅对某一个"中奖"输入返回 1,对其余全部返回 0。你手上没有任何可利用的结构——没有排序、没有索引,只能逐个测试。经典计算机无法做得更好:平均 N/2 次、最坏 N 次测试。而 Grover 只需约 √N 次就能找到中奖项。

这一加速是平方级的,规模越大越显著:

搜索空间 N经典(最坏情况)Grover(≈√N)
100100~10
1,000,0001,000,000~1,000
2⁶⁴(64 位密钥)1.8 × 10¹⁹~4.3 × 10⁹

注:「≈√N」一列为查询复杂度的数量级,并非精确迭代次数;最优迭代次数为 ⌊(π/4)·√N⌋

几何直觉 振幅放大

整个算法都活动在一个二维平面里,由两个向量张成:中奖态 |w⟩ 与所有未中奖态的等权混合 |s'⟩。初始的均匀叠加态 |s⟩ 几乎贴在 |s'⟩ 上,只朝 |w⟩ 偏出一个极小的角度 θ——因为随机一猜命中的概率只有 1/N。

每一次 Grover 迭代执行两次反射,而两次反射合起来就是一次旋转。具体地说,每次迭代把状态朝 |w⟩ 旋转 。迭代足够多次后,状态便几乎正对 |w⟩,此时测量就能以高概率读出中奖项。

为何是 √N 次 又为何不能更多

初始偏角满足 sin θ = 1/√N,故当 N 较大时 θ ≈ 1/√N(弧度)。每步增加 ,而我们要从约 0 走到 π/2(即 |w⟩ 所在轴),大约需要

(π/2) / (2θ) ≈ (π/4)·√N 次迭代。

这正说明 Grover 是周期性的、而非单调的:一旦越过最优点继续迭代,状态会转 |w⟩,成功概率随之回落。多采几次有用,多迭代几次没用。

两个算子

算子作用
谕示(相位翻转)翻转中奖项振幅的符号|w⟩ → −|w⟩,其余不变。它只是识别答案,并不揭示或"知道"答案。
扩散(关于均值翻转)把每个振幅关于其平均值做反射。谕示先把中奖项压到均值以下,这次反射便将它高高抬到其余项之上。

谕示接扩散 = 一次 2θ 旋转。这一对操作反复施加,就是算法的引擎。

识别而非知晓
谕示不过是一个高效的"这是不是解"的判定。Grover 从不需要谁来告诉它答案——若你早已知道中奖项,就无需搜索了。这也正是它适用于哈希求逆、SAT 赋值校验这类问题的原因:验证一个猜测很便宜,找到一个却很难。

它擅长什么 又不擅长什么

  • 平方级而非指数级。Grover 不像 Shor 破解大数分解那样"攻破"难题,它只是把暴力搜索的代价开了个平方根。
  • 谕示必须是廉价的量子函数。把 N 条无结构经典记录装进谕示本身就要 O(N)——那会抵消加速。真正的收益在于谕示是一条紧凑规则(哈希、约束校验),而非一张字面意义的数据库表。
  • 它已被证明最优。对真正无结构的搜索,没有量子算法能突破 O(√N),所以这是该问题的终点,而非通往更快方法的跳板。
  • 它可推广。这套"反射加旋转"的手法称为振幅放大,是众多更大算法内部可复用的构件。

算法逐步拆解

  1. 用 Hadamard 门制备均匀叠加态——即起始态 |s⟩
  2. 施加谕示,翻转目标态的相位。
  3. 施加扩散算子放大目标态的振幅(一次 2θ 旋转)。
  4. 重复约 (π/4)·√N 次(取最接近的整数)后测量。

对照代码理解

下面的内核把目标态设为全 1 串 11…1。请对照上文原理来读:h(q) 构建均匀叠加;多控 z.ctrl(...) 是对该单一状态做相位翻转的谕示;h(q); x(q) … x(q); h(q) 这段夹层即扩散算子;迭代次数通常取最接近 (π/4)·√N 的整数。更精确地,最优次数为 k ≈ round(π/(4θ) − 1/2)——取最接近的整数,因为成功概率 sin²((2k+1)θ) 在 k = π/(4θ) − 1/2 处取峰值——其中 sin θ = 1/√N

该实现与标准扩散算子 D = 2|s⟩⟨s| − I 至多相差一个全局相位或等价约定,不影响最终测量概率。

示例假定 n ≥ 2;对于 n = 1,多控门的空控制列表语义取决于具体框架。

import qalgora, math

@qalgora.kernel
def grover(n: int, iterations: int):
    q = qalgora.qvector(n)
    h(q)
    for _ in range(iterations):
        # oracle: mark the all-ones state
        z.ctrl(q[0:n-1], q[n-1])
        # diffusion operator
        h(q); x(q)
        z.ctrl(q[0:n-1], q[n-1])
        x(q); h(q)
    mz(q)

n = 3
iters = round(math.pi / 4 * math.sqrt(2 ** n))
print(qalgora.sample(grover, n, iters))   # peaks at "111"
动手试试
iters 调离最优值,观察 "111" 峰随之变矮——这是对 Grover 周期性最直接的动手演示。相位估计QAOA 页面复用了同样的叠加与干涉思想。

参考文献

  • L. K. Grover, "A fast quantum mechanical algorithm for database search," Proc. 28th ACM STOC, 212-219 (1996). arXiv:quant-ph/9605043