Shor's Algorithm
Factor an integer in polynomial time by reducing factoring to order-finding, solved with the quantum phase estimation of a modular-multiplication operator. It turns a problem that underpins modern public-key cryptography into a periodicity question a quantum computer can solve efficiently.
The problem it solves
Factoring a large integer N into its prime factors is a famously hard classical
problem. The best known classical method (the general number-field sieve) runs in
sub-exponential time — better than purely exponential, but nowhere near polynomial. RSA's
security relies on the practical hardness of factoring large semiprimes for classical computers:
publish N, and trust that no one can recover its two prime factors in any feasible
amount of time.
Shor's algorithm drops the quantum cost of factoring N to a
polynomial in the number of bits n = log₂N. This is not a quadratic
speedup — it is a jump from sub-exponential to polynomial, and that is exactly why it is so
disruptive for cryptography.
| Bit length n | Classical (number-field sieve, rough) | Shor (polynomial) |
|---|---|---|
| 1024 | extremely expensive | polynomial (~n³, implementation-dependent) |
| 2048 | currently considered infeasible | polynomial (~n³, implementation-dependent) |
Note the classical cost above is sub-exponential, not truly exponential; the point of the comparison is the class of growth — Shor pushes the curve into the polynomial regime.
The key idea — reducing factoring to period-finding
Shor's real trick is a purely classical reduction: factoring N is equivalent to finding
the period of a function. Pick any a coprime to N and look at
the sequence
a⁰, a¹, a², a³, … (mod N)
This sequence is necessarily periodic. The smallest positive r that brings it back to 1
— the r with a^r ≡ 1 (mod N) — is called the order of
a mod N. Once you know r, the rest is schoolbook algebra: if
r is even then a^r − 1 = (a^(r/2) − 1)(a^(r/2) + 1) is a multiple of
N, so gcd(a^(r/2) ± 1, N) very likely exposes a non-trivial factor.
The hard part has therefore been compressed into one thing: finding the period r. A classical computer cannot do this (finding the period is as hard as factoring), but a quantum computer can — which is where phase estimation enters.
How the quantum part finds the period
Define the unitary U|y⟩ = |a·y mod N⟩, "multiply by a". Its eigenvalues all
have the form e^(2πi·s/r), and the denominator of that phase s/r hides exactly
the order r we want. So finding the order becomes
quantum phase estimation on U.
The circuit prepares a uniform superposition on a counting register, applies a ladder of controlled
U^(2^j) — which amount to modular exponentiation a^(2^j) mod N — to
kick the phase information onto the counting qubits, and reads it out with an inverse QFT. The measured
bitstring approximates 2ⁿ·(s/r). Feeding that fraction to the classical
continued-fractions expansion recovers the denominator r from that rational
approximation.
Why it works — and why it retries
Shor's algorithm is probabilistic, with a few ways to miss, each of them mild:
- Phase estimation may not return the best approximation to
s/r— take more shots. - The recovered
rmay be odd, or satisfya^(r/2) ≡ −1 (mod N)— that round is useless, so pick a newaand start over. (The casea^(r/2) ≡ +1cannot arise for evenr: it would contradictrbeing the least period, so it is automatically excluded — leaving≡ −1as the only extra failure mode.) - One can prove that a randomly chosen
aavoids both bad cases with probability at least 1/2, so only a constant number of rounds is needed on average.
What it is — and isn't — good for
- It genuinely "breaks" factoring. Unlike Grover's quadratic speedup, Shor moves factoring from sub-exponential to polynomial. Shor's integer-factoring version threatens RSA; its discrete-logarithm version threatens Diffie–Hellman, DSA, ECDH, and ECDSA — schemes based on the (elliptic-curve) discrete-logarithm problem.
- It needs fault tolerance. The controlled modular-exponentiation circuit is deep and wide; factoring a real 2048-bit key needs thousands of logical qubits, hence millions of error-corrected physical qubits. That is far beyond today's hardware — which is why "post-quantum cryptography" is being deployed now.
- It is highly specialised. The whole machine is built for periodicity; it is not a general accelerator and does not transfer to unstructured search or generic optimisation.
- It is hybrid by nature. The quantum part only finds the period; the continued-fraction post-processing and gcd are classical.
The algorithm, step by step
- Pick a random
acoprime toN. - Use phase estimation to find the order
rofamodN. - A randomly chosen
asatisfies both conditions (reven anda^(r/2) ≢ −1 (mod N)) with probability ≥ 1/2. Sinceris the least positive order ofamodN, an evenrautomatically givesa^(r/2) ≢ 1 (mod N)(otherwiser/2would already be a period); the only bad even case isa^(r/2) ≡ −1. When the conditions hold,gcd(a^(r/2) − 1, N)orgcd(a^(r/2) + 1, N)necessarily yields a non-trivial factor ofN. Otherwise pick a newaand repeat.
Seeing it in code
The skeleton below shows the structure of the order-finding subroutine. Read it against the theory
above: cq is the counting register, and h(cq) puts it in superposition to hold
the phase; wq is the work register holding |y⟩, initialised to |1⟩
by x(wq[0]); the commented placeholder for controlled modular exponentiation is exactly the
ladder of controlled U^(2^j) operators; an inverse QFT on the counting register and a
measurement follow. The measured result is handed to classical continued fractions to recover the order
r, and from it the factors of 15.
import qalgora
@qalgora.kernel
def order_finding(counting: int, work: int, a: int, N: int):
cq = qalgora.qvector(counting)
wq = qalgora.qvector(work)
h(cq)
x(wq[0])
# controlled modular exponentiation a^(2^j) mod N ...
# inverse QFT on the counting register
mz(cq)
counts = qalgora.sample(order_finding, 8, 4, 7, 15)
# classical post-processing: continued fractions -> order r -> factors of 15
This is not a complete Shor implementation — it only shows the structure of the quantum
order-finding circuit. A runnable version still needs the controlled modular exponentiation
U^(2ʲ), the inverse QFT, and classical continued-fraction post-processing.
References
- P. W. Shor, "Polynomial-time algorithms for prime factorization and discrete logarithms on a quantum computer," SIAM J. Comput. 26(5), 1484-1509 (1997). arXiv:quant-ph/9508027
Shor 算法
通过将因子分解问题归约为求阶问题,以多项式时间分解整数;求阶借助模乘算子的量子相位估计来完成。它把一个支撑现代公钥密码的难题,转化为量子计算机能高效求解的周期性问题。
它解决的问题
把一个大整数 N 分解成它的素因子,是经典计算中公认的难题。已知最好的经典算法(一般数域筛法)的运行时间是亚指数级的——比纯指数好,却远谈不上多项式。RSA 的安全性依赖于经典计算机难以对大半素数进行因式分解这一实际困难:公开 N,并相信无人能在可行时间内还原其两个素因子。
Shor 算法把分解 N 所需的量子操作数降到关于比特位数 n = log₂N 的多项式级。这不是平方级加速,而是从亚指数到多项式的质变——这正是它对密码学具有颠覆性意义的根源。
| 比特位数 n | 经典(数域筛法,约略) | Shor(多项式) |
|---|---|---|
| 1024 | 极其昂贵 | 多项式(约 n³,取决于实现) |
| 2048 | 当前公认不可行 | 多项式(约 n³,取决于实现) |
请注意:表中的经典代价并非真正的指数,而是亚指数;关键对照在于增长的类别——Shor 把曲线压进了多项式区间。
核心洞见 把分解归约为求周期
Shor 真正的妙处,是一步纯经典的归约:分解 N 等价于求某个函数的周期。任取一个与 N 互质的 a,考察数列
a⁰, a¹, a², a³, … (mod N)
这个数列必然是周期性的。使它回到 1 的最小正整数 r——即满足 a^r ≡ 1 (mod N) 的 r——称为 a 模 N 的阶。一旦求得 r,剩下的全是中学代数:若 r 为偶数,则 a^r − 1 = (a^(r/2) − 1)(a^(r/2) + 1) 是 N 的倍数,于是 gcd(a^(r/2) ± 1, N) 极可能给出一个非平凡因子。
难点因此被压缩成唯一一件事:求周期 r。经典计算机做不到这一点(找周期本身就和分解一样难),但量子计算机可以——这正是相位估计登场之处。
量子如何求出周期
定义幺正算符 U|y⟩ = |a·y mod N⟩,即"乘以 a"。它的本征值都形如 e^(2πi·s/r),相位 s/r 的分母里恰好藏着我们要的阶 r。于是求阶就变成了对 U 做量子相位估计。
线路在计数寄存器上制备均匀叠加,再施加一串受控的 U^(2^j)——它们等效于模幂运算 a^(2^j) mod N——把相位信息踢回到计数比特上,最后用逆 QFT 读出。测量得到的比特串近似于 2ⁿ·(s/r)。把这个分数交给经典的连分数展开,就能从这个有理逼近中还原出分母 r。
为何成功 又为何会失败重试
Shor 算法是概率性的,存在几处可能落空,但每一处都很温和:
- 相位估计返回的可能不是
s/r的最佳逼近——多采几次即可。 - 求得的
r可能是奇数,或满足a^(r/2) ≡ −1 (mod N)——此时该轮无用,另取一个a重来。(a^(r/2) ≡ +1与「r为最小周期」矛盾,对偶数r自动排除,因此唯一的额外失败模式就是≡ −1。) - 可以证明,随机选取的
a让上述两个坏情况同时落空的概率至少为 1/2,故期望只需常数轮即可成功。
它擅长什么 又不擅长什么
- 它真正"攻破"了分解问题。与 Grover 仅做平方级加速不同,Shor 把分解从亚指数推进到多项式。Shor 算法的整数分解版本威胁 RSA;其离散对数版本威胁 Diffie-Hellman、DSA、ECDH、ECDSA 等基于离散对数或椭圆曲线离散对数的问题。
- 它需要容错。受控模幂线路又深又宽;要分解一个真实的 2048 位密钥,需要数千个逻辑比特,进而需要数百万个带纠错的物理比特。这远超当前硬件,正是"后量子密码"今天就要部署的原因。
- 它高度专一。整套机制是为周期性问题量身打造的;它不是通用加速器,无法直接搬到无结构搜索或一般优化上。
- 混合是其本性。量子部分只负责求周期;连分数后处理与 gcd 计算都是经典的。
算法逐步拆解
- 随机选取与
N互质的a。 - 用相位估计求
a模N的阶r。 - 随机选取的
a满足两个条件(r为偶数且a^(r/2) ≢ −1 (mod N))的概率 ≥ 1/2。由于r是a模N的最小正阶,若r为偶数,则通常不会有a^(r/2) ≡ 1 (mod N),否则r/2已是周期;唯一的坏情况是a^(r/2) ≡ −1。此时gcd(a^(r/2) − 1, N)与gcd(a^(r/2) + 1, N)中至少一个给出非平凡因子;否则另取一个a重试。
对照代码理解
下面的骨架展示求阶子程序的结构。请对照上文原理来读:cq 是计数寄存器,h(cq) 在其上制备叠加态以承载相位;wq 是承载 |y⟩ 的工作寄存器,x(wq[0]) 将其初始化为 |1⟩;被注释占位的受控模幂正是 U^(2^j) 这串受控算子;随后对计数寄存器施加逆 QFT 并测量。测量结果交由经典连分数处理,还原出阶 r,进而得到 15 的因子。
import qalgora
@qalgora.kernel
def order_finding(counting: int, work: int, a: int, N: int):
cq = qalgora.qvector(counting)
wq = qalgora.qvector(work)
h(cq)
x(wq[0])
# controlled modular exponentiation a^(2^j) mod N ...
# inverse QFT on the counting register
mz(cq)
counts = qalgora.sample(order_finding, 8, 4, 7, 15)
# classical post-processing: continued fractions -> order r -> factors of 15
该代码不是完整的 Shor 实现,只展示量子求阶线路的结构;真正可运行的版本还需补全受控模幂 U^(2ʲ)、逆 QFT,以及经典连分数后处理。
参考文献
- P. W. Shor, "Polynomial-time algorithms for prime factorization and discrete logarithms on a quantum computer," SIAM J. Comput. 26(5), 1484-1509 (1997). arXiv:quant-ph/9508027