The Order-Finding Subroutine
Suppose you are handed an integer coprime to . You are asked for the smallest positive integer such that . This is the order-finding problem. No classical algorithm is known that solves it in time polynomial in . Every known classical approach either factors first or searches exponentially many candidate exponents. The best general-purpose classical methods run in sub-exponential but still super-polynomial time. Order finding looks like a narrow number-theoretic curiosity. But it is the computational heart of Shor's Factoring Algorithm. Once you can find multiplicative orders efficiently, factoring large integers becomes tractable. So does breaking RSA-style public-key cryptography. This single subroutine is the reason quantum computers threaten a large fraction of deployed internet cryptography. That is why every major standards body now tracks progress toward fault-tolerant machines. Such machines would need to run it at cryptographic scale. The quantum solution combines two ideas you should already have in hand. The first is Quantum Phase Estimation, which extracts eigenvalue phases of a unitary to high precision. The second is the classical theory of Continued Fractions, which recovers exact rationals from their decimal (or binary) approximations. The trick is to build a unitary whose eigenphases encode . Then run phase estimation to estimate one such phase. Finally, use a continued-fraction expansion to pull the integer out of that noisy estimate. This article gives the complete circuit-level construction. It covers the modular exponentiation unitary, the phase estimation wrapper, and the classical post-processing. It also gives a full correctness and complexity analysis. This analysis shows why quantum gates (with efficient modular exponentiation) suffice. Classical methods, by contrast, need far more.
- Order finding asks for the smallest with ; classically hard, quantumly efficient.
- The unitary has eigenphases that are exact multiples of .
- Quantum phase estimation on yields a -bit approximation to for a random integer .
- The continued-fraction expansion of that approximation recovers in lowest terms in classical time.
- Repeating times and taking the LCM of candidate denominators finds with high probability.
- This subroutine, wrapped in modular exponentiation, is exactly the quantum core of Shor's factoring algorithm.
Order finding works because the periodicity of modular exponentiation shows up as an exact eigenphase of a unitary, which quantum phase estimation can read out and continued fractions can decode into the period itself.
The idea
Fix and an integer with . The multiplicative order of modulo , written , is the smallest positive integer such that . Such an always exists (by Euler's theorem, ), and the sequence is periodic with period exactly . Order finding is precisely the task of computing this period given and . The key structural fact is this: consider the unitary operator acting on the -qubit register of integers mod (padded up to dimension ) defined by
and acting as the identity (or arbitrarily, as long as it stays unitary) on basis states with . Because is invertible mod , this map is a permutation of , hence is a genuine unitary (a permutation matrix) on that subspace. Since , we have on that subspace, so every eigenvalue of restricted there is an -th root of unity: for . The problem of finding becomes the problem of reading off one of these eigenphases and recognizing the denominator hiding inside it. Phase estimation is built exactly for this: given a unitary and an eigenstate with , it produces an estimate of . The catch is that we do not have direct access to a single eigenstate of — we can only prepare basis states, which are superpositions of eigenstates. It turns out this is not a problem: preparing (or any convenient computational basis state coprime-compatible with the cycle structure) as the phase-estimation input state is an equal superposition over the eigenstates of with a specific, uniform distribution of eigenvalues , . Phase estimation on this input therefore collapses, upon measurement, to a random and reports (an estimate of) . The remaining work is to recover from noisy knowledge of , and that is exactly what the continued fraction algorithm does: given a good rational approximation to , it reconstructs in lowest terms, from which is read off as the denominator (after ruling out common-factor degeneracies).
How it works
The full algorithm has a quantum stage (phase estimation on modular exponentiation) and a classical stage (continued fractions plus a repeat-and-verify loop).
Setup. Let be the modulus, so an -qubit register can hold any residue mod . Choose the phase-estimation precision register to have qubits (enough bits to make continued-fraction recovery unique with high probability; the "+1" is a small safety margin used in the standard analysis).
Step 1 — Prepare registers. Initialize a -qubit control register in and an -qubit target register in (a convenient basis state, since generates a cyclic subgroup interaction with every ).
Step 2 — Superposition on the control register. Apply Hadamard to every control qubit, producing
Step 3 — Controlled modular exponentiation. Apply the unitary
implemented as a cascade of controlled- operations (the standard phase-estimation trick), each conditioned on one bit of : qubit of the control register controls an application of , i.e. "multiply the target register by if that control bit is 1." This is exactly repeated modular squaring — the same fast-exponentiation trick used classically — realized reversibly as a quantum circuit. The result is
Step 4 — Inverse QFT on the control register. This is the phase-estimation readout step: apply to the control qubits and measure them in the computational basis, yielding a -bit integer .
Step 5 — Classical continued-fraction recovery. Compute and expand it as a continued fraction; take successive convergents until you find one with that is a strong candidate for in lowest terms. Output the denominator as a candidate order .
Step 6 — Verify and repeat. Check . If not (or if made a proper divisor of rather than itself), repeat the whole procedure a small number of times and take the least common multiple of the candidate denominators obtained, then verify that LCM against . ``` function ORDER-FIND(a, N): n ← ceil(log2(N)) t ← 2n + 1 # precision register size repeat up to M = O(log log N) times:
# --- quantum phase estimation stage --- prepare control register C of t qubits in |0...0> prepare target register T of n qubits in |1> apply H to every qubit of C for i in 0 .. t-1: apply controlled-U_a^(2^i) with control = C[i], target = T
# U_a^(2^i) |y> = |a^(2^i) * y mod N>, realized via
# repeated modular squaring, computed reversibly apply inverse-QFT to C measure C, obtaining integer y in [0, 2^t - 1]
# --- classical post-processing stage --- phi ← y / 2^t (p, q) ← BEST-CONVERGENT(phi, max_denominator = N)
# continued-fraction expansion of phi,
# returns the convergent p_i/q_i with q_i < N
# closest to phi candidates.append(q) r ← LCM(candidates) if a^r mod N == 1 and r > 0: return r else: return FAIL # retry ORDER-FIND from scratch ``` ``` function BEST-CONVERGENT(phi, max_denominator):
# standard continued fraction expansion of phi a0 ← floor(phi) terms ← [a0] x ← phi - a0 p_prev, q_prev ← 1, 0 p_cur, q_cur ← a0, 1 while q_cur <= max_denominator and x != 0: x ← 1 / x ai ← floor(x) p_next ← ai p_cur + p_prev q_next ← ai q_cur + q_prev if q_next > max_denominator: break p_prev, q_prev ← p_cur, q_cur p_cur, q_cur ← p_next, q_next x ← x - ai return (p_cur, q_cur) ``` The controlled- gates are the only "arithmetic" part of the circuit: each is a reversible modular multiplication by a fixed classical constant (itself precomputed classically, once, by repeated squaring), implemented with reversible adders and reversible modular reduction circuits — standard building blocks with known polynomial-size constructions.
Complexity & correctness
Correctness — why the phases are exact multiples of . Because restricted to the cyclic set is a cyclic permutation of order , its eigenvalues on the span of these basis states are exactly the -th roots of unity for , with eigenvectors
A direct check confirms . The initial state decomposes as the equal-weight superposition . Running phase estimation on this input is, by linearity, equivalent to running it on a uniformly random : the measured control register collapses to an estimate of for a uniformly random .
Why continued fractions recover . Phase estimation with control qubits produces such that approximates to within with probability at least (the standard phase estimation error bound), and with the choice , the approximation error satisfies
because implies . A classical theorem on continued fractions guarantees: if for coprime integers , then is necessarily one of the convergents of the continued-fraction expansion of . Since (in lowest terms, dividing out ) satisfies this bound, the convergent-search step is guaranteed to encounter it. The algorithm scans convergents with denominator and returns the appropriate one — this recovers where , a divisor of , not necessarily itself.
Why repetition fixes the issue. If happens to share a common factor with , the recovered denominator is a proper divisor of , not . However, is uniform on , and it is a standard fact that a uniformly random satisfies with probability at least (via bounds on the density of integers with few or large prime factors relative to type arguments — concretely, the probability that reduces to something with denominator exactly is bounded below by a constant fraction over independent trials in expectation). Running the quantum stage times and taking the LCM of the resulting candidate denominators drives the failure probability down to an arbitrarily small constant, and a final classical check certifies success — false accepts are impossible since verification is exact.
Time complexity.
- Quantum circuit size: control qubits, and controlled modular-exponentiation gates, each a reversible modular multiplication circuit of size (schoolbook) or (fast multiplication), giving total gate count (or with fast arithmetic).
- Inverse QFT: gates (or with the approximate QFT).
- Classical continued-fraction expansion: Euclidean-algorithm-style steps, each with -time big-integer arithmetic (or with fast algorithms), so total — negligible compared to the quantum circuit.
- Repetitions: , an essentially negligible multiplicative overhead.
Overall, order finding runs in elementary gates (), i.e. polynomial in — exponentially faster than the best known classical algorithms, which require time super-polynomial in (subexponential, roughly -notation complexity like general number-field-sieve-style bounds for related problems, though order finding specifically has no known polynomial classical algorithm and no proof of hardness either — it is an unproven, empirically robust separation).
Space complexity. qubits: for the control register and for the target register, plus ancilla qubits for the reversible arithmetic circuits (garbage collection of ancillas is possible via standard reversible-computation techniques, keeping the total workspace linear in ).
Honest tradeoffs. The polynomial gate count hides a large constant: fault-tolerant modular exponentiation on cryptographically-sized (2048-bit RSA moduli) requires millions of logical qubit-operations and, with current error-correction overheads, potentially billions of physical gate operations. The algorithm is probabilistic — repetition and verification are mandatory, not optional — and its correctness relies on classical arithmetic (GCD, LCM, verification) being cheap and exact, which they are, but errors in the quantum part (decoherence, gate infidelity) are not corrected by the classical post-processing and must be handled by Quantum Error Correction beneath this algorithm.
Worked example
Take , . First check : yes. The true order is found by direct computation:
| 0 | 1 |
| 1 | 2 |
| 2 | 4 |
| 3 | 8 |
| 4 | 16 |
| 5 | 11 |
| 6 | 1 (cycle repeats) |
So : the true order of mod is . Now trace the quantum algorithm conceptually. We need qubits for the target register, and control qubits, giving possible measurement outcomes for . The eigenphases of on the cycle are for . Suppose the measurement collapses to (a case with , the "clean" case). Phase estimation ideally would give . Concretely , so a likely measured value is , giving
Run the continued fraction expansion of :
| step | integer part | remainder | convergent |
|---|---|---|---|
| 0 | |||
| 1 | |||
| 2 | |||
| 3 | (denominator jumps past , stop) |
The first convergent with denominator that closely matches is , obtained at step 2, exactly the true . The algorithm outputs candidate denominator .
Verification. Check . ✓ Success — is confirmed on the first attempt, no repetition needed. Now consider a "unlucky" branch: suppose instead the measurement had collapsed to , where . Then in lowest terms, and the continued-fraction search returns , a proper divisor of the true order. A single run reports the wrong order (, so the verification step would actually catch this directly!). This is exactly why Step 6 (verify, and if needed repeat and take LCMs) exists: with two independent runs, one landing on (denominator 6) and another on (giving in lowest terms, denominator 3), recovers the correct order even if a single run alone was ambiguous.
Common pitfalls & traps
| Pitfall | What goes wrong | Fix |
|---|---|---|
| Using too few control qubits | too small means doesn't approximate tightly enough for the continued-fraction theorem to apply | Use |
| Forgetting to verify the candidate | A collapse silently returns a proper divisor as if it were | Always check before accepting |
| Treating a single run as sufficient | Success probability per run is only , not high | Repeat times and take LCM of candidates |
| Confusing the eigenphase with the measured bitstring directly | is an integer in , not the phase itself; skipping the division by breaks everything downstream | Always compute before continued-fraction expansion |
| Implementing naively as sequential applications of | Blows up circuit depth to instead of | Precompute classically once, build a single modular-multiplication-by-constant circuit per control bit |
| Choosing not coprime to | is not a bijection on , hence not unitary in the intended way | Check first (if not, is itself a nontrivial factor of — useful in the factoring context but breaks order finding as stated) |
Pioneers & history
Origins · 1 minPeter Williston Shor and how this was discovered
Peter Shor devised the full factoring algorithm — of which order finding is the quantum core — while at Bell Laboratories, building directly on prior quantum Fourier transform and phase estimation ideas developed by Coppersmith, Deutsch, and Simon. His 1994 result is widely regarded as the single most consequential theoretical result in quantum computing, since it gave the first strong evidence that a working quantum computer could break the cryptographic assumptions underlying RSA.
Where this matters
Order finding is not deployed in production systems today, because no quantum computer yet has enough error-corrected qubits to run it on cryptographically relevant moduli — but its threat model already shapes real infrastructure decisions. Standards bodies such as NIST have run multi-year competitions to select post-quantum cryptographic algorithms (lattice-based schemes like Kyber and Dilithium) precisely because Shor's algorithm, built on this subroutine, would break RSA and elliptic-curve cryptography outright given a sufficiently large fault-tolerant quantum computer. Financial institutions, governments, and browser vendors are actively migrating TLS and VPN protocols to hybrid classical/post-quantum schemes today, years before such a machine might exist, as a direct consequence of this algorithm's existence. On the research side, order finding (and its close cousin, the abelian Hidden Subgroup Problem) is the canonical example used to teach the power of the quantum Fourier transform, and every subsequent quantum algorithm with exponential speedups over classical methods for algebraic problems — discrete logarithm, Pell's equation, certain hidden shift problems — reuses the same phase-estimation-plus-continued-fractions template. Experimental groups building superconducting, trapped-ion, and photonic quantum processors use small-scale factoring demonstrations (factoring 15, 21, and similar small numbers) as benchmark tasks that exercise controlled modular arithmetic, phase estimation, and measurement — making order finding one of the most-implemented "hard" quantum subroutines in the experimental literature, even at toy scale.
Ask the tutor: How does the choice of affect the probability that order finding succeeds on a given attempt, and why does averaging over random matter for the factoring reduction?
Why must and be coprime for order finding to make sense?
If , then is not invertible modulo , so the map is not a bijection on — some residues have no preimage. The operator as defined would then fail to be unitary on that subspace, because unitary matrices must be invertible (norm-preserving bijections), and a non-injective linear map cannot be norm-preserving on the full space. Practically, if is discovered first, that GCD is already a nontrivial factor of , so order finding is unnecessary — this is one of the branches Shor's algorithm checks before invoking the quantum subroutine at all.
Why does the algorithm use control qubits rather than just ?
Phase estimation accuracy scales with the number of control qubits: with qubits, the estimate lands within of the true phase with high probability. The continued-fraction recovery theorem requires the approximation error to be strictly less than , and since , this demands to be comparably larger than . Choosing gives exactly this margin. Using only qubits would give resolution , far too coarse to distinguish nearby fractions once approaches in size.
What happens if the algorithm fails — does it give a wrong answer or detect failure?
It detects failure, and this is a key design feature. The final classical step checks exactly, using ordinary modular exponentiation, which is cheap and completely reliable classically. If the check fails, the algorithm does not output a wrong answer — it reports failure and retries the entire quantum-plus-classical pipeline. This makes order finding a Monte Carlo algorithm with zero-error verification: any output it does return is guaranteed correct, and only the running time is randomized.
How does order finding connect to factoring , foreshadowing Shor's algorithm?
If is even, and , then and are (with high probability over random choice of ) nontrivial factors of . This follows because , but neither factor alone is , forcing 's prime factors to split between the two GCDs. Order finding is thus the one genuinely quantum ingredient; everything else in factoring is classical number theory wrapped around it.
Could this algorithm be run on a small quantum computer today for real cryptographic moduli?
No. Factoring a 2048-bit RSA modulus would require an -bit target register, roughly control qubits, and reversible modular exponentiation circuits with millions of logical gates, all executed with error rates low enough to survive that many operations. Current quantum hardware, even with error correction, is many orders of magnitude away from this scale. Demonstrations to date have factored numbers like 15 or 21 — instructive but cryptographically meaningless — precisely to exercise this subroutine's circuit structure at toy scale.
Is there a known proof that no classical algorithm can solve order finding efficiently?
No such proof exists. Order finding's classical hardness is a widely believed but unproven conjecture, closely tied to the conjectured hardness of integer factorization — the two problems are polynomial-time equivalent in a certain sense (an efficient order-finding oracle yields efficient factoring, and vice versa for many practical cases). No lower bound rules out a clever classical polynomial-time algorithm; the belief in hardness rests on decades of failed attempts and the problem's deep structural similarity to factoring and discrete logarithm, both cornerstones of modern cryptography.
Why is the input state used rather than an explicit eigenstate of ?
Explicit eigenstates are complex superpositions over the entire cycle and are just as hard to prepare directly as the answer itself — you would need to know to build them. The state is trivial to prepare and happens to equal the uniform superposition of all with equal amplitude . Phase estimation then effectively samples a uniformly random eigenstate for free, at the cost of only needing repetition to handle the cases where the sampled shares a factor with .