Shor's Factoring Algorithm

Shor's Algorithm is a quantum algorithm that factors an -bit integer in time polynomial in — specifically gate operations (with fast multiplication) — providing an exponential speedup over the best known classical algorithms. Discovered by Peter Shor in 1994, it reduces factoring to order-finding, solved efficiently using the Quantum Fourier Transform. Its existence threatens RSA, Diffie–Hellman, and elliptic-curve cryptography, motivating the field of post-quantum cryptography.

Shor's algorithm solves the integer factorization problem: given a composite integer , find a nontrivial factor. The classical hardness of this problem underlies the RSA cryptosystem. The algorithm's central move is a reduction — factoring is achieved by finding the multiplicative order of a randomly chosen modulo , i.e., the least with . This order-finding is performed by preparing a superposition over exponents, applying modular exponentiation, and using the quantum Fourier transform to extract the period via continued fractions. The surprising fact is that a problem believed to require super-polynomial classical effort collapses to polynomial time on a quantum computer — the first compelling evidence that quantum computation is qualitatively more powerful for a problem of genuine practical importance.

The Core Insight

Factoring is hard, but periodicity detection is easy for quantum computers. The function is periodic with period (the order of ). A classical computer must evaluate at exponentially many points to detect this period, but a quantum computer evaluates on a superposition of all inputs simultaneously, then uses the Quantum Fourier Transform to interfere those amplitudes so that measuring the output yields information about . Once is known (and even, with ), the factors emerge from . The quantum speedup lives entirely in the period-finding subroutine; everything else is classical number theory.

Formal Statement

Order / Multiplicative Order

Let be a positive integer and an integer coprime to , . The multiplicative order of modulo is the least positive integer such that

1
⟳Existence follows because the map permutes the finite group , so some power must return to the identity; minimality defines .

The element generates a cyclic subgroup of order inside , and where is Euler's totient.

Factoring via Order-Finding

Let be an odd composite integer that is not a prime power. Choose uniformly at random from with , and let be its order. Then with probability at least (over the choice of ):

2
⟳Using the Chinese Remainder Theorem decompose and bound the fraction of elements whose order is odd or whose half-power is ; each prime-power factor contributes at most a factor .

When [2] holds, set . Then but , so

3
⟳. Since , neither factor is divisible by all of , so the common factors split.

and therefore is a nontrivial factor of .

Quantum Fourier Transform

The Quantum Fourier Transform on acts on basis states () by

4
⟳This is the discrete Fourier transform unitarized; the prefactor ensures the map preserves norm, and the kernel is the -th root of unity raised to .

It is implemented with Hadamard and controlled-phase gates via the product (tensor-factored) form of the transform.

Why It Holds — The Algorithm and Its Analysis

Order-Finding via Phase Estimation

Setup. Choose such that (a "counting" register of qubits) and a "work" register of qubits. Step 1 — Uniform superposition. Apply Hadamards to the counting register:
5
⟳, the equal superposition over all computational basis states.
Step 2 — Modular exponentiation. Apply the reversible unitary :
6
⟳Implemented by repeated squaring — — each controlled modular multiplication costing gates, of them.
Step 3 — Measure (or trace out) the work register. This collapses to a coset: for some random ,
7
⟳All with the same value differ by multiples of ; conditioning on the measured value leaves exactly the arithmetic progression .
Step 4 — Apply the QFT to the counting register. The amplitude on is
8
⟳Apply [4] term-by-term; the phase factor is a global phase per fixed and drops out of the probability.
Step 5 — Constructive interference. The geometric sum over is large precisely when is near an integer, i.e. for integer . The probability concentrates:
9
⟳Sum the finite geometric series with and take the squared modulus, yielding the Dirichlet (Fejér) kernel.
Step 6 — Continued fractions. Measure . With probability , . Since is a fraction with denominator , it is the unique such fraction within , recoverable from by the continued fraction expansion, yielding (after dividing out ). Step 7 — Verify and repeat. Check . If is odd or , choose a new . A constant number of repetitions succeeds with overwhelming probability.

Step 6 may return only a divisor of (when ) or fail when . Standard fixes: take the least common multiple of denominators from two independent runs, or test small multiples . The success probability per run is bounded below by a constant (after accounting for these losses), so or runs suffice.

