Shor Algorithm
Short Definition
Section titled “Short Definition”Shor’s algorithm is a family of randomized quantum algorithms that solves integer factoring and discrete logarithms in time polynomial in the input length. Its quantum core does not search through candidate factors. It finds a period, or more generally a hidden subgroup, by preparing a coherent periodic function and decoding its frequency information with a Quantum Fourier Transform; the dedicated page owns the transform circuit and approximation contract, while this page owns period finding and verified arithmetic recovery.
For factoring, the logical chain is
Most of the surrounding work is classical: choose a base, compute greatest common divisors, use continued fractions, verify a candidate order, and retry when a random choice is unhelpful. The quantum work is dominated by reversible modular arithmetic, not by the Fourier transform alone.
This page is the canonical home for the complete reduction, its success conditions, the discrete-logarithm variant, asymptotic complexity, cryptographic consequences, and implementation caveats. Quantum Phase Estimation owns the general eigenphase algorithm and its precision analysis.
What the Algorithm Actually Establishes
Section titled “What the Algorithm Actually Establishes”Let be the integer to factor and let
be its bit length. Shor’s result gives a uniform family of quantum circuits, together with polynomial-time classical processing, whose expected runtime is polynomial in . The algorithm is probabilistic, but unsuccessful runs are detectable and repetition raises the success probability.
Several qualifications matter:
- The theorem is about an ideal fault-tolerant computation with scalable coherent arithmetic.
- The algorithm is polynomial in the number of input bits, not in the numerical value .
- Factoring is not known to be NP-complete, and Shor’s result does not make generic NP problems easy.
- The speedup is relative to the best known classical factoring algorithms; no theorem proves that every classical algorithm must be slow.
- The same framework solves discrete logarithms in finite cyclic groups, including the groups used by finite-field and elliptic-curve cryptography.
Calling the result “exponential speedup” is common but imprecise for factoring. The best known general classical algorithm is subexponential rather than fully exponential in , whereas Shor’s algorithm is polynomial. “Superpolynomial improvement over the best known classical method” states the comparison more accurately.
From Factoring to Order Finding
Section titled “From Factoring to Order Finding”Assume classical preprocessing has removed easy cases: is odd, composite, and not a prime power. Primality testing, perfect-power detection, modular exponentiation, and greatest common divisors all have polynomial-time classical algorithms.
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.
Only order finding is quantum. Every branch is checked classically: a lucky gcd gives a factor immediately, while an odd order or the square root triggers a retry.
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
Among bases coprime to , standard finite-group counting shows that
A non-coprime base only helps, because the initial gcd then exposes a factor. Thus exact order finding combined with a random base has a constant probability of making progress. Recovering the full order from one Fourier sample has an additional number-theoretic success factor, discussed below, but polynomially many repetitions suffice.
Worked example: factoring 15
Section titled “Worked example: factoring 15”Take and choose . Since
find the powers
The order is . Therefore
and
The example illustrates the reduction, but it is too small to demonstrate scalability. A circuit specialized using advance knowledge that the answer is , or that the period is , does not constitute a general implementation of Shor’s algorithm.
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 an approximately periodic progression,
where only values inside occur. Measuring the second register is optional: ignoring it produces the same first-register statistics.
Applying the QFT over 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 the invertible residues and can be completed to a unitary. The orbit
has length . Its Fourier eigenstates are
and direct index shifting gives
The easy input is an equal superposition of these eigenstates:
Consequently QPE applied to samples an eigenphase approximately uniformly over . It is unnecessary to prepare a particular unknown eigenstate.
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.
Recovering the Order
Section titled “Recovering the Order”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 . The candidate denominator is tested by modular exponentiation:
Verification is essential. Finite-resolution outcomes, a non-nearest Fourier bin, or a convergent unrelated to the true phase can all produce a wrong denominator.
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. This ratio is not bounded below by a positive constant for all , but it decreases slowly enough that repeated samples remain polynomially sufficient. Practical postprocessing can also combine compatible denominator information, for example by least common multiples, and verify the result.
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.
All three failures are detectable. A complete complexity statement counts the repetitions needed to obtain and verify a useful order.
Discrete Logarithms as Hidden Subgroups
Section titled “Discrete Logarithms as Hidden Subgroups”Simon’s Algorithm owns hidden-subgroup recovery for through Hadamard samples and binary equations. This section instead owns the number-theoretic subgroup and recovery problem over .
Let be a cyclic group of known order , and suppose
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 one-dimensional subgroup of the two-dimensional Abelian group . A coherent evaluation of , followed by a two-register QFT, samples characters orthogonal to . An observed pair satisfies
When is invertible modulo ,
Otherwise several samples supply a solvable modular linear system. Sign conventions vary with the choice of versus and with the Fourier-transform sign; the hidden subgroup, not a memorized sign, is the invariant content.
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.
Complexity and the Source of the Speedup
Section titled “Complexity and the Source of the Speedup”For an -bit modulus, the order-finding registers contain qubits and require phase precision , hence control bits. Standard decompositions give:
- gates for an exact QFT on qubits;
- polynomial-size reversible circuits for addition and modular multiplication;
- about cubic elementary-gate scaling in common schoolbook-arithmetic constructions;
- polynomially many repetitions for Fourier and number-theoretic success.
The precise exponents and constants depend on the multiplication algorithm, ancilla budget, connectivity, gate alphabet, allowed measurements, and whether cost means gate count, depth, space, or spacetime volume. For example, Beauregard’s compact general construction uses qubits, elementary gates, and depth . It is a logical circuit result, not a physical-qubit estimate. Quantum Complexity Classes defines BQP and explains why membership does not itself prove a classical lower bound.
The Quantum Algorithms and Complexity chapter guide supplies the wider problem, access, output, resource, comparator, and evidence audit: Shor’s polynomial quantum upper bound is not by itself a proved classical superpolynomial lower bound.
By comparison, the general number field sieve has heuristic asymptotic running time
This is subexponential in but superpolynomial. Shor replaces the best known classical asymptotic scaling with polynomial quantum gate complexity, subject to the structured-access and fault-tolerance assumptions.
Where the advantage does not come from
Section titled “Where the advantage does not come from”- It is not quantum parallelism followed by reading all values .
- It is not an exhaustive search over divisors.
- It is not the QFT in isolation; the periodic state and efficient modular arithmetic are indispensable.
- It is not a generic rule that quantum computers solve every hard problem exponentially faster.
- It does not remove input, verification, control, routing, or error-correction costs.
The speedup is an interference algorithm for a specific algebraic structure.
Cryptographic Implications
Section titled “Cryptographic Implications”At cryptographically relevant scale on a fault-tolerant quantum computer, Shor’s algorithms target the mathematical assumptions behind widely deployed public-key systems:
| Problem solved by Shor | Vulnerable constructions |
|---|---|
| integer factoring | RSA encryption, RSA key transport, and RSA signatures |
| finite-field discrete logarithm | finite-field Diffie–Hellman, ElGamal, and DSA |
| elliptic-curve discrete logarithm | ECDH, ECDSA, and related elliptic-curve protocols |
Factoring an RSA modulus reveals and , from which the private exponent can be reconstructed. Solving on an elliptic curve reveals the private scalar . These are direct breaks of the underlying one-way problems, not merely quadratic search improvements.
Shor’s algorithm does not directly break symmetric ciphers or cryptographic hash functions. Generic exhaustive key search is instead associated with Grover Search, which gives a quadratic query improvement under an appropriate coherent oracle model. Concrete cryptanalysis must still count reversible implementation, memory, parallelization, and error correction.
Post-quantum migration
Section titled “Post-quantum migration”Post-quantum cryptography consists of classical algorithms designed to resist known classical and quantum attacks; it does not require quantum communication or quantum hardware. In August 2024, NIST approved FIPS 203 for ML-KEM, FIPS 204 for ML-DSA, and FIPS 205 for SLH-DSA. Their publication is an operational basis for migration, not evidence that a cryptographically relevant quantum computer is imminent.
Migration can still be urgent because:
- cryptographic infrastructure changes slowly;
- archived ciphertext may remain sensitive for years;
- an adversary can store encrypted traffic now and attempt decryption later;
- protocols, certificates, hardware, and compliance regimes have long replacement cycles.
Quantum key distribution is a separate communication technology. It neither replaces the broad functionality of post-quantum public-key cryptography nor changes the mathematical statement of Shor’s algorithm.
Reading Resource Estimates Correctly
Section titled “Reading Resource Estimates Correctly”Asymptotic polynomial time does not determine the size of a useful machine. A resource estimate must specify at least:
- the arithmetic circuit and success probability;
- logical qubits, non-Clifford gates, depth, and measurements;
- the error-correcting code and target logical failure rate;
- physical error rates and operation times;
- connectivity, routing, and classical reaction latency;
- magic-state factories or another non-Clifford mechanism;
- the space-time tradeoff and allowed wall-clock time.
Numbers quoted without this contract are not portable.
Three illustrative estimates
Section titled “Three illustrative estimates”Compact logical circuit. Beauregard’s 2003 construction demonstrates that a fully general factoring circuit can use qubits, at the price of gates. These are ideal logical qubits and elementary circuit operations. Error-correction overhead is outside the count.
Surface-code estimate from 2021. Gidney and Ekerå estimated that one particular construction could factor an RSA-2048 modulus in about eight hours using about 20 million physical qubits. Their model assumed a nearest-neighbor square grid, physical gate error , a surface-code cycle, and classical reaction time. At the abstract-circuit level, their formulas included
The physical headline follows only after choosing the code layout, factories, error budget, and timing assumptions.
A 2025 preprint tradeoff. Gidney later estimated that RSA-2048 could be factored in less than a week with fewer than one million physical qubits under the same headline error, connectivity, cycle-time, and reaction-time assumptions. The reduction uses approximate residue arithmetic, yoked surface-code storage, and magic-state cultivation, while accepting a longer runtime and different arithmetic costs. This is a research preprint and a model-dependent estimate, not a hardware forecast. Its large shift from the 2021 number shows why resource estimates should be versioned and compared by assumptions, not repeated as timeless thresholds.
Elliptic-curve discrete logarithms
Section titled “Elliptic-curve discrete logarithms”Roetteler, Naehrig, Svore, and Lauter gave a concrete reversible circuit for an elliptic curve over an -bit prime field using at most
qubits and
Toffoli gates. This is again a logical gate-level estimate. The study indicates that elliptic-curve systems at comparable classical security can be a smaller quantum target than RSA, but a physical comparison still requires one consistent error-correction and hardware model.
No one of these studies supplies a universal “qubits required for Shor” number. They answer different architecture-and-runtime questions.
Why Fault Tolerance Dominates
Section titled “Why Fault Tolerance Dominates”Large modular-exponentiation circuits contain many sequential arithmetic operations. A small physical error rate per operation is not enough: the probability that the entire computation is correct must remain acceptable across a vast logical circuit.
A fault-tolerant implementation must budget:
- logical data storage: encoded registers must survive throughout modular exponentiation;
- non-Clifford operations: Toffoli, CCZ, or synthesized rotations usually consume distilled or cultivated resource states;
- factory throughput: too few factories save qubits but lengthen runtime;
- routing and connectivity: arithmetic operands and resource states must meet without uncontrolled congestion;
- code distance: the logical error per operation must be low enough for the total circuit volume;
- syndrome processing: decoding and feedforward must keep pace with code cycles;
- measurement latency: semiclassical QFT and adaptive arithmetic can depend on classical reactions;
- verification and retries: the physical estimate must include the algorithm’s stochastic success probability.
Changing any one item can move the physical-qubit count or runtime by orders of magnitude. This is why a small noisy demonstration and a cryptographically relevant fault-tolerant computation are different evidence categories, not merely different sizes of the same benchmark.
Universal Gate Sets explains logical synthesis and non-Clifford costs. Later pages on stabilizer codes and the surface code will own the error-correction mechanisms themselves.
What Small Demonstrations Do and Do Not Show
Section titled “What Small Demonstrations Do and Do Not Show”Small experiments can validate coherent modular arithmetic, phase kickback, semiclassical Fourier decoding, and control. They are valuable engineering and pedagogical tests.
However, factoring or another tiny number often permits aggressive compilation: identities specific to the chosen modulus, base, or known period remove most of the arithmetic. A demonstration that embeds information derived from the factors does not implement a scalable black-box factoring algorithm. Smolin, Smith, and Vargo showed how several apparently different small factoring demonstrations could be reproduced by an oversimplified procedure, emphasizing that valid evidence must not use the answer being sought.
For a scalable claim, ask:
- Does the circuit accept a general -bit modulus rather than one hard-coded example?
- Is modular exponentiation implemented reversibly rather than replaced by a precomputed period?
- Are the factors absent from compilation and parameter selection?
- Does the resource count include precision, verification, and retries?
- Which components were demonstrated physically, simulated classically, or only estimated?
The evidence ladder in Claims, Hype, and Evidence Standards provides the broader reporting framework.
Common Mistakes
Section titled “Common Mistakes”- Saying the quantum computer tries all factors and reads the correct one.
- Omitting the classical gcd and continued-fraction steps.
- Forgetting that the selected base can yield an odd order or the useless root .
- Assuming one phase sample always returns the full order.
- Applying continued fractions without verifying the candidate denominator.
- Treating controlled modular powers as unit-cost black boxes.
- Calling the QFT alone Shor’s algorithm.
- Reporting a logical-qubit count as a physical-qubit count.
- Quoting a physical estimate without its error rate, cycle time, connectivity, runtime, and code assumptions.
- Treating a compiled factor- circuit as evidence for scalable modular arithmetic.
- Claiming Shor breaks AES directly or solves all NP-complete problems.
- Presenting post-quantum migration as proof that a cryptographically relevant machine already exists.
End-to-End Checklist
Section titled “End-to-End Checklist”Before evaluating a Shor implementation, record:
- the exact factoring or group-discrete-logarithm problem;
- classical preprocessing and random-base policy;
- the reversible arithmetic circuit;
- control-register precision and Fourier convention;
- continued-fraction or hidden-subgroup postprocessing;
- candidate verification and retry probability;
- logical qubits, gate counts, depth, and non-Clifford volume;
- error-correction, connectivity, timing, and factory assumptions;
- the cryptographic parameter set and classical comparison;
- which claims are theorem, simulation, experiment, estimate, or projection.
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. Separate algorithmic and physical claims
Section titled “7. Separate algorithmic and physical claims”Classify each statement as a theorem-level algorithmic claim or an assumption-dependent engineering estimate:
- factoring has a polynomial-time quantum algorithm;
- a general circuit can be built with logical qubits;
- RSA-2048 can be factored in eight hours with 20 million physical qubits;
- fewer than one million physical qubits can suffice if a runtime below one week is accepted.
Explain what extra information is required to compare statements 3 and 4.
Solution
Statement 1 is the asymptotic algorithmic theorem. Statement 2 is a logical circuit construction with a particular gate and depth tradeoff. Statements 3 and 4 are physical resource estimates derived from selected arithmetic, code, layout, error, timing, factory, and failure-budget models.
To compare 3 and 4, one must align the physical gate error, code-cycle time, classical reaction time, connectivity, error-correcting code, arithmetic method, logical failure target, magic-state method, number of factories, retry policy, and wall-clock constraint. A smaller qubit count may be purchased with greater depth or runtime, so the two headline numbers alone do not establish an across-the-board improvement.
References
Section titled “References”- 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.
- 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.
- 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.
- S. Beauregard, “Circuit for Shor’s algorithm using qubits,” Quantum Information and Computation 3, 175–185, 2003, doi:10.26421/QIC3.2-8.
- M. Roetteler, M. Naehrig, K. M. Svore, and K. Lauter, “Quantum resource estimates for computing elliptic curve discrete logarithms,” in Advances in Cryptology – ASIACRYPT 2017, 241–270, 2017, doi:10.1007/978-3-319-70697-9_9.
- C. Gidney and M. Ekerå, “How to factor 2048 bit RSA integers in 8 hours using 20 million noisy qubits,” Quantum 5, 433, 2021, doi:10.22331/q-2021-04-15-433.
- C. Gidney, “How to factor 2048 bit RSA integers with less than a million noisy qubits,” 2025 research preprint, arXiv:2505.15917.
- J. A. Smolin, G. Smith, and A. Vargo, “Oversimplifying quantum factoring,” Nature 499, 163–165, 2013, doi:10.1038/nature12290.
- National Institute of Standards and Technology, “Announcing approval of three Federal Information Processing Standards for post-quantum cryptography,” August 13, 2024, NIST announcement.