Shor's Factoring Algorithm

Factoring a large integer is the quiet hardness assumption that most of the internet trusts. The best classical algorithm known — the general number field sieve — needs time exp⁡ ⁣(O(n1/3(log⁡n)2/3))\exp\!\big(O(n^{1/3}(\log n)^{2/3})\big) to split an nn-bit modulus, subexponential yet stubbornly superpolynomial, and RSA, the workhorse of public-key cryptography, is safe only for as long as nobody does better. In 1994 Peter Shor did better, and by an exponential margin: a quantum algorithm that factors in time polynomial in nn. The result did not just add an entry to a complexity table; it redrew the map of what a computer is, and it is the reason "post-quantum cryptography" is a funded field rather than a thought experiment. The algorithm is a hinge between two worlds. Almost all of it is ordinary number theory: to factor NN, pick a random base aa, and — unless you get lucky and gcd⁡(a,N)\gcd(a,N) is already a factor — find the multiplicative order rr of aa modulo NN, the smallest rr with ar≡1a^r\equiv 1. From an even rr with ar/2≢−1a^{r/2}\not\equiv-1, a difference of squares hands you gcd⁡(ar/2±1, N)\gcd(a^{r/2}\pm1,\,N), two nontrivial factors, in a few lines of Euclid. The one step no classical machine can do quickly is finding rr, because the period of x↦ax  Nx\mapsto a^x\bmod N hides the factorization. That single step is the quantum computer's entire job. Quantum mechanically, rr stops being a needle in an exponential haystack and becomes a global phase pattern. The operator "multiply by aa" has eigenvalues e2πis/re^{2\pi i s/r}; quantum phase estimation reads one, the inverse quantum Fourier transform sharpens it into a measurement peak, and continued fractions strip the unknown numerator to expose rr. This article assembles that pipeline from its named prerequisites — the QFT, phase estimation, order finding — and shows why it is the flagship instance of the abelian hidden subgroup problem.

Key takeaways
  • Shor's algorithm factors an nn-bit integer in time O(n2log⁡nlog⁡log⁡n)O(n^2\log n\log\log n) on a quantum computer — an exponential speedup over every classical method known.
  • The engine is a classical reduction: factoring reduces, with probability ≥12\ge \tfrac12 per random base, to finding the multiplicative order rr of aa modulo NN.
  • The quantum core solves order finding by phase estimation on the modular-multiplication unitary Ua∣y⟩=∣ay  N⟩U_a\lvert y\rangle=\lvert ay\bmod N\rangle, whose eigenvalues e2πis/re^{2\pi i s/r} carry the period.
  • You never build an eigenstate: the trivial state ∣1⟩\lvert 1\rangle is an equal superposition of all rr of them, so one run samples a random ss and the same circuit works without knowing rr.
  • The measured estimate of s/rs/r is post-processed by continued fractions to recover rr exactly; this demands a phase register of t≈2n+1t\approx 2n+1 qubits so that Q=2t≥N2Q=2^t\ge N^2.
  • Breaking RSA is the headline, but order finding is also discrete log, Diffie–Hellman, and elliptic-curve crypto — all abelian hidden subgroup problems solved by one Fourier-sampling template.
  • Key idea: Factoring reduces to finding the period rr of x↦ax  Nx\mapsto a^x\bmod N; the quantum Fourier transform reads that period out of a uniform superposition in one shot, turning an exponentially hard classical search into polynomial-time phase estimation on the modular-multiplication operator.
The core insight

Factoring reduces to finding the period rr of x↦ax  Nx\mapsto a^x\bmod N; the quantum Fourier transform reads this period out of a uniform superposition in one shot, turning an exponentially hard classical search into polynomial-time phase estimation on the modular-multiplication operator.

Where this lives today

Shor's algorithm is at once a laboratory demonstration, an engineering target, and a policy driver. Experimentally it has been shown but never scaled: a 2001 nuclear-magnetic-resonance experiment factored 15=3×515=3\times5 on seven spins, and later photonic and ion-trap demonstrations repeated small cases — but every published "factoring" of a large number is either a compiled special case exploiting the known answer or a different algorithm entirely, not honest scalable Shor. The number that matters is the resource estimate: the Gidney–Ekerå analysis (2021) puts a 2048-bit RSA break at roughly 2020 million noisy physical qubits running about 88 hours under surface-code error correction — thousands of logical qubits and 10910^9–101010^{10} Toffoli gates. That is far beyond present devices, but it is a concrete, shrinking target, and the modular-exponentiation arithmetic dominating it is where circuit-optimization research now concentrates. The consequences are already operational. Because "harvest now, decrypt later" — recording encrypted traffic today to break it once hardware matures — turns a future capability into a present risk, standards bodies have moved: in 2024 NIST finalized its first post-quantum cryptography standards (lattice-based ML-KEM and ML-DSA, hash-based SLH-DSA), and migration away from RSA and elliptic-curve schemes is underway across governments and industry. Meanwhile the algorithm's descendants define a frontier: order finding is the abelian hidden subgroup problem for Z\mathbb{Z}, discrete log is the HSP for Z×Z\mathbb{Z}\times\mathbb{Z}, and the open question of efficient nonabelian HSP algorithms — bearing on graph isomorphism (symmetric group) and lattice problems (dihedral group) — takes Shor's success as both its inspiration and its stubborn limit.