Schematic of Shor's order-finding circuit and the post-QFT probability peaks at multiples of $2^t/r$.

Shor Order-Finding Circuit |0>^t |0> H H H a^x mod N QFT† measure y Pr[y] after QFT y P 0 2^t/r 2·2^t/r

Peter Williston Shor | b. 1959

Peter Shor, an applied mathematician at Bell Labs (later MIT), introduced the factoring and discrete-logarithm algorithms in his landmark 1994 FOCS paper "Algorithms for Quantum Computation: Discrete Logarithms and Factoring." Trained in combinatorics and probability, Shor recognized that the hidden-subgroup structure underlying period-finding could be exposed by the quantum Fourier transform — building conceptually on Simon's problem and Deutsch–Jozsa. He also pioneered quantum error correction (the 9-qubit Shor code, 1995), making fault-tolerant quantum computation conceivable and thereby giving his algorithm physical plausibility. He received the Nevanlinna Prize (1998) and the Gödel Prize, and his work catalyzed both quantum computing as a field and the entire post-quantum cryptography enterprise.

Building Intuition

Imagine the modular exponential function as a striped tablecloth: it repeats with period , but is hidden among exponentially many columns. A classical observer can only lift the cloth at one spot at a time. The quantum computer instead lifts the entire cloth into a superposition. After measuring the work register, you're left not with a single column but with a perfectly periodic "comb" of positions — though you cannot read it directly, because measuring would give one random tooth. The QFT acts like a prism: a periodic comb of spacing in the input transforms into a new comb of spacing in the output, and crucially the random offset becomes an unobservable global phase. So measuring the QFT output samples near integer multiples of , and the continued-fraction algorithm reads off from any one of them. The whole trick is converting "find a hidden period" — exponentially hard classically — into "find the spacing of bright fringes," which interference does for free.

Interference picture

Physically, this is a multi-slit diffraction experiment. The collapsed state [7] is an array of "slits" at positions spaced apart. The QFT is the propagation to the far field (Fraunhofer regime). Constructive interference produces bright fringes exactly where the path-phase is a multiple of — at . The width of each fringe shrinks as , so choosing makes the peaks sharp enough that the nearest fraction is uniquely resolvable. Quantum factoring is, at heart, diffraction grating spectroscopy of an arithmetic period.

Worked Examples

Factoring N = 15 with a = 7

Given: , choose (coprime to 15). Find the order: . So . Check conditions [2]: is even ✓. , and ✓. Extract factors via [3]:
Quantum side (sanity check): with so , the QFT peaks at . Measuring gives ; continued fractions yield denominator . ✓

Factoring N = 21 with a = 2

Given: , choose (). Find the order: . So . Check conditions [2]: even ✓. , and ✓. Extract factors via [3]:
Quantum side: with , peaks at . Measuring gives ; continued fraction yields convergent , so . ✓

Common Misconceptions

"Shor's algorithm tries all factors in parallel." No — quantum parallelism alone is useless because measurement returns a single random outcome. The power comes from interference engineered by the QFT, which concentrates amplitude on outcomes encoding . Naive superposition without the Fourier step would just yield a uniformly random , conveying nothing about the period. "It directly factors ." The quantum subroutine never factors anything; it finds the order . All the factoring happens in classical post-processing through GCD computations [3]. The reduction (order-finding → factoring) is pure number theory, predating quantum computing.

When the lucky-condition fails

Take , . Then , so (even). But — condition [2] fails. Computing and : both trivial. The algorithm learns nothing and must restart with a fresh . This is exactly the "bad " case that Theorem [2] bounds to probability .

Preconditions matter. Before running, classically dispose of easy cases: if is even, return 2; if is a perfect power, find by testing -th roots; if you already have a factor. Shor's quantum core is invoked only on odd composites with at least two distinct prime factors.

Connections

Shor's algorithm is the flagship instance of the abelian Hidden Subgroup Problem: order-finding is HSP over , and the same QFT machinery solves the Discrete Logarithm Problem (breaking Diffie–Hellman and ECC). Its period-finding kernel generalizes Simon's Algorithm (HSP over ). The order-finding subroutine is precisely Quantum Phase Estimation applied to the modular-multiplication unitary , whose eigenvalues are . The classical reduction relies on the Chinese Remainder Theorem and Continued Fractions, while implementation cost is dominated by reversible Modular Exponentiation circuits.

