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 to split an -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 . 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 , pick a random base , and — unless you get lucky and is already a factor — find the multiplicative order of modulo , the smallest with . From an even with , a difference of squares hands you , two nontrivial factors, in a few lines of Euclid. The one step no classical machine can do quickly is finding , because the period of hides the factorization. That single step is the quantum computer's entire job. Quantum mechanically, stops being a needle in an exponential haystack and becomes a global phase pattern. The operator "multiply by " has eigenvalues ; 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 . 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.
- Shor's algorithm factors an -bit integer in time on a quantum computer — an exponential speedup over every classical method known.
- The engine is a classical reduction: factoring reduces, with probability per random base, to finding the multiplicative order of modulo .
- The quantum core solves order finding by phase estimation on the modular-multiplication unitary , whose eigenvalues carry the period.
- You never build an eigenstate: the trivial state is an equal superposition of all of them, so one run samples a random and the same circuit works without knowing .
- The measured estimate of is post-processed by continued fractions to recover exactly; this demands a phase register of qubits so that .
- 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 of ; 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.
Factoring reduces to finding the period of ; 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 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 million noisy physical qubits running about hours under surface-code error correction — thousands of logical qubits and – 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 , discrete log is the HSP for , 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 as a periodic signal whose hidden period is exactly the number the algorithm wants. A quantum computer evaluates on every input at once, entangling a label of with the value in one pass of reversible arithmetic. Ignore the value register and the input register collapses onto a single arithmetic progression — one period's worth of the comb. The quantum Fourier transform of a comb of spacing is itself a comb, but of spacing : 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 — multiply a residue by , modulo — is a permutation of the residues, and a permutation whose cycles have length has eigenvalues that are -th roots of unity, . Estimate one eigenvalue's phase and you have measured a fraction ; run it through continued fractions and the unknown numerator falls away, leaving . The genius of the construction is that you never have to prepare an eigenstate — which would require knowing first. The residue , trivial to write down, is an exactly equal superposition of all eigenstates, so one run samples a uniformly random for free. The first figure lays out this two-register circuit; the second shows the interference comb it produces.
Where the comb's teeth land is set entirely by number theory, and one instance shows the mechanism sharply. Take , : the powers of mod cycle , so ; with qubits, , and the post-QFT distribution is four sharp peaks at . Reading gives , whose continued-fraction denominator is — done in one shot. The second figure is that exact distribution, the payoff picture of the whole algorithm.
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.
where: — composite integer to factor, bits; — random base with and ; — multiplicative order of mod , the least with . Reading: given a good (even , ), two Euclid gcds finish the factoring in classical work. The quantum side needs an operator whose spectrum stores . Multiplication by modulo is a bijection of residues, hence a unitary permutation, and it is the object phase estimation acts on.
where: — permutation operator on residues, unitary because multiplication by a unit is invertible mod ; — computational basis state labelling residue . Reading: moves along the cycle , closing after exactly steps. Because that cycle has length , the operator's eigenstates are discrete Fourier modes over the cycle, and their eigenvalues are the -th roots of unity — the period, encoded directly in a phase.
where: — eigenstate indexed by ; — eigenvalue, an -th root of unity. Reading: phase estimation on would return the fraction — but preparing needs , the very unknown. The escape is that the residue is already an equal superposition over all eigenstates, so it needs no knowledge of at all.
where: — computational basis state for residue , trivially prepared. Reading: feed into phase estimation and each run collapses onto one random , sampling uniformly from . 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.
where: — size of the phase register, chosen ; — qubits in the phase register, . Reading: this one line does exponentially many evaluations of in superposition; everything after is interference, not further arithmetic. Applying the inverse QFT and measuring concentrates the amplitude near integer multiples of — the interference comb of the second figure.
where: — measured value of the phase register; — number of terms in the collapsed progression; — the random integer selected by that run. Reading: the geometric sum is only when is near an integer, so measurement lands on the tooth nearest with high probability. Dividing by gives an approximation to ; continued fractions recover the exact fraction, but only if the register is large enough that no other fraction with denominator below is as close.
where: — measured fraction fed to the continued-fraction algorithm; — target rational, in lowest terms exactly when . Reading: this is why — the resolution must beat the gap between distinct fractions of denominator . Finally, the cost. The QFT is cheap (); the bill is the modular exponentiation, a ladder of controlled modular multiplications.
where: — controlled multiplication by , conditioned on exponent bit ; — total gate count with fast (Schönhage–Strassen) integer multiplication. Reading: modular multiplications each costing give with schoolbook arithmetic, dropping to with fast multiplication — polynomial, and that is the whole point.
The goal of this first derivation is to justify equation (1) completely — to show precisely why knowing the order of a random base lets ordinary greatest-common-divisor arithmetic split , and to pin down exactly which two conditions on 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 must be non-trivial precisely when is even and is not the "boring" square root of unity.
Step 1. By definition of the order, , so divides . Why: the order is the exact period of the powers of , so is the first power difference that cleanly divides — the anchor the rest of the argument hangs from.
Step 2. Assume is even and write ; then divides the product . Why: the difference of squares is the whole mechanism — it splits the quantity divides into two explicit integers, and any prime of must land in one of them.
Step 3. Now , because and is the least exponent giving ; assume also the favourable case . Why: if then one factor is and the other carries all of , so the gcds return only and — these are exactly the two "bad-base" failure modes the reduction must dodge.
Step 4. Since divides neither nor individually, yet divides their product, shares a proper factor with each; hence and are non-trivial, computed in by Euclid. Why: a prime power cannot sit entirely inside a factor that fails to divide, so its parts distribute across the two gcds — this is the difference of squares delivering the split concretely. *Verified: gives and ; the bad base has and returns only and .*
Go deeper · Derivation B · 1 minWhy 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 of an eigenstate , yet every is defined in terms of the unknown , 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 eigenstates collapses to the single computational basis state — so that the algorithm runs on a state anyone can prepare, and each run silently samples a uniformly random . The plan is to sum the eigenstate definitions over , swap the order of summation, and evaluate the resulting geometric sum.
Step 1. Sum equation (3) over and interchange the two sums: . Why: pulling the -sum outside isolates a pure phase sum over for each fixed , which is a geometric series with a clean closed form.
Step 2. Evaluate the inner sum: , zero for every and for . 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 survives, leaving . Why: the entire equal superposition of eigenstates is nothing but the residue in disguise, so preparing is preparing without ever naming .
Step 4. Phase estimation is linear, so running it on produces the entangled sum ; measuring the phase register collapses one term, delivering a uniformly random . 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 the four eigenphases are ; summing the four returns , and equal sampling of matches the four equal peaks in the second figure.*
Go deeper · Derivation C · 2 minRegister size and continued-fraction recovery
The output of phase estimation is not but a noisy estimate of the fraction , and the final classical step must recover the exact rational from that approximation. The goal here is to derive the register-size rule (equivalently ) as the exact resolution needed for continued fractions to return 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 .
Step 1. With qubits, phase estimation returns the integer whose fraction is within of the true with constant probability. Why: 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 , cheaply.
Step 2. A rational with is the unique fraction of denominator below within of a given real, because two distinct fractions and with denominators differ by at least . Why: fractions of bounded denominator are spread apart by at least , 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: , i.e. , hence ; the standard choice 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 tie for closest, so continued fractions cannot decide and the readout is corrupted, not just coarse.
Step 4. Run the continued-fraction expansion of and take the last convergent with denominator below ; its denominator is when , and a proper divisor of otherwise, cured by repetition. Why: the convergents of a continued fraction are provably the best rational approximations of bounded denominator, so the algorithm reads off directly — and a coprime , which occurs with probability , delivers itself. *Verified: needs , , so , suffices; the outcome gives , whose convergent denominator is , while gives and only the divisor .*
Limiting cases
The algorithm's behaviour is governed by number-theoretic luck in the base and by correct sizing of the phase register:
| Case | Result | Meaning |
|---|---|---|
| Odd order | odd | is not an integer power, so the factoring step (1) is undefined; this run is discarded and a fresh is drawn. |
| Trivial square root | The difference of squares gives only and ; another bad-base event cured by retrying. | |
| Both good conditions | even, | Success: split . For with distinct odd prime factors this holds with probability per random . |
| Prime power | Order finding need not split cleanly, but prime powers are caught by a classical preprocessing test (is an integer for ). | |
| Even | Trivial — divide out factors of classically before invoking the quantum routine at all. | |
| Register too small | Continued fractions cannot resolve uniquely; distinct fractions tie and the readout is ambiguous. Must use . |
Worked examples
1 · Factoring 15 end to end (fully worked)
Factor using the base : 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 , so is a valid base and gives no free factor. The modulus has bits, so choose a phase register of qubits: . The circuit uses an 8-qubit phase register.
Step 2. What order finding returns. The powers of mod cycle , so the order is . The quantum subroutine does not know this in advance; it prepares , runs controlled modular exponentiation, applies the inverse QFT, and measures. Because divides exactly, the outcome is one of four sharp peaks , each with probability . Measurement yields .
Step 3. Continued-fraction recovery. Suppose the run returns . Then , already in lowest terms, so the denominator is the candidate . Verify: . Good — confirmed. (Had the run returned , giving , the candidate would be the divisor ; verifying rejects it, and one simply reruns. The outcomes and — a chance — succeed immediately.) Recovered .
Step 4. Extract the factors. The order is even and , which is neither nor — a good base. Apply equation (1): and . .
2 · A larger period and a bad base (21)
Factor with , then show what goes wrong for the base .
Step 1. Good base . Here . The powers give order — even, and larger than the modest register would suggest, illustrating why (here qubits, ) is needed to resolve .
Step 2. Finish the factoring. With , , and . Then and . .
Step 3. Why fails. The base also has order mod (powers ), but now . The difference of squares collapses: and — only the trivial factors. A bad base returns and ; discard and redraw . 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
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.
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 of and the orthogonality collapse giving ; the register condition ; the reduction-success bound via the CRT two-adic-valuation argument (N&C Appendix 4 / Theorem 5.3); the worked instances and , including the bad base mod ; and the gate count. Hardware resource figures (roughly million qubits / 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 — 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 , it finds the period of modulo . The "parallelism" is real but subtle — the circuit evaluates for all at once, entangling with — 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 gates, no faster asymptotically than the modular exponentiation it accompanies. The speedup lives in the problem framing: classically, detecting the period of 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 uniquely. Two different fractions with denominators below can be as close as , so to guarantee your measured estimate is nearer the true than to any impostor, the resolution must beat . That forces , i.e. ; one extra bit buys the constant success probability, giving . Use only qubits and the estimate of is too coarse — several fractions of denominator below 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 : its order can be odd (so is not an integer power and the factoring formula is undefined), or can equal modulo (so the difference of squares gives only the trivial factors and ). Both are number-theoretic accidents of that particular , not failures of the quantum circuit. The reassuring theorem, proved via the Chinese Remainder Theorem, is that for an odd composite with distinct prime factors these bad events together have probability at most . So a good base turns up in a couple of tries on average, and the whole algorithm just redraws 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 , 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.