The physical picture

Think of f(x)=ax  Nf(x)=a^x\bmod N as a periodic signal whose hidden period is exactly the number the algorithm wants. A quantum computer evaluates ff on every input at once, entangling a label of xx with the value f(x)f(x) in one pass of reversible arithmetic. Ignore the value register and the input register collapses onto a single arithmetic progression {x0, x0+r, x0+2r,… }\{x_0,\,x_0+r,\,x_0+2r,\dots\} — one period's worth of the comb. The quantum Fourier transform of a comb of spacing rr is itself a comb, but of spacing Q/rQ/r: the period, invisible in the values, reappears as sharp interference peaks. No individual function value was ever examined; only the global periodicity survived. The phase-estimation viewpoint is cleaner, and the one this article builds on. The operator UaU_a — multiply a residue by aa, modulo NN — is a permutation of the residues, and a permutation whose cycles have length rr has eigenvalues that are rr-th roots of unity, e2πis/re^{2\pi i s/r}. Estimate one eigenvalue's phase and you have measured a fraction s/rs/r; run it through continued fractions and the unknown numerator ss falls away, leaving rr. The genius of the construction is that you never have to prepare an eigenstate — which would require knowing rr first. The residue 11, trivial to write down, is an exactly equal superposition of all rr eigenstates, so one run samples a uniformly random ss for free. The first figure lays out this two-register circuit; the second shows the interference comb it produces.

Figure
The Shor circuit: a phase register of t ≈ 2n+1 qubits is put in uniform superposition, drives a controlled modular exponentiation that writes aˣ mod N into the lower register, then the inverse QFT concentrates the amplitude so the measured y ≈ sQ per r, with Q = 2ᵗ ≥ N²
Two registers: phase estimation on U_a drives order finding phase register t ≈ 2n+1 value register n qubits 0…0 H⊗ᵗ modular exponentiation aˣ mod N QFT⁻¹ y ≈ sQ/r 1 prepare uniform superposition continued fractions → r, Q = 2ᵗ ≥ N²

Where the comb's teeth land is set entirely by number theory, and one instance shows the mechanism sharply. Take N=15N=15, a=7a=7: the powers of 77 mod 1515 cycle 7,4,13,1,…7,4,13,1,\dots, so r=4r=4; with t=8t=8 qubits, Q=256≥N2=225Q=256\ge N^2=225, and the post-QFT distribution is four sharp peaks at y=sQ/r=64sy=sQ/r=64s. Reading y=64y=64 gives 1/41/4, whose continued-fraction denominator is r=4r=4 — done in one shot. The second figure is that exact distribution, the payoff picture of the whole algorithm.

Figure
Post-QFT measurement distribution for N = 15, a = 7 with r = 4 and Q = 256: because r divides Q the comb is four exact peaks at y = sQ/r = 0, 64, 128, 192, each with probability 1/4; the coprime outcomes y = 64 and y = 192 return r = 4 through continued fractions, the outcome y = 128 gives only the divisor 2, and y = 0 is uninformative
The interference comb — N = 15, a = 7, r = 4, Q = 256: peaks at y = sQ/r 0.25 probability 0 64 128 192 256 measured value y of the phase register 1/4 → r=4 1/2 → r=2 3/4 → r=4 0/1

The core equations

The whole algorithm rests on one classical fact — that the order gives up the factors — and one quantum fact — that phase estimation gives up the order. Start with the classical bridge, which is elementary number theory: an even order with a non-trivial square root of unity yields factors by a difference of squares.

gcd⁡ ⁣(ar/2−1, N) and gcd⁡ ⁣(ar/2+1, N) are nontrivial factors of N(1)\gcd\!\big(a^{r/2}-1,\,N\big)\ \text{and}\ \gcd\!\big(a^{r/2}+1,\,N\big)\ \text{are nontrivial factors of } N \qquad (1)

where: NN — composite integer to factor, n=⌈log⁡2N⌉n=\lceil\log_2 N\rceil bits; aa — random base with 1<a<N1<a<N and gcd⁡(a,N)=1\gcd(a,N)=1; rr — multiplicative order of aa mod NN, the least r≥1r\ge1 with ar≡1a^r\equiv1. Reading: given a good aa (even rr, ar/2≢−1a^{r/2}\not\equiv-1), two Euclid gcds finish the factoring in O(n2)O(n^2) classical work. The quantum side needs an operator whose spectrum stores rr. Multiplication by aa modulo NN is a bijection of residues, hence a unitary permutation, and it is the object phase estimation acts on.

