Shor Algorithm
Shor’s algorithm factors integers by finding the period of modular exponentiation. A quantum Fourier measurement reveals information about that period; classical continued fractions and greatest common divisors turn it into factors. The algorithm runs in expected time polynomial in the number of input bits. It also solves discrete logarithms in efficiently represented finite cyclic groups.
The quantum computer does not read out a list of trial divisors. Its advantage comes from coherent arithmetic followed by interference. Preparing that arithmetic is usually more costly than the Fourier transform itself. Below, the factoring reduction is developed first, followed by the discrete-logarithm construction and the distinction between a logical algorithm and a physical implementation.
Helpful background. Quantum phase estimation supplies the eigenphase distribution and confidence bounds; the quantum Fourier transform explains how periodic amplitudes interfere.
Factoring through a multiplicative order
Section titled “Factoring through a multiplicative order”Assume classical preprocessing has removed factors of two, identified primes and detected perfect powers. For a perfect power , it suffices to factor the smaller integer . We may therefore take odd, composite and not a perfect power. Primality testing, perfect-power detection, modular exponentiation and greatest common divisors have polynomial-time classical algorithms. The input length is .
Choose an integer uniformly from
and compute
If , then is already a nontrivial factor. Otherwise is invertible modulo , and its multiplicative order modulo is
Suppose order finding returns an even . Set
Then
so
Minimality of implies . If also
then neither factor nor is divisible by all of . The classical computations
therefore reveal nontrivial factors.
If is odd or , the run has supplied no factor. This is not an undetected error: discard that base and try another.
Why a useful base occurs often enough
Section titled “Why a useful base occurs often enough”Write the preprocessed odd integer as a product involving distinct odd primes. Let be the event
For a uniformly chosen invertible residue, finite-group counting gives
One way to see the bound is to use the Chinese remainder theorem. On each odd prime-power factor, write the local order as an odd number times . A useful square root fails precisely when all coincide, including the all-zero case. These exponents are independent for a uniform invertible residue, and each value in any one local distribution has probability at most . Conditioning on the first exponent therefore bounds the failure probability by .
Excluding the base removes only an unsuccessful choice, so the same lower bound applies to the sampling range above. A non-coprime base helps through the initial gcd. Exact order finding thus gives a constant chance of progress; recovering the full order from finite Fourier samples has an additional success factor discussed below.
Worked example: factoring 15
Section titled “Worked example: factoring 15”Take and choose . Since
find the powers
The order is . Therefore
and
This verifies the arithmetic reduction. A general factoring circuit must obtain the period without having it or the factors supplied during circuit construction.
Quantum order finding
Section titled “Quantum order finding”The function
is periodic with least positive period because
The quantum circuit makes many values of interfere coherently so that this period appears as a reciprocal spacing in Fourier space.
Periodic-state formulation
Section titled “Periodic-state formulation”Choose a power of two
and prepare two registers as
Reversible modular exponentiation computes
If the second register is measured with result , the first register is left in a truncated periodic progression,
Here choose , let , and set . The progression is exact; it is truncated by the finite register boundary. Measuring the second register is optional: ignoring it produces the same first-register statistics.
Applying the inverse QFT over , with the same convention as phase estimation, gives constructive interference near
The measured ratio therefore approximates . When divides , these are exact Fourier bins. In general the peaks have finite width, and continued fractions recover the nearby rational.
Phase-estimation formulation
Section titled “Phase-estimation formulation”The same computation can be expressed as eigenphase estimation. On the orbit generated by , define modular multiplication
Because , multiplication by permutes all residues , not only the invertible ones. On an -qubit register, define it as the identity on . This specifies a permutation unitary on the entire encoded space. Reversible arithmetic must also restore any workspace used to implement it. The orbit
has length . Its Fourier eigenstates are
and direct index shifting gives
The easy input is an equal superposition of these eigenstates:
Consequently the exact output distribution is an equal-weight mixture of the finite-resolution QPE distributions for . The latent eigenphase labels have exactly uniform weights; the measured binary bins need not be equally likely. It is unnecessary to prepare an unknown eigenstate. A finite-resolution outcome can leave several orbit eigenstates coherently present in the target.
Controlled powers are efficient arithmetic
Section titled “Controlled powers are efficient arithmetic”QPE calls controlled powers
The crucial identity is
Each constant is computed efficiently by classical repeated squaring. The quantum circuit then performs controlled reversible multiplication by that known constant. It does not repeat a base circuit times. This arithmetic structure is what keeps order finding polynomial.
Continued fractions and verified factors
Section titled “Continued fractions and verified factors”Let be the measured Fourier outcome. Take
Since and , a nearest-bin outcome obeys
Legendre’s continued-fraction theorem says that if is in lowest terms and a rational approximation satisfies this bound, then appears among the continued-fraction convergents of . Test the candidate denominator by modular exponentiation:
This test proves that the candidate is a multiple of the true order, not necessarily the least order. For example, , but .
For factoring, a verified even multiple can still be tried: compute and accept only if . Then gives nontrivial factors. Unlike the case of the least even order, is now possible and must be checked. A returned factor is always confirmed by division, so an inaccurate Fourier sample need not become an incorrect factorization.
One simple implementation scans the continued-fraction convergents with denominator below , tests them and repeats when none gives a useful factor. Successful nearest-bin samples with include the true order among these candidates. This is enough for the polynomial expected-runtime guarantee.
When the sampled fraction is not reduced
Section titled “When the sampled fraction is not reduced”If
then
and continued fractions reveal only the divisor . The probability that one uniformly sampled is coprime to is
where is Euler’s totient function. It is not bounded below by a positive constant for all , but its inverse grows at most on the order of asymptotically. A nearest-bin event has probability at least for every , so useful rational reconstruction remains efficient in expectation.
Several valid reduced denominators can reveal the order together. For and , the true order is six. With , a result can reveal while reveals . Neither denominator passes the modular test alone: and . Their least common multiple is six, which passes. It gives and factors , .
Two incomplete denominator estimates can complement one another. The figure follows particular outcomes for , and . Each rational approximation and the combined modular result are checked classically; arbitrary noisy denominators cannot simply be assumed to divide the true order.
The end-to-end success probability therefore combines three events:
- the random base has a useful even order;
- Fourier sampling lands close enough to a rational ;
- the sampled numerator exposes enough of the denominator.
The individual reasons for failure are not all observable from one output: the sampled and its approximation error are unknown. What can be checked is whether the proposed arithmetic gives a nontrivial divisor. A complete runtime includes repeats, and complete prime factorization recursively factors the divisors obtained.
Discrete logarithms as hidden subgroups
Section titled “Discrete logarithms as hidden subgroups”The Fourier idea also appears in Simon’s algorithm, where one solves binary equations. Discrete logarithms instead produce modular equations over a cyclic group.
Let be a cyclic group of known order , and suppose
Assume group elements have efficient encodings and coherent reversible group operations. The discrete-logarithm problem asks for . Define
Two pairs have the same function value exactly when their difference lies in the subgroup
Thus hides a cyclic subgroup of order in the product group . A coherent evaluation of , followed by a two-register QFT, samples characters orthogonal to . An observed pair satisfies
When is invertible modulo ,
If is not invertible, the sample determines only a congruence modulo . Several samples suffice once : an extended-gcd calculation finds coefficients with , and then . Verify the result by checking .
For example, modulo six the equations and determine and , respectively. Together they give , although neither coefficient is invertible modulo six.
The relation follows by summing a character over ; choosing instead of changes the subgroup and the relative sign. Reversing both Fourier signs leaves the same zero relation. For non-power-of-two , the group QFT must be synthesized to a sufficient approximation; its error belongs in the success probability.
This construction applies to multiplicative groups of finite fields and, in additive notation, to elliptic-curve groups. For points and , the coherent group operation evaluates . Efficient reversible point addition replaces modular multiplication, but the Fourier and classical linear-algebra logic is the same.
Logical complexity and physical cost
Section titled “Logical complexity and physical cost”For an -bit modulus, order finding uses register qubits and controlled modular multiplications by classically computed constants. A typical schoolbook reversible multiplication uses gates, leading to roughly cubic arithmetic cost. The QFT on controls contributes gates before rotation synthesis; it is not the dominant step in these constructions.
Space, depth and gate count can be traded against one another. Beauregard’s compact construction uses logical qubits, elementary gates and depth . These are circuit resources, not physical-qubit counts. Actual counts also depend on the elementary gate alphabet and accuracy of small rotations.
The general number field sieve provides a classical comparison with heuristic asymptotic running time
This is subexponential in but superpolynomial. Shor’s polynomial algorithm improves on that scaling; it does not prove that every classical factoring algorithm must be superpolynomial. Factoring is not known to be NP-complete, and the result does not make arbitrary NP-complete problems easy. Quantum complexity classes explains these distinctions.
Physical error correction adds another layer. If logical operation locations each have failure probability bounded by , a union bound gives total failure probability at most , without requiring independence. Keeping this below requires in this uniform allocation. Code distance, memory duration, routing, non-Clifford-state production and classical feedforward then determine physical space and elapsed time. A logical qubit count alone supplies none of those quantities.
The derivation of these costs is developed in resource estimation; changing architectural proposals are compared in resource-estimation frontiers. Numerical projections are conditional models, not dates by which a machine will exist.
Cryptographic consequences and small demonstrations
Section titled “Cryptographic consequences and small demonstrations”At a sufficient fault-tolerant scale, the algorithms attack these underlying mathematical problems:
| Problem | Examples affected |
|---|---|
| Factoring an RSA modulus | RSA encryption and signatures |
| Finite-field discrete logarithm | Diffie–Hellman, ElGamal and DSA |
| Elliptic-curve discrete logarithm | ECDH and ECDSA |
For RSA, factors of allow reconstruction of the private exponent. For an elliptic curve, solving reveals the private scalar. Efficient reversible group arithmetic is needed in each case. Shor’s algorithm does not directly solve generic symmetric-key search; Grover search addresses that different task.
Post-quantum cryptography uses classical algorithms designed to resist known quantum attacks. It is distinct from quantum key distribution and does not require quantum communication. See cryptography case studies for the systems context.
A small experiment can test phase kickback, modular arithmetic or Fourier decoding without demonstrating a scalable factoring computation. Optimizations based on the known input and are legitimate if they can themselves be computed efficiently. Supplying the unknown period or factors to the compiler removes the hard part. Smolin, Smith and Vargo’s analysis of oversimplified factoring demonstrations makes this distinction concrete. A general implementation must retain the coherent arithmetic and the cost of finding and verifying the answer.
Exercises
Section titled “Exercises”1. Factor 15 from an order
Section titled “1. Factor 15 from an order”For and , determine the order and use it to recover both prime factors.
Solution
The powers modulo are
so . Since is even,
Then
and
Both gcds are nontrivial, giving .
2. Diagnose an unhelpful base
Section titled “2. Diagnose an unhelpful base”For , choose . Find its order and explain why the gcd step after order finding fails.
Solution
Since
we have and therefore . The order is even, but
Consequently
and
Neither is a nontrivial factor. The run is recognized as unhelpful and a new base is chosen.
3. Verify the modular-multiplication eigenstate
Section titled “3. Verify the modular-multiplication eigenstate”Starting from
prove that .
Solution
Apply and shift the summation index to modulo :
The wraparound term is valid because .
4. Recover a denominator by continued fractions
Section titled “4. Recover a denominator by continued fractions”Suppose order finding uses and measures . Show that is a convergent of and verify the rational-reconstruction error bound for denominator .
Solution
The Euclidean algorithm gives
Its convergents include
The approximation error is
Since
Legendre’s sufficient condition holds. A candidate order must still be checked by testing .
5. Why use about twice the input bit length?
Section titled “5. Why use about twice the input bit length?”Let and choose . Show that a nearest Fourier bin satisfies the continued-fraction accuracy condition for .
Solution
A nearest integer to obeys
Dividing by gives
Because and ,
Therefore
which is the desired sufficient condition.
6. A discrete-logarithm Fourier relation
Section titled “6. A discrete-logarithm Fourier relation”In the group , let and . First find such that . Then check that the Fourier sample satisfies the hidden-subgroup relation .
Solution
The powers of modulo begin
Thus in the cyclic group of order . For the sample ,
Because is invertible,
7. A candidate multiple and a logical error budget
Section titled “7. A candidate multiple and a logical error budget”For and , show why candidate passes but fails the factor-recovery step. Separately, if a circuit has logical operation locations and allocates failure probability to them, give a sufficient uniform per-location bound. Does it determine the physical-qubit count?
Solution
The least order is four, so eight is a multiple and . But , giving gcds and . This is why an unproven candidate multiple requires checking both roots , even though the least even order cannot give .
The union bound requires , or . It is a sufficient logical error allocation. Converting it to physical qubits requires a code and a noise model, plus the storage, routing and non-Clifford-operation costs. No physical-qubit number follows from this inequality alone.
References
Section titled “References”- S. Beauregard, “Circuit for Shor’s algorithm using qubits,” Quantum Information and Computation 3, 175–185, 2003, doi:10.26421/QIC3.2-8.
- J. P. Buhler, H. W. Lenstra Jr., and C. Pomerance, “Factoring integers with the number field sieve,” in The Development of the Number Field Sieve, 50–94, 1993, doi:10.1007/BFb0091539.
- A. Ekert and R. Jozsa, “Quantum computation and Shor’s factoring algorithm,” Reviews of Modern Physics 68, 733–753, 1996, doi:10.1103/RevModPhys.68.733.
- M. A. Nielsen and I. L. Chuang, Quantum Computation and Quantum Information, 10th anniversary ed., Cambridge University Press, 2010, doi:10.1017/CBO9780511976667.
- P. W. Shor, “Polynomial-time algorithms for prime factorization and discrete logarithms on a quantum computer,” SIAM Journal on Computing 26, 1484–1509, 1997, doi:10.1137/S0097539795293172.
- J. A. Smolin, G. Smith, and A. Vargo, “Oversimplifying quantum factoring,” Nature 499, 163–165, 2013, doi:10.1038/nature12290.