Shor's Factoring Algorithm
Every day, billions of secure connections rely on an assumption. This assumption is that factoring large integers is hard. RSA encryption, digital signatures, and much of internet commerce depend on this. All of it sits on top of this single computational bottleneck. In 1994, Peter Shor showed something remarkable. A quantum computer can factor an -bit integer in time polynomial in . The best known classical algorithms, by contrast, take sub-exponential time. This was the first quantum algorithm to promise an exponential speedup. That speedup applied to a practically important problem. It remains the canonical demonstration of quantum advantage. The deep insight is a reduction. Factoring an integer can be turned into another problem. That problem is finding the order of a randomly chosen element modulo . This is a periodicity problem, perfectly suited to the quantum Fourier transform. The quantum part of Shor's algorithm — The Order-Finding Subroutine — extracts a hidden period. It does so exponentially faster than any known classical method. The classical part is a short randomized wrapper. It repeatedly calls this quantum subroutine. It checks a few conditions using elementary number theory. It succeeds with high probability after only a handful of trials. This article assembles the full algorithm. It explains precisely how factoring reduces to order-finding. It gives the complete classical control logic around the quantum subroutine. It proves the whole pipeline runs in expected polynomial time. It treats the number-theoretic reduction as a black box that calls order-finding. The order-finding subroutine itself — phase estimation applied to modular exponentiation — is covered in depth elsewhere. By the end, you should be able to do several things. You should trace a full run of Shor's algorithm on a small number by hand. You should explain exactly why the reduction works. This uses the structure of the multiplicative group mod . You should also state honestly what does and does not need quantum hardware, versus classical computation. This sets up directly why Shor's algorithm threatens RSA Cryptography.
- Factoring reduces to finding the multiplicative order of a random coprime to .
- If is even and , then gives a nontrivial factor.
- A random satisfies these conditions with probability at least , so few retries are needed.
- The quantum subroutine (order-finding via quantum phase estimation) is the only part needing a quantum computer.
- Total running time is polynomial in : roughly per attempt, with expected attempts.
- This breaks RSA's hardness assumption, motivating post-quantum cryptography.
Factoring is hard classically because finding periods is hard classically — and a quantum computer finds periods efficiently.
The idea
Shor's algorithm does not factor directly. Instead it reduces factoring to order-finding: given and an integer coprime to , find the smallest positive integer (the multiplicative order of modulo ) such that
The set of integers coprime to under multiplication mod forms a finite abelian group, , and every element has some finite order dividing (Euler's totient). The function is periodic with period exactly , and this periodicity is what the quantum subroutine detects. The classical number-theoretic insight, due essentially to a folklore reduction predating Shor but combined by him with quantum order-finding, is this: if is even and , then is a nontrivial square root of modulo . Writing
and knowing neither factor is , the Euclidean algorithm applied to (or ) must return a proper, nontrivial divisor of . This works because divides the product but divides neither factor individually — meaning 's prime factors must be split between the two terms, and the gcd isolates a nontrivial subset of them. Shor's contribution was showing order-finding is exactly the kind of problem the quantum Fourier transform solves efficiently: it reveals the period of a periodic quantum superposition in polynomial time, via Quantum Phase Estimation applied to the modular-exponentiation unitary . This article treats that subroutine as a trusted primitive and focuses on the surrounding reduction and classical control flow that make the full factoring algorithm work.
How it works
The full algorithm alternates classical preprocessing, one call to quantum order-finding, and classical postprocessing, retrying with fresh randomness when a trial fails.
Step 1 — Trivial-case filter. If is even, output the factor . If is a perfect power (checkable classically in polynomial time by trying all exponents and testing integer -th roots), output . These classical pre-checks remove degenerate cases where the group-theoretic argument below can fail or become trivial.
Step 2 — Random base. Choose uniformly at random from .
Step 3 — GCD shortcut. Compute using the Euclidean algorithm. If this gcd is not , it is already a nontrivial factor of — done, no quantum computer needed.
Step 4 — Quantum order-finding. Otherwise . Call the quantum subroutine to find the order of mod , i.e. the smallest with .
Step 5 — Parity and nontriviality check. If is odd, or if is even but , this trial fails to produce a factor; go back to Step 2 with a new random .
Step 6 — Extract the factor. Otherwise compute . This is guaranteed to be a nontrivial, proper factor of . ``` ALGORITHM ShorFactor(N):
# N: odd composite integer > 1, not a prime power (checked below) if N is even: return 2 if N is a perfect power p^k (k >= 2): return p loop forever: a := uniform_random_integer(2, N - 1) g := gcd(a, N) # classical Euclidean algorithm if g != 1: return g # lucky classical hit r := QuantumOrderFind(a, N) # calls order-finding subroutine if r is odd: continue # retry with new a if a^(r/2) mod N == N - 1: # i.e. == -1 mod N continue # retry with new a f := gcd(a^(r/2) - 1, N) if f == 1 or f == N: continue # extremely rare degenerate case return f # f is a nontrivial factor of N ``` Once a single nontrivial factor is found, splits as , and the same routine (or classical trial division for small remaining factors) is applied recursively to fully factor into primes. Modular exponentiation is done classically via fast exponentiation-by-squaring, in bit operations for -bit (schoolbook multiplication) or better with fast multiplication. The diagram below shows the control flow: the quantum computer is invoked only inside the shaded box, and everything else — random sampling, gcd, modular arithmetic, retry logic — is ordinary classical computation.
Complexity & correctness
Time complexity. For -bit : the trivial-case checks (evenness, perfect-power test) run in or so, negligible compared to the rest. Each trial does one computation ( bit operations classically), one call to quantum order-finding, and one modular exponentiation plus another for the postprocessing. The quantum order-finding subroutine itself runs in time (dominated by modular exponentiation controlled by the phase-estimation register, plus an quantum Fourier transform), using qubits for the target register and (or for accuracy margin) qubits for the phase register. The key question is how many trials are expected. As shown below, each random succeeds — meaning it yields an even order with — with probability at least (more precisely where is the number of distinct odd prime factors of , which is at least whenever has at least one odd prime factor with multiplicity, i.e. essentially always for not a power of ). So the expected number of trials is , and the total expected running time is
bit operations (with expected calls dominated by a constant), which is polynomial in — an exponential improvement over the best known classical factoring algorithms, whose running time is sub-exponential, e.g. the general number field sieve at roughly .
Space complexity. qubits for the quantum register (the exact count depends on the phase-estimation precision and the modular-exponentiation circuit's ancillas, typically to total qubits in explicit constructions), plus classical bits for bookkeeping.
Correctness argument. The proof has two independent parts. Part 1 (number theory: why the reduction is correct when it succeeds). Suppose is even and satisfies (i.e. ). Since is the smallest exponent with , and , we know is a square root of mod that is neither (else would already satisfy , contradicting minimality of ) nor (by assumption). So
By the Chinese Remainder Theorem, 's prime power factors are distributed between and in a way that is not all-or-nothing, so is strictly between and — a genuine nontrivial factor. This argument requires to have at least two distinct prime factors (guaranteed once the perfect-power and even cases are filtered out in Step 1, since a non-power-of-2, non-prime-power composite must have at least two distinct odd prime factors, or one odd prime factor and the factor handled separately — the standard treatment restricts attention to odd with at least two distinct prime factors after trivial filtering). Part 2 (probability: why a random succeeds often enough). Fix the distinct odd prime power factors (with after filtering). By CRT, choosing uniformly at random mod (coprime to ) is equivalent to choosing independent uniform random elements for each . Each is cyclic (a classical fact for odd prime powers), so the order of , and in particular the largest power of dividing that order, behaves like that of a uniform random element of a cyclic group. A counting argument over cyclic groups shows: the probability that all the -adic valuations coincide across all — the exact condition under which is odd or — is at most for . Hence with probability at least , a random trial yields a usable , giving expected retries. This is the classical randomized wrapper's core correctness guarantee, entirely independent of the quantum subroutine's internal workings.
Tradeoffs to be honest about. The quantum order-finding step needs a fault-tolerant quantum computer with enough logical qubits and low enough error rates to run a deep circuit (modular exponentiation is the expensive part, requiring sequential controlled modular multiplications). Near-term noisy devices cannot run this reliably for cryptographically relevant (thousands of bits). The algorithm is also a Monte Carlo procedure — it can fail on any given trial (odd , or unlucky ) — so a bounded number of retries with high-probability success is the correct framing, not a deterministic guarantee on the first try.
Worked example
Factor using .
Step 1. is odd; is it a perfect power? for any prime , . Continue.
Step 2–3. Pick . , so proceed to order-finding.
Step 4 (quantum order-finding, traced classically here for illustration). Compute powers of mod :
| 1 | 2 |
| 2 | 4 |
| 3 | 8 |
| 4 | 16 |
| 5 | 11 |
| 6 | 1 |
The order is (the smallest positive with ). In the real algorithm, this value is what quantum phase estimation extracts (with high probability, via continued-fraction expansion of the measured phase) without ever computing this whole table — it uses superposition to probe all powers of simultaneously.
Step 5. is even. Compute . Since , the nontriviality condition holds — proceed to extraction.
Step 6. Compute . is a nontrivial factor of . Since , the algorithm succeeds on the very first trial, returning and (by division) the cofactor .
A failing trial, for contrast. Suppose instead had been chosen. Then , and the order of mod is (since ). This is even, so check . This is the forbidden case , so this trial fails and the algorithm restarts with a new random — illustrating why the retry loop is necessary and why picking a "bad" like is a real, non-degenerate failure mode, not a bug.
Common pitfalls & traps
| Pitfall | Why it happens | Fix |
|---|---|---|
| Forgetting the perfect-power / even pre-check | The order-finding reduction's correctness proof assumes has ≥2 distinct odd prime factors | Always filter even and classically first |
| Treating odd as an error | Some random genuinely have odd order; this is expected, not a bug | Just retry with a fresh random |
| Stopping at without retry | This case gives — no information | Detect this case explicitly and loop back to Step 2 |
| Confusing order-finding output with the factor itself | is a period, not a factor; an extra gcd step is required | Always run Steps 5–6 after getting from the quantum subroutine |
| Assuming exact phase estimation | Quantum phase estimation gives an estimate of , requiring continued fractions to recover exactly | Use enough precision qubits () and continued-fraction post-processing (handled inside order-finding) |
| Ignoring the case pre-quantum | Rare but possible; wastes a quantum call if not checked classically first | Always compute classically before invoking the quantum subroutine |
Pioneers & history
Origins · 1 minPeter Williston Shor and how this was discovered
Shor developed the algorithm while working at AT&T Bell Labs on quantum computational complexity, building on earlier work on quantum Fourier sampling and Simon's period-finding problem. His 1994 paper (published in full in 1997 in SIAM Journal on Computing) showed that both integer factorization and the discrete logarithm problem admit polynomial-time quantum algorithms, immediately establishing quantum computing's relevance to cryptography and triggering major investment in quantum hardware research.
Where this matters
Shor's algorithm is the central reason cryptographers now build post-quantum cryptography: RSA, Diffie–Hellman, and elliptic-curve cryptosystems all rely on the hardness of factoring or discrete logarithm, both broken in polynomial time by Shor's approach and its discrete-log variant. Standards bodies (NIST) have run multi-year competitions selecting lattice-based and hash-based replacements precisely because Shor's algorithm makes today's public-key infrastructure obsolete once large, fault-tolerant quantum computers exist. Beyond cryptography, Shor's algorithm is the flagship benchmark for quantum hardware progress: every major quantum computing effort (superconducting qubits, trapped ions, photonics) reports small-scale factoring or order-finding demonstrations as evidence of progress toward fault tolerance. It also inspired the broader class of hidden subgroup problem algorithms, unifying factoring, discrete log, and other abelian group problems under a single quantum algorithmic framework, and motivated deep study of the Quantum Fourier Transform as a general-purpose primitive analogous to the classical FFT in digital signal processing.
Ask the tutor: Can you walk through why a random a fails to give a usable order with probability at most 1/2, using the CRT decomposition explicitly?
Does Shor's algorithm factor N directly on the quantum computer?
No. The quantum computer only finds the order of a randomly chosen modulo — a periodicity-detection task suited to quantum phase estimation and the quantum Fourier transform. All the surrounding logic — picking , computing gcds, checking parity of , extracting a factor from — is ordinary classical computation. The quantum subroutine is a black-box period-finder; the number-theoretic reduction that turns a period into a factor is entirely classical and was understood, in essence, before Shor combined it with a fast quantum period-finder.
Why does choosing a random a work almost always, rather than needing a special a?
The multiplicative group mod splits via the Chinese Remainder Theorem into a product of cyclic groups, one per prime power factor of . A uniformly random corresponds to independent uniformly random elements in each cyclic factor. A counting argument over cyclic groups shows the "bad" outcomes — odd, or — happen only when the 2-adic structure of the orders in every factor coincides exactly, an event with probability at most for distinct prime factors, hence at most .
What happens if N is a prime power, like N = 3^4 = 81?
The reduction's correctness proof needs to have at least two distinct prime factors, because it relies on CRT splitting into at least two independent cyclic components. If for a single prime , this splitting is trivial and the probability argument collapses — a random would almost never produce a usable nontrivial factor. This is why Step 1 explicitly tests for perfect powers classically (via integer root-finding) and handles them separately before ever invoking the quantum subroutine.
How many qubits does an actual implementation need?
A textbook circuit construction uses roughly to qubits for -bit : an -qubit (or larger, for precision) phase-estimation register, an -qubit target register holding values mod , and additional ancilla qubits for the arithmetic circuits implementing controlled modular multiplication and exponentiation. Optimized constructions reduce ancilla counts, but the dominant cost is not qubit count so much as circuit depth: modular exponentiation requires sequential modular multiplications, each itself requiring or better gate operations, making circuit depth the primary engineering bottleneck for fault-tolerant implementations.
Is Shor's algorithm deterministic or randomized?
It is a randomized (Monte Carlo) algorithm with one-sided, boundable error: each trial either succeeds (returns a genuine nontrivial factor) or fails cleanly (detected via the parity/negation checks), never returning a wrong answer silently as long as the postprocessing checks are implemented correctly. Because each trial succeeds with probability at least , repeating the trial a constant number of times drives the failure probability down exponentially, so in practice a handful of retries suffices with overwhelming probability.
Does this mean quantum computers can solve all NP-complete problems fast?
No — this is a common misconception. Factoring is not known to be NP-complete; it lies in NP ∩ co-NP and is widely believed to be strictly easier than NP-complete problems. Shor's algorithm exploits very specific abelian group structure (the hidden subgroup problem for ), not general combinatorial search. Grover's algorithm gives only a quadratic speedup for unstructured search relevant to NP-complete problems, not an exponential one, so Shor's result does not imply quantum computers can efficiently solve NP-complete problems in general.
What is the discrete-log analog, and why does it matter equally?
Shor's original paper also solves the discrete logarithm problem in polynomial time, using the same hidden-subgroup-problem framework but over instead of . This matters because Diffie–Hellman key exchange and elliptic-curve cryptography (ECDH, ECDSA) rely on discrete-log hardness rather than factoring, so a quantum computer capable of running Shor's factoring algorithm can, with essentially the same techniques, break these systems too — making the threat comprehensive across nearly all deployed public-key cryptography, not just RSA.