Ua ∣y⟩=∣ay  N⟩,0≤y<N(2)U_a\,\lvert y\rangle = \lvert a y \bmod N\rangle,\qquad 0\le y<N \qquad (2)

where: UaU_a — permutation operator on residues, unitary because multiplication by a unit aa is invertible mod NN; ∣y⟩\lvert y\rangle — computational basis state labelling residue yy. Reading: UaU_a moves along the cycle 1→a→a2→⋯1\to a\to a^2\to\cdots, closing after exactly rr steps. Because that cycle has length rr, the operator's eigenstates are discrete Fourier modes over the cycle, and their eigenvalues are the rr-th roots of unity — the period, encoded directly in a phase.

∣us⟩=1r∑k=0r−1e−2πisk/r ∣ak  N⟩,Ua∣us⟩=e2πis/r∣us⟩(3)\lvert u_s\rangle = \frac{1}{\sqrt r}\sum_{k=0}^{r-1} e^{-2\pi i s k/r}\,\lvert a^k\bmod N\rangle,\qquad U_a\lvert u_s\rangle = e^{2\pi i s/r}\lvert u_s\rangle \qquad (3)

where: ∣us⟩\lvert u_s\rangle — eigenstate indexed by s∈{0,…,r−1}s\in\{0,\dots,r-1\}; e2πis/re^{2\pi i s/r} — eigenvalue, an rr-th root of unity. Reading: phase estimation on ∣us⟩\lvert u_s\rangle would return the fraction s/rs/r — but preparing ∣us⟩\lvert u_s\rangle needs rr, the very unknown. The escape is that the residue 11 is already an equal superposition over all rr eigenstates, so it needs no knowledge of rr at all.

1r∑s=0r−1∣us⟩=∣1⟩(4)\frac{1}{\sqrt r}\sum_{s=0}^{r-1}\lvert u_s\rangle = \lvert 1\rangle \qquad (4)

where: ∣1⟩\lvert 1\rangle — computational basis state for residue 11, trivially prepared. Reading: feed ∣1⟩\lvert 1\rangle into phase estimation and each run collapses onto one random ∣us⟩\lvert u_s\rangle, sampling ss uniformly from {0,…,r−1}\{0,\dots,r-1\}. Running phase estimation is running the modular exponentiation controlled on a superposed exponent, which produces the entangled comb state that the inverse QFT will read.

∣ψ⟩=1Q∑x=0Q−1∣x⟩ ∣ax  N⟩,Q=2t,  t≈2n+1(5)\lvert\psi\rangle = \frac{1}{\sqrt Q}\sum_{x=0}^{Q-1}\lvert x\rangle\,\lvert a^x\bmod N\rangle,\qquad Q=2^t,\ \ t\approx 2n+1 \qquad (5)

where: QQ — size of the phase register, chosen Q≥N2Q\ge N^2; tt — qubits in the phase register, t=⌈log⁡2Q⌉t=\lceil\log_2 Q\rceil. Reading: this one line does exponentially many evaluations of axa^x in superposition; everything after is interference, not further arithmetic. Applying the inverse QFT and measuring concentrates the amplitude near integer multiples of Q/rQ/r — the interference comb of the second figure.

Pr⁡[measure y]=1rQ∣∑j=0m−1e2πi jry/Q∣2 → Q→∞  peaks at y≈sQr(6)\Pr[\text{measure } y] = \frac{1}{rQ}\left|\sum_{j=0}^{m-1} e^{2\pi i\,jr y/Q}\right|^2 \ \xrightarrow{\ Q\to\infty\ }\ \text{peaks at } y\approx\frac{sQ}{r} \qquad (6)

where: yy — measured value of the phase register; m≈Q/rm\approx Q/r — number of terms in the collapsed progression; ss — the random integer 0≤s<r0\le s<r selected by that run. Reading: the geometric sum is O(m)O(m) only when ry/Qry/Q is near an integer, so measurement lands on the tooth nearest sQ/rsQ/r with high probability. Dividing yy by QQ gives an approximation to s/rs/r; continued fractions recover the exact fraction, but only if the register is large enough that no other fraction with denominator below NN is as close.

∣yQ−sr∣≤12Q≤12N2 ⇒ sr is the unique convergent of yQ with denominator<N(7)\left|\frac{y}{Q}-\frac{s}{r}\right|\le\frac{1}{2Q}\le\frac{1}{2N^2}\ \Rightarrow\ \frac{s}{r}\ \text{is the unique convergent of}\ \frac{y}{Q}\ \text{with denominator}<N \qquad (7)

where: y/Qy/Q — measured fraction fed to the continued-fraction algorithm; s/rs/r — target rational, in lowest terms exactly when gcd⁡(s,r)=1\gcd(s,r)=1. Reading: this is why t≈2n+1t\approx 2n+1 — the resolution 1/(2Q)1/(2Q) must beat the 1/(2N2)1/(2N^2) gap between distinct fractions of denominator <N<N. Finally, the cost. The QFT is cheap (O(n2)O(n^2)); the bill is the modular exponentiation, a ladder of controlled modular multiplications.

