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 nn-bit integer in time polynomial in nn. 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 NN can be turned into another problem. That problem is finding the order of a randomly chosen element modulo NN. 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 NN. 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.

Key takeaways
  • Factoring NN reduces to finding the multiplicative order rr of a random aa coprime to NN.
  • If rr is even and ar/2≢−1(modN)a^{r/2} \not\equiv -1 \pmod N, then gcd⁡(ar/2±1,N)\gcd(a^{r/2}\pm 1, N) gives a nontrivial factor.
  • A random aa satisfies these conditions with probability at least 1/21/2, 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 n=log⁡Nn = \log N: roughly O(n3)O(n^3) per attempt, with O(1)O(1) expected attempts.
  • This breaks RSA's hardness assumption, motivating post-quantum cryptography.
The core insight

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 NN directly. Instead it reduces factoring to order-finding: given NN and an integer aa coprime to NN, find the smallest positive integer rr (the multiplicative order of aa modulo NN) such that

ar≡1(modN).a^r \equiv 1 \pmod N .

The set of integers coprime to NN under multiplication mod NN forms a finite abelian group, ZN∗\mathbb{Z}_N^*, and every element has some finite order dividing ∣ZN∗∣=φ(N)|\mathbb{Z}_N^*| = \varphi(N) (Euler's totient). The function f(x)=ax  Nf(x) = a^x \bmod N is periodic with period exactly rr, 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 rr is even and ar/2≢±1(modN)a^{r/2} \not\equiv \pm 1 \pmod N, then ar/2a^{r/2} is a nontrivial square root of 11 modulo NN. Writing

(ar/2−1)(ar/2+1)≡0(modN),(a^{r/2} - 1)(a^{r/2} + 1) \equiv 0 \pmod N,

and knowing neither factor is ≡0(modN)\equiv 0 \pmod N, the Euclidean algorithm applied to gcd⁡(ar/2−1, N)\gcd(a^{r/2} - 1,\, N) (or +1+1) must return a proper, nontrivial divisor of NN. This works because NN divides the product but divides neither factor individually — meaning NN'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 Ua∣y⟩=∣ay  N⟩U_a\lvert y\rangle = \lvert ay \bmod N\rangle. 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 NN is even, output the factor 22. If NN is a perfect power pkp^k (checkable classically in polynomial time by trying all exponents k≤log⁡2Nk \le \log_2 N and testing integer kk-th roots), output pp. These classical pre-checks remove degenerate cases where the group-theoretic argument below can fail or become trivial.

Step 2 — Random base. Choose aa uniformly at random from {2,…,N−1}\{2, \dots, N-1\}.

Step 3 — GCD shortcut. Compute gcd⁡(a,N)\gcd(a, N) using the Euclidean algorithm. If this gcd is not 11, it is already a nontrivial factor of NN — done, no quantum computer needed.

Step 4 — Quantum order-finding. Otherwise a∈ZN∗a \in \mathbb{Z}_N^*. Call the quantum subroutine to find the order rr of aa mod NN, i.e. the smallest r>0r>0 with ar≡1(modN)a^r \equiv 1 \pmod N.

Step 5 — Parity and nontriviality check. If rr is odd, or if rr is even but ar/2≡−1(modN)a^{r/2} \equiv -1 \pmod N, this trial fails to produce a factor; go back to Step 2 with a new random aa.

Step 6 — Extract the factor. Otherwise compute gcd⁡(ar/2−1,N)\gcd(a^{r/2} - 1, N). This is guaranteed to be a nontrivial, proper factor of NN. ``` 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 ff is found, NN splits as f×(N/f)f \times (N/f), and the same routine (or classical trial division for small remaining factors) is applied recursively to fully factor NN into primes. Modular exponentiation ar/2  Na^{r/2} \bmod N is done classically via fast exponentiation-by-squaring, in O(n3)O(n^3) bit operations for nn-bit NN (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.

Figure
Control flow of Shor's algorithm: classical wrapper around one quantum subroutine call
Input N N even? N a prime power? → return factor directly pick random a ∈ [2, N−1] gcd(a,N) ≠ 1 ? classical yes → factor found return gcd no QUANTUM: order-finding phase estimation on U_a: |y⟩ → |ay mod N⟩ outputs order r with a^r ≡ 1 (mod N) r even AND a^(r/2) ≠ −1 mod N? retry loop (new a) yes → return gcd(a^(r/2)−1, N) return factor

Complexity & correctness

Time complexity. For nn-bit NN: the trivial-case checks (evenness, perfect-power test) run in O(n2)O(n^2) or so, negligible compared to the rest. Each trial does one gcd⁡\gcd computation (O(n2)O(n^2) bit operations classically), one call to quantum order-finding, and one modular exponentiation plus another gcd⁡\gcd for the postprocessing. The quantum order-finding subroutine itself runs in O(n3)O(n^3) time (dominated by modular exponentiation controlled by the phase-estimation register, plus an O(n2)O(n^2) quantum Fourier transform), using O(n)O(n) qubits for the target register and O(n)O(n) (or O(2n)O(2n) for accuracy margin) qubits for the phase register. The key question is how many trials are expected. As shown below, each random aa succeeds — meaning it yields an even order rr with ar/2≢−1a^{r/2}\not\equiv -1 — with probability at least 1/21/2 (more precisely 1−1/2k−11 - 1/2^{k-1} where kk is the number of distinct odd prime factors of NN, which is at least 1/21/2 whenever NN has at least one odd prime factor with multiplicity, i.e. essentially always for NN not a power of 22). So the expected number of trials is O(1)O(1), and the total expected running time is

O(n3)O(n^3)

bit operations (with O(n)O(n) expected calls dominated by a constant), which is polynomial in n=log⁡Nn = \log N — 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 exp⁡(O(n1/3log⁡2/3n))\exp(O(n^{1/3}\log^{2/3} n)).

Space complexity. O(n)O(n) qubits for the quantum register (the exact count depends on the phase-estimation precision and the modular-exponentiation circuit's ancillas, typically O(n)O(n) to O(n2)O(n^2) total qubits in explicit constructions), plus O(n)O(n) 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 r=ordN(a)r = \text{ord}_N(a) is even and x=ar/2  Nx = a^{r/2} \bmod N satisfies x≠N−1x \ne N-1 (i.e. x≢−1x \not\equiv -1). Since rr is the smallest exponent with ar≡1a^r \equiv 1, and x2=ar≡1(modN)x^2 = a^r \equiv 1 \pmod N, we know xx is a square root of 11 mod NN that is neither 11 (else r/2r/2 would already satisfy ar/2≡1a^{r/2}\equiv 1, contradicting minimality of rr) nor −1-1 (by assumption). So

N∣(x−1)(x+1),N∤(x−1),N∤(x+1).N \mid (x-1)(x+1), \quad N \nmid (x - 1), \quad N \nmid (x+1).

By the Chinese Remainder Theorem, NN's prime power factors are distributed between x−1x - 1 and x+1x + 1 in a way that is not all-or-nothing, so gcd⁡(x−1,N)\gcd(x - 1, N) is strictly between 11 and NN — a genuine nontrivial factor. This argument requires NN 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 22 handled separately — the standard treatment restricts attention to odd NN with at least two distinct prime factors after trivial filtering). Part 2 (probability: why a random aa succeeds often enough). Fix the distinct odd prime power factors N=p1e1⋯pkekN = p_1^{e_1}\cdots p_k^{e_k} (with k≥2k \ge 2 after filtering). By CRT, choosing aa uniformly at random mod NN (coprime to NN) is equivalent to choosing independent uniform random elements ai∈Zpiei∗a_i \in \mathbb{Z}_{p_i^{e_i}}^* for each ii. Each Zpiei∗\mathbb{Z}_{p_i^{e_i}}^* is cyclic (a classical fact for odd prime powers), so the order of aia_i, and in particular the largest power of 22 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 22-adic valuations v2(ord(ai))v_2(\text{ord}(a_i)) coincide across all ii — the exact condition under which rr is odd or ar/2≡−1a^{r/2}\equiv -1 — is at most 1/2k−1≤1/21/2^{k-1} \le 1/2 for k≥2k \ge 2. Hence with probability at least 1/21/2, a random trial yields a usable rr, giving expected O(1)O(1) 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 O(n)O(n) sequential controlled modular multiplications). Near-term noisy devices cannot run this reliably for cryptographically relevant nn (thousands of bits). The algorithm is also a Monte Carlo procedure — it can fail on any given trial (odd rr, or unlucky aa) — 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 N=21N = 21 using a=2a = 2.

Step 1. 2121 is odd; is it a perfect power? 21≠pk21 \ne p^k for any prime pp, k≥2k\ge 2. Continue.

Step 2–3. Pick a=2a = 2. gcd⁡(2,21)=1\gcd(2, 21) = 1, so proceed to order-finding.

Step 4 (quantum order-finding, traced classically here for illustration). Compute powers of 22 mod 2121:

xx2x  212^x \bmod 21
12
24
38
416
511
61

The order is r=6r = 6 (the smallest positive xx with 2x≡12^x \equiv 1). In the real algorithm, this value r=6r=6 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 aa simultaneously.

Step 5. r=6r = 6 is even. Compute ar/2=23=8  21=8a^{r/2} = 2^3 = 8 \bmod 21 = 8. Since 8≠21−1=208 \ne 21 - 1 = 20, the nontriviality condition holds — proceed to extraction.

Step 6. Compute gcd⁡(8−1,21)=gcd⁡(7,21)=7\gcd(8 - 1, 21) = \gcd(7, 21) = 7. 77 is a nontrivial factor of 2121. Since 21=7×321 = 7 \times 3, the algorithm succeeds on the very first trial, returning f=7f = 7 and (by division) the cofactor 33.

A failing trial, for contrast. Suppose instead a=20≡−1(mod21)a = 20 \equiv -1 \pmod{21} had been chosen. Then gcd⁡(20,21)=1\gcd(20, 21) = 1, and the order of 20≡−120 \equiv -1 mod 2121 is r=2r = 2 (since (−1)2=1(-1)^2 = 1). This rr is even, so check ar/2=201  21=20≡−1a^{r/2} = 20^1 \bmod 21 = 20 \equiv -1. This is the forbidden case ar/2≡−1a^{r/2} \equiv -1, so this trial fails and the algorithm restarts with a new random aa — illustrating why the retry loop is necessary and why picking a "bad" aa like N−1N-1 is a real, non-degenerate failure mode, not a bug.

Common pitfalls & traps

PitfallWhy it happensFix
Forgetting the perfect-power / even pre-checkThe order-finding reduction's correctness proof assumes NN has ≥2 distinct odd prime factorsAlways filter NN even and N=pkN = p^k classically first
Treating rr odd as an errorSome random aa genuinely have odd order; this is expected, not a bugJust retry with a fresh random aa
Stopping at ar/2≡−1a^{r/2}\equiv -1 without retryThis case gives gcd⁡(x±1,N)∈{1,N}\gcd(x\pm1,N) \in \{1,N\} — no informationDetect this case explicitly and loop back to Step 2
Confusing order-finding output with the factor itselfrr is a period, not a factor; an extra gcd step is requiredAlways run Steps 5–6 after getting rr from the quantum subroutine
Assuming exact phase estimationQuantum phase estimation gives an estimate of k/rk/r, requiring continued fractions to recover rr exactlyUse enough precision qubits (≈2n+1\approx 2n+1) and continued-fraction post-processing (handled inside order-finding)
Ignoring the case gcd⁡(a,N)≠1\gcd(a,N)\ne 1 pre-quantumRare but possible; wastes a quantum call if not checked classically firstAlways compute gcd⁡(a,N)\gcd(a,N) classically before invoking the quantum subroutine

Pioneers & history

Origins · 1 minPeter Williston Shor and how this was discovered
PW
Peter Williston Shor
born 1959 · American applied mathematician at Bell Labs, later MIT, who invented the algorithm in 1994

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.

History
1976
— Diffie and Hellman, and shortly after Rivest–Shamir–Adleman, base public-key cryptography on the presumed hardness of factoring and discrete log.
1985
— Deutsch formalizes the quantum Turing machine, laying groundwork for quantum complexity theory.
1994
— Shor announces polynomial-time quantum algorithms for factoring and discrete logarithm.
1996
— Kitaev reformulates order-finding via the quantum phase-estimation framework, clarifying and generalizing Shor's construction.
2001
— IBM experimentally demonstrates Shor's algorithm factoring 15=3×515 = 3 \times 5 on a 7-qubit liquid-state NMR quantum computer.

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 rr of a randomly chosen aa modulo NN — a periodicity-detection task suited to quantum phase estimation and the quantum Fourier transform. All the surrounding logic — picking aa, computing gcds, checking parity of rr, extracting a factor from ar/2±1a^{r/2}\pm 1 — 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 NN splits via the Chinese Remainder Theorem into a product of cyclic groups, one per prime power factor of NN. A uniformly random aa corresponds to independent uniformly random elements in each cyclic factor. A counting argument over cyclic groups shows the "bad" outcomes — rr odd, or ar/2≡−1a^{r/2}\equiv -1 — happen only when the 2-adic structure of the orders in every factor coincides exactly, an event with probability at most 1/2k−11/2^{k-1} for k≥2k\ge 2 distinct prime factors, hence at most 1/21/2.

What happens if N is a prime power, like N = 3^4 = 81?

The reduction's correctness proof needs NN to have at least two distinct prime factors, because it relies on CRT splitting NN into at least two independent cyclic components. If N=pkN = p^k for a single prime pp, this splitting is trivial and the probability argument collapses — a random aa 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 2n2n to 3n3n qubits for nn-bit NN: an nn-qubit (or larger, for precision) phase-estimation register, an nn-qubit target register holding values mod NN, 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 O(n)O(n) sequential modular multiplications, each itself requiring O(n2)O(n^2) 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 1/21/2, 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 Z\mathbb{Z}), 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 Z×Z\mathbb{Z}\times\mathbb{Z} instead of Z\mathbb{Z}. 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.

Before this

Where this leads