Real-World Applications

  1. Breaking RSA. RSA-2048 security rests on the difficulty of factoring a 2048-bit modulus; a fault-tolerant quantum computer running Shor's algorithm would recover the private key. Estimates suggest ~20 million noisy physical qubits (Gidney–Ekerå, 2019) — large but finite.
  2. Breaking Diffie–Hellman and ECC. Via the discrete-log variant, Shor's method defeats elliptic-curve cryptography (ECDSA, used in Bitcoin and TLS) and classical Diffie–Hellman key exchange.
  3. Driving post-quantum cryptography (PQC). NIST's standardization of lattice- and hash-based schemes (CRYSTALS-Kyber, Dilithium, SPHINCS+, 2022–2024) is a direct response to Shor's threat.
  4. "Harvest now, decrypt later" defense. Governments and enterprises migrate to PQC today because encrypted traffic captured now could be broken once large quantum computers exist.
  5. Benchmarking quantum hardware. Small instances () have been demonstrated on NMR, photonic, ion-trap, and superconducting platforms as proof-of-principle and as integration tests (though several "demonstrations" used precompiled shortcuts).
  6. Cryptographic agility standards. IETF and TLS 1.3 hybrid key-exchange (X25519 + Kyber) deployments by Google, Cloudflare, and Apple are motivated by the Shor threat model.
  7. Resource-estimation research. Shor's algorithm is the canonical workload for surface-code overhead, magic-state distillation, and logical-qubit cost analyses in fault-tolerant architecture design.

Historical Development

  • 1980–1985 — Benioff, Feynman, and Deutsch lay theoretical foundations of quantum computation; Deutsch defines the universal quantum Turing machine.
  • 1992 — Deutsch–Jozsa algorithm gives the first exponential (deterministic) quantum–classical separation, albeit for an artificial problem.
  • 1993 — Bernstein–Vazirani and the formalization of quantum query complexity sharpen the notion of quantum advantage.
  • 1994 — Daniel Simon presents Simon's problem with an exponential speedup; its period-finding structure directly inspires Shor.
  • 1994 (Nov) — Peter Shor announces the polynomial-time factoring and discrete-log algorithms at FOCS; published in full in SIAM J. Comput. 1997.
  • 1995 — Shor introduces the 9-qubit quantum error-correcting code, showing fault tolerance is in principle possible — making the algorithm physically relevant.
  • 1996–1998 — Kitaev reframes the method via quantum phase estimation and the eigenvalue/HSP perspective; Coppersmith analyzes the approximate QFT.
  • 2001 — IBM and Stanford factor on a 7-qubit NMR quantum computer (Vandersypen et al.), the first experimental demonstration.
  • 2012–2019 — Photonic and superconducting demonstrations; Gidney–Ekerå (2019) estimate ~20 million qubits / 8 hours to break RSA-2048, refining the resource picture.

Subtleties & Limits

Resource gap and noise. No quantum computer has factored a number that resists classical methods; demonstrations are tiny and often compiled with knowledge of the answer. The decisive obstacle is fault tolerance — Shor's algorithm needs millions of physical qubits and deep, coherent circuits, far beyond NISQ-era hardware. Classical lower bounds. It remains unproven that factoring is classically hard. The best classical algorithm, the General Number Field Sieve, runs in — sub-exponential but super-polynomial — yet no proof rules out a polynomial-time classical factoring algorithm. Thus Shor's speedup is conditional on this folklore hardness. HSP frontier. Order-finding is the abelian HSP, fully solved by the QFT. The non-abelian Hidden Subgroup Problem (e.g. the dihedral group, linked to lattice problems, and the symmetric group, linked to graph isomorphism) resists efficient quantum solution; whether Shor-style techniques extend there is a major open question with cryptographic stakes for post-quantum schemes.

See Also

Quantum Fourier Transform · Quantum Phase Estimation · Hidden Subgroup Problem · Discrete Logarithm Problem · Simon's Algorithm · Grover's Algorithm · Modular Exponentiation · Continued Fractions · RSA Cryptosystem · Post-Quantum Cryptography · Quantum Error Correction

Before this

Where this leads