∣x⟩∣y⟩→ ∏jC-Ua2j ∣x⟩ ∣y ax  N⟩,TShor=O ⁣(n2log⁡nlog⁡log⁡n)(8)\lvert x\rangle\lvert y\rangle \xrightarrow{\ \prod_j C\text{-}U_a^{2^j}\ } \lvert x\rangle\,\big\lvert y\,a^x\bmod N\big\rangle,\qquad T_{\text{Shor}}=O\!\big(n^2\log n\log\log n\big) \qquad (8)

where: C-Ua2jC\text{-}U_a^{2^j} — controlled multiplication by a2j  Na^{2^j}\bmod N, conditioned on exponent bit xjx_j; TShorT_{\text{Shor}} — total gate count with fast (Schönhage–Strassen) integer multiplication. Reading: O(n)O(n) modular multiplications each costing O(n2)O(n^2) give O(n3)O(n^3) with schoolbook arithmetic, dropping to O(n2log⁡nlog⁡log⁡n)O(n^2\log n\log\log n) with fast multiplication — polynomial, and that is the whole point.

Derivation AFrom the order to the factors

The goal of this first derivation is to justify equation (1) completely — to show precisely why knowing the order rr of a random base aa lets ordinary greatest-common-divisor arithmetic split NN, and to pin down exactly which two conditions on rr make the trick work. Everything here is classical; not a single qubit appears. The plan is to start from the defining congruence of the order, factor a difference of squares, and then argue that a common factor with NN must be non-trivial precisely when rr is even and ar/2a^{r/2} is not the "boring" square root −1-1 of unity.

Step 1. By definition of the order, ar≡1(modN)a^r\equiv 1\pmod N, so NN divides ar−1a^r-1. Why: the order is the exact period of the powers of aa, so ar−1a^r-1 is the first power difference that NN cleanly divides — the anchor the rest of the argument hangs from.

Step 2. Assume rr is even and write ar−1=(ar/2−1)(ar/2+1)a^r-1=(a^{r/2}-1)(a^{r/2}+1); then NN divides the product (ar/2−1)(ar/2+1)(a^{r/2}-1)(a^{r/2}+1). Why: the difference of squares is the whole mechanism — it splits the quantity NN divides into two explicit integers, and any prime of NN must land in one of them.

Step 3. Now ar/2≢1(modN)a^{r/2}\not\equiv 1\pmod N, because r/2<rr/2<r and rr is the least exponent giving 11; assume also the favourable case ar/2≢−1(modN)a^{r/2}\not\equiv -1\pmod N. Why: if ar/2≡±1a^{r/2}\equiv\pm1 then one factor is ≡0\equiv0 and the other carries all of NN, so the gcds return only 11 and NN — these are exactly the two "bad-base" failure modes the reduction must dodge.

Step 4. Since NN divides neither ar/2−1a^{r/2}-1 nor ar/2+1a^{r/2}+1 individually, yet divides their product, NN shares a proper factor with each; hence gcd⁡(ar/2−1,N)\gcd(a^{r/2}-1,N) and gcd⁡(ar/2+1,N)\gcd(a^{r/2}+1,N) are non-trivial, computed in O(n2)O(n^2) by Euclid. Why: a prime power pm∥Np^m\parallel N cannot sit entirely inside a factor that NN fails to divide, so its parts distribute across the two gcds — this is the difference of squares delivering the split concretely. *Verified: N=15, a=7, r=4, ar/2=4N=15,\,a=7,\,r=4,\,a^{r/2}=4 gives gcd⁡(3,15)=3\gcd(3,15)=3 and gcd⁡(5,15)=5\gcd(5,15)=5; the bad base a=14a=14 has ar/2=14≡−1a^{r/2}=14\equiv-1 and returns only 11 and 1515.*

Go deeper · Derivation B · 1 minWhy the trivial state 1 phase-estimates the period
Derivation BWhy the trivial state 1 phase-estimates the period

This derivation resolves the apparent circularity at the heart of Shor's construction: phase estimation reads the eigenphase s/rs/r of an eigenstate ∣us⟩\lvert u_s\rangle, yet every ∣us⟩\lvert u_s\rangle is defined in terms of the unknown rr, so how can one prepare the input without already solving the problem. The goal is to prove equation (4) — that the equal superposition of all rr eigenstates collapses to the single computational basis state ∣1⟩\lvert 1\rangle — so that the algorithm runs on a state anyone can prepare, and each run silently samples a uniformly random ss. The plan is to sum the eigenstate definitions over ss, swap the order of summation, and evaluate the resulting geometric sum.

Step 1. Sum equation (3) over ss and interchange the two sums: 1r∑s∣us⟩=1r∑k=0r−1(∑s=0r−1e−2πisk/r)∣ak  N⟩\frac{1}{\sqrt r}\sum_{s}\lvert u_s\rangle=\frac{1}{r}\sum_{k=0}^{r-1}\big(\sum_{s=0}^{r-1}e^{-2\pi i sk/r}\big)\lvert a^k\bmod N\rangle. Why: pulling the kk-sum outside isolates a pure phase sum over ss for each fixed kk, which is a geometric series with a clean closed form.

Step 2. Evaluate the inner sum: ∑s=0r−1e−2πisk/r=r δk,0\sum_{s=0}^{r-1}e^{-2\pi i sk/r}=r\,\delta_{k,0}, zero for every k≢0k\not\equiv0 and rr for k=0k=0. Why: this is the discrete orthogonality of roots of unity — the same identity that makes the Fourier transform diagonalize cyclic shifts, here killing every basis term except one.

Step 3. Only k=0k=0 survives, leaving ∣a0  N⟩=∣1⟩\lvert a^0\bmod N\rangle=\lvert 1\rangle. Why: the entire equal superposition of eigenstates is nothing but the residue 11 in disguise, so preparing ∣1⟩\lvert 1\rangle is preparing 1r∑s∣us⟩\frac{1}{\sqrt r}\sum_s\lvert u_s\rangle without ever naming rr.

Step 4. Phase estimation is linear, so running it on ∣1⟩=1r∑s∣us⟩\lvert 1\rangle=\frac{1}{\sqrt r}\sum_s\lvert u_s\rangle produces the entangled sum 1r∑s∣s/r~⟩∣us⟩\frac{1}{\sqrt r}\sum_s\lvert \widetilde{s/r}\rangle\lvert u_s\rangle; measuring the phase register collapses one term, delivering a uniformly random ss. Why: linearity converts "superposition of eigenstates" into "random choice of eigenphase" at measurement — the one probabilistic step, and the reason a few repetitions suffice. *Verified: for r=4r=4 the four eigenphases are s/4∈{0,14,12,34}s/4\in\{0,\tfrac14,\tfrac12,\tfrac34\}; summing the four ∣us⟩\lvert u_s\rangle returns ∣1⟩\lvert 1\rangle, and equal sampling of ss matches the four equal peaks in the second figure.*

Go deeper · Derivation C · 2 minRegister size and continued-fraction recovery
Derivation CRegister size and continued-fraction recovery

The output of phase estimation is not rr but a noisy estimate y/Qy/Q of the fraction s/rs/r, and the final classical step must recover the exact rational from that approximation. The goal here is to derive the register-size rule t≈2n+1t\approx 2n+1 (equivalently Q≥N2Q\ge N^2) as the exact resolution needed for continued fractions to return s/rs/r uniquely, and to explain why an undersized register makes the answer ambiguous rather than merely imprecise. The plan is to bound the phase-estimation error, invoke the uniqueness theorem for continued-fraction convergents, and combine the two into a condition on QQ.

Step 1. With tt qubits, phase estimation returns the integer yy whose fraction y/Qy/Q is within 1/(2Q)1/(2Q) of the true s/rs/r with constant probability. Why: Q=2tQ=2^t is the grid spacing of representable phases, so the best estimate is off by at most half a grid cell — the resolution improves exponentially in tt, cheaply.

Step 2. A rational s/rs/r with r<Nr<N is the unique fraction of denominator below NN within 1/(2N2)1/(2N^2) of a given real, because two distinct fractions s/rs/r and s′/r′s'/r' with denominators <N<N differ by at least 1/(rr′)>1/N21/(rr')>1/N^2. Why: fractions of bounded denominator are spread apart by at least 1/N21/N^2, so any approximation closer than half that gap can match only one of them — this is the theorem that makes recovery deterministic.

Step 3. Demand the estimation resolution beat the fraction gap: 1/(2Q)≤1/(2N2)1/(2Q)\le 1/(2N^2), i.e. Q≥N2Q\ge N^2, hence t≥2nt\ge 2n; the standard choice t=2n+1t=2n+1 adds one bit of headroom for the constant success probability. Why: matching the two scales is exactly equation (7) — undersize the register and several fractions of denominator <N<N tie for closest, so continued fractions cannot decide and the readout is corrupted, not just coarse.

Step 4. Run the continued-fraction expansion of y/Qy/Q and take the last convergent with denominator below NN; its denominator is rr when gcd⁡(s,r)=1\gcd(s,r)=1, and a proper divisor of rr otherwise, cured by repetition. Why: the convergents of a continued fraction are provably the best rational approximations of bounded denominator, so the algorithm reads s/rs/r off directly — and a coprime ss, which occurs with probability φ(r)/r=Ω(1/log⁡log⁡r)\varphi(r)/r=\Omega(1/\log\log r), delivers rr itself. *Verified: N=15N=15 needs n=4n=4, N2=225N^2=225, so t=8t=8, Q=256Q=256 suffices; the outcome y=192y=192 gives 192/256=3/4192/256=3/4, whose convergent denominator is r=4r=4, while y=128y=128 gives 1/21/2 and only the divisor 22.*

Limiting cases

The algorithm's behaviour is governed by number-theoretic luck in the base aa and by correct sizing of the phase register:

CaseResultMeaning
Odd orderrr oddar/2a^{r/2} is not an integer power, so the factoring step (1) is undefined; this run is discarded and a fresh aa is drawn.
Trivial square rootar/2≡−1(modN)a^{r/2}\equiv -1\pmod NThe difference of squares gives only gcd⁡=1\gcd=1 and gcd⁡=N\gcd=N; another bad-base event cured by retrying.
Both good conditionsrr even, ar/2≢−1a^{r/2}\not\equiv-1Success: gcd⁡(ar/2±1,N)\gcd(a^{r/2}\pm1,N) split NN. For NN with k≥2k\ge2 distinct odd prime factors this holds with probability ≥1−2−(k−1)≥12\ge 1-2^{-(k-1)}\ge\tfrac12 per random aa.
Prime power N=pmN=p^mN=pmN=p^mOrder finding need not split cleanly, but prime powers are caught by a classical preprocessing test (is N1/bN^{1/b} an integer for b≤log⁡2Nb\le\log_2 N).
Even NN2∣N2\mid NTrivial — divide out factors of 22 classically before invoking the quantum routine at all.
Register too smallQ<N2Q<N^2Continued fractions cannot resolve s/rs/r uniquely; distinct fractions tie and the readout is ambiguous. Must use t≈2n+1t\approx 2n+1.

Worked examples

1 · Factoring 15 end to end (fully worked)

Factor N=15N=15 using the base a=7a=7: run the classical setup, state what the quantum order-finding subroutine returns, and finish the factoring — with every number explicit.

Step 1. Classical setup. Check gcd⁡(7,15)=1\gcd(7,15)=1, so 77 is a valid base and gives no free factor. The modulus has n=⌈log⁡215⌉=4n=\lceil\log_2 15\rceil=4 bits, so choose a phase register of t=8t=8 qubits: Q=28=256≥N2=225Q=2^8=256\ge N^2=225. The circuit uses an 8-qubit phase register.

Step 2. What order finding returns. The powers of 77 mod 1515 cycle 71=7, 72=4, 73=13, 74=17^1=7,\ 7^2=4,\ 7^3=13,\ 7^4=1, so the order is r=4r=4. The quantum subroutine does not know this in advance; it prepares ∣1⟩\lvert 1\rangle, runs controlled modular exponentiation, applies the inverse QFT, and measures. Because r=4r=4 divides Q=256Q=256 exactly, the outcome is one of four sharp peaks y∈{0,64,128,192}y\in\{0,64,128,192\}, each with probability 14\tfrac14. Measurement yields y∈{0,64,128,192}y\in\{0,64,128,192\}.

Step 3. Continued-fraction recovery. Suppose the run returns y=64y=64. Then y/Q=64/256=1/4y/Q=64/256=1/4, already in lowest terms, so the denominator is the candidate r=4r=4. Verify: 74=2401=160×15+1≡1(mod15)7^4=2401=160\times15+1\equiv1\pmod{15}. Good — r=4r=4 confirmed. (Had the run returned y=128y=128, giving 1/21/2, the candidate would be the divisor 22; verifying 72=49≡4≢17^2=49\equiv4\not\equiv1 rejects it, and one simply reruns. The outcomes 6464 and 192192 — a 12\tfrac12 chance — succeed immediately.) Recovered r=4r=4.

Step 4. Extract the factors. The order is even and ar/2=72=49≡4(mod15)a^{r/2}=7^2=49\equiv4\pmod{15}, which is neither 11 nor −1≡14-1\equiv14 — a good base. Apply equation (1): gcd⁡(4−1,15)=gcd⁡(3,15)=3\gcd(4-1,15)=\gcd(3,15)=\mathbf{3} and gcd⁡(4+1,15)=gcd⁡(5,15)=5\gcd(4+1,15)=\gcd(5,15)=\mathbf{5}. 15=3×515=3\times5.

2 · A larger period and a bad base (21)

Factor N=21N=21 with a=2a=2, then show what goes wrong for the base a=5a=5.

Step 1. Good base a=2a=2. Here gcd⁡(2,21)=1\gcd(2,21)=1. The powers 21=2, 22=4, 23=8, 24=16, 25=11, 26=1(mod21)2^1=2,\,2^2=4,\,2^3=8,\,2^4=16,\,2^5=11,\,2^6=1\pmod{21} give order r=6r=6 — even, and larger than the modest register would suggest, illustrating why t≈2n+1t\approx 2n+1 (here 2⋅5+1=112\cdot5+1=11 qubits, Q≥N2=441Q\ge N^2=441) is needed to resolve s/6s/6.

Step 2. Finish the factoring. With r=6r=6, ar/2=23=8(mod21)a^{r/2}=2^3=8\pmod{21}, and 8≢±18\not\equiv\pm1. Then gcd⁡(8−1,21)=gcd⁡(7,21)=7\gcd(8-1,21)=\gcd(7,21)=\mathbf{7} and gcd⁡(8+1,21)=gcd⁡(9,21)=3\gcd(8+1,21)=\gcd(9,21)=\mathbf{3}. 21=7×321=7\times3.

Step 3. Why a=5a=5 fails. The base 55 also has order r=6r=6 mod 2121 (powers 5,4,20,16,17,15,4,20,16,17,1), but now ar/2=53=125≡20≡−1(mod21)a^{r/2}=5^3=125\equiv20\equiv-1\pmod{21}. The difference of squares collapses: gcd⁡(20−1,21)=gcd⁡(19,21)=1\gcd(20-1,21)=\gcd(19,21)=1 and gcd⁡(20+1,21)=gcd⁡(21,21)=21\gcd(20+1,21)=\gcd(21,21)=21 — only the trivial factors. A bad base returns 11 and NN; discard and redraw aa. Because at least half of all valid bases are good, a handful of trials suffices.

Physics of the portrait

Shor's algorithm is the moment computer science reached into quantum mechanics and pulled out something no classical machine could match — and it did so by recognizing that a period, invisible to sampling, is a phase written across a superposition that interference can read.

Origins · 1 minPeter Shor and how this was discovered
PS
Peter Shor
born 1959 · quantum algorithms and complexity

Peter Williston Shor, an American mathematician then at AT&T Bell Laboratories, changed the stakes of quantum computing in a single 1994 paper. Before it, quantum computers were a curiosity with a few contrived speedups (Deutsch–Jozsa, Simon) over problems nobody cared about; Shor produced a polynomial-time algorithm for a problem the entire world's cryptography depended on being hard — integer factorization — and for its cousin, discrete logarithm. His insight braided three threads: the reduction of factoring to order finding, the quantum Fourier transform as an efficient circuit, and phase estimation on the modular-multiplication operator. The reaction was immediate and double-edged: it poured funding and talent into quantum computing and launched post-quantum cryptography as a defensive discipline. Shor's fingerprints are elsewhere too — the nine-qubit Shor code of 1995, the first quantum error-correcting code, showed quantum information could in principle be protected against decoherence, removing the last "in-principle-impossible" objection to scalable machines. He later moved to MIT. What makes the factoring result endure is its structure: it is the clean, canonical solution of the abelian hidden subgroup problem, and essentially every exponential-speedup quantum algorithm since is measured against its template.

History
1994
— Peter Shor presents the polynomial-time factoring and discrete-log algorithm at the FOCS conference
1995
— Shor introduces the nine-qubit code, the first quantum error-correcting code, and gives an approximate QFT
1996
— Ekert and Jozsa expose the order-finding and hidden-subgroup structure underlying the algorithm
1997
— Shor's expanded paper appears in the SIAM Journal on Computing
2001
— a seven-qubit nuclear-magnetic-resonance experiment factors 15 into 3 and 5

Going further

Texts. Nielsen & Chuang, Quantum Computation and Quantum Information, §5.2–5.3 (order finding and factoring) and Appendix 4 (the reduction-success bound) · Shor, "Polynomial-Time Algorithms for Prime Factorization and Discrete Logarithms on a Quantum Computer," SIAM J. Comput. 26, 1484 (1997) · Preskill, Lecture Notes for Physics 219, Ch. 6 · Kitaev, Shen & Vyalyi, Classical and Quantum Computation, Ch. 13 · Mermin, Quantum Computer Science, Ch. 3 · Watrous, The Theory of Quantum Information, lecture notes on factoring.

Provenance. The equations and complexity bounds follow Nielsen & Chuang Ch. 5 and Shor's 1997 paper. A verifier should recompute: the difference-of-squares step and the two Euclid gcds of equation (1); the eigenphase e2πis/re^{2\pi i s/r} of UaU_a and the orthogonality collapse ∑se−2πisk/r=rδk,0\sum_s e^{-2\pi i sk/r}=r\delta_{k,0} giving ∣1⟩=1r∑s∣us⟩\lvert 1\rangle=\frac{1}{\sqrt r}\sum_s\lvert u_s\rangle; the register condition 1/(2Q)≤1/(2N2)⇒Q≥N21/(2Q)\le1/(2N^2)\Rightarrow Q\ge N^2; the reduction-success bound ≥1−2−(k−1)\ge1-2^{-(k-1)} via the CRT two-adic-valuation argument (N&C Appendix 4 / Theorem 5.3); the worked instances N=15,a=7⇒r=4⇒{3,5}N=15,a=7\Rightarrow r=4\Rightarrow\{3,5\} and N=21,a=2⇒r=6⇒{7,3}N=21,a=2\Rightarrow r=6\Rightarrow\{7,3\}, including the bad base a=5a=5 mod 2121; and the O(n2log⁡nlog⁡log⁡n)O(n^2\log n\log\log n) gate count. Hardware resource figures (roughly 2020 million qubits / 88 hours for RSA-2048; NIST's 2024 PQC standards) are cited as reported estimates, not derived here.

Builds on: Quantum Fourier Transform · Quantum Phase Estimation · Order Finding and Period Finding · Quantum Parallelism and the Oracle Model. Leads to: Quantum Discrete Logarithm Algorithm · Hidden Subgroup Problem · Simon's Algorithm.

Ask the tutor: Ask me to walk you through factoring your own small NN — pick a base, and we will find its order, draw the interference comb, and read the factors off together.

Does Shor's algorithm try all the factors of N at once in superposition?

No — that is the wrong model, and the one to unlearn first. The quantum computer never tests candidate divisors. It solves a different problem, order finding: given the base aa, it finds the period rr of a0,a1,a2,…a^0,a^1,a^2,\dots modulo NN. The "parallelism" is real but subtle — the circuit evaluates axa^x for all xx at once, entangling xx with ax  Na^x\bmod N — yet you cannot read those values out; measurement gives one useless random pair. What survives is a global property, the period, which the QFT converts into a measurable interference pattern. Factoring then follows classically from the period, not from any parallel division.

Where exactly is the exponential speedup — the QFT is only quadratic?

The QFT is not the source of the speedup, which surprises many people. It costs only O(n2)O(n^2) gates, no faster asymptotically than the modular exponentiation it accompanies. The speedup lives in the problem framing: classically, detecting the period of ax  Na^x\bmod N seems to need exponentially many evaluations, because the period encodes the factorization and no local structure reveals it. Quantum mechanically the period is a phase pattern spread across a superposition, and interference reads a global phase in one shot. The win is not a faster Fourier transform — the classical FFT is comparably fast — but the ability to apply that transform to an exponentially large superposition prepared with only polynomial work. Speedup is superposition plus interference, not the transform alone.

Why is the register 2n+1 qubits and not just n?

Because continued fractions need enough resolution to name the fraction s/rs/r uniquely. Two different fractions with denominators below NN can be as close as 1/N21/N^2, so to guarantee your measured estimate y/Qy/Q is nearer the true s/rs/r than to any impostor, the resolution 1/(2Q)1/(2Q) must beat 1/(2N2)1/(2N^2). That forces Q≥N2Q\ge N^2, i.e. t≥2nt\ge 2n; one extra bit buys the constant success probability, giving t≈2n+1t\approx 2n+1. Use only nn qubits and the estimate of s/rs/r is too coarse — several fractions of denominator below NN are all consistent with the measurement, and continued fractions cannot pick the right one. The register size is set by classical post-processing, not by the quantum part.

What are the "bad bases," and how often do they ruin a run?

Two things can go wrong with a random base aa: its order rr can be odd (so ar/2a^{r/2} is not an integer power and the factoring formula is undefined), or ar/2a^{r/2} can equal −1-1 modulo NN (so the difference of squares gives only the trivial factors 11 and NN). Both are number-theoretic accidents of that particular aa, not failures of the quantum circuit. The reassuring theorem, proved via the Chinese Remainder Theorem, is that for an odd composite with k≥2k\ge2 distinct prime factors these bad events together have probability at most 2−(k−1)≤122^{-(k-1)}\le\tfrac12. So a good base turns up in a couple of tries on average, and the whole algorithm just redraws aa and repeats when it hits a bad one.

Has anyone actually factored a big number with Shor's algorithm?

Not honestly, and this is widely misreported. The genuine demonstrations are tiny: a 2001 NMR experiment factored 1515, and later photonic and ion-trap experiments repeated small cases. Headlines claiming much larger factorizations almost always describe either compiled circuits that secretly hard-code the known answer, or a different method entirely (a variational or annealing heuristic) that does not scale and is not Shor's algorithm. Breaking RSA-2048 requires thousands of logical qubits — roughly twenty million noisy physical qubits for hours — under full error correction, hardware that does not yet exist. The algorithm is proven on paper and in toy demonstrations; running it at cryptographic scale is the open engineering challenge.

If we can't run it yet, why worry about it now?

Because encrypted data has a long shelf life and adversaries are patient. The "harvest now, decrypt later" threat is simple: record encrypted traffic today, store it, and decrypt it years from now once a large fault-tolerant quantum computer exists. Anything that must stay secret for a decade — state secrets, medical records, long-lived keys — is therefore already at risk from a machine that has not been built. That is why standards bodies moved ahead of the hardware: NIST finalized post-quantum cryptography standards in 2024, and migration away from RSA and elliptic-curve cryptography is underway now. Shor's algorithm is thus a present-tense policy problem despite being a future-tense engineering one — its mere existence, provably correct, is enough to force the change.

Before this

Where this leads