Factoring 21 with Shor's algorithm: qubits, periods, and retries
The quantum part finds an order
Shor's factoring algorithm combines a quantum order-finding subroutine with classical arithmetic. For coprime positive integers , the multiplicative order of modulo is the least positive integer satisfying
Our target is . We first use , as in the original article, and discover why even a correctly found order can fail to give a factor. We then use to finish the factorization.
The small circuit below is an illustration of interference, not a register-size prescription for reliable large-number factoring. The full algorithm and its efficiency analysis are given in Peter Shor's original paper.
1. Qubits and measurement
A pure qubit state is
Measurement in this computational basis returns zero with probability and one with probability . The coefficients are amplitudes, not probabilities themselves. A global complex phase does not change the physical pure state; the Bloch sphere describes pure states after this equivalence, rather than arbitrary real unit vectors representing all register states.
Independent registers combine by tensor product. For example,
The four outcome probabilities are , summing to one. This particular state is a product state, not an entangled state. A general multi-qubit state need not factor into a product of individual qubits.
We abbreviate tensor products of basis states using binary strings, or their decimal values when the register width is understood. Thus in a four-qubit register. The symbol can describe a single qubit or a multi-qubit register encoding the integer one, so the register size must be stated.
2. Hadamard gates and controlled operations
The Hadamard gate acts as
Applying it to each qubit of an initially zero -qubit register creates
A controlled operation applies when the control is one and the identity when it is zero. It acts linearly on a superposition, and can create entanglement. A controlled bit flip, for example, maps
Hadamards alone do not implement Shor's algorithm: reversible modular arithmetic, controlled operations, and phase operations for the Fourier transform are also needed.
3. The quantum Fourier transform
On a register with basis states, use the convention
These are unitary transformations. Their phases make some contributions reinforce and others cancel. Order finding uses this interference to obtain information about a period; it does not read out all values calculated in a superposition.
4. Prepare a small order-finding example
Take four control qubits, so , and a five-qubit work register initialized to the integer one. Five qubits are needed for general residues modulo 21, including the value 20. Four work qubits would not suffice; the original text's register counts are inconsistent.
For , define
Because five is coprime to 21, this is a permutation of those 21 basis states. Define to fix the remaining basis states to obtain a unitary permutation on the entire five-qubit register.
Write . The control bit applies , so their product applies and maps the work state one to . The powers are implemented by modular repeated-squaring circuits, not by literally repeating an enormous number of gates.
After the Hadamards and controlled modular operations, the joint state is
The residues repeat with period six:
| | | Control values in this example | | --- | --- | --- | | 0 | 1 | 0, 6, 12 | | 1 | 5 | 1, 7, 13 | | 2 | 4 | 2, 8, 14 | | 3 | 20 | 3, 9, 15 | | 4 | 16 | 4, 10 | | 5 | 17 | 5, 11 |
Thus the grouped state is
The second ket in each product is a five-qubit register. There are sixteen orthogonal joint terms, each with amplitude , so the state is normalized.
We can see the period in a written table, but measuring the state does not return that table: it returns one basis outcome. The algorithm must convert the periodic structure into measurable interference.
5. Fourier interference reveals the period structure
For explanation, imagine measuring the work register. If the result is one, which occurs with probability , the normalized control state becomes
After the inverse QFT, its amplitude at outcome is
Consequently,
This compact normalized expression avoids the missing factors and incorrect expanded coefficients in the source.
More generally, a work outcome selects control values , all below . Their normalized post-measurement state transforms to amplitudes
The prefactor has unit-magnitude phase apart from normalization. The finite geometric sum is large when neighboring phases are nearly aligned:
When the denominator below is nonzero, the squared magnitude of that sum is
At exact alignment its limiting value is . This explains the peaks rather than asserting that the Fourier transform deterministically outputs the period.
The work measurement is optional. Measuring only the transformed control register gives the mixture over the work outcomes. For and , the exact marginal probabilities are approximately:
| Outcomes | Probability of each listed outcome | | --- | --- | | 0, 8 | 0.17187500 | | 3, 5, 11, 13 | 0.11774272 | | 2, 6, 10, 14 | 0.03125000 | | 4, 12 | 0.01562500 | | 1, 7, 9, 15 | 0.00725728 |
They sum to one. The largest peaks lie near multiples of , namely . Other outcomes remain possible, and different conditioned work outcomes need not have identical finite-register distributions.
6. Recovering and checking a candidate order
A measured suggests a rational approximation . A reduced fraction may reveal only a divisor of when and share a factor. The outcome is also uninformative about the order by itself.
For the standard precision argument, choose a sufficiently large power-of-two control range, conventionally . Continued fractions recover candidate denominators from good approximations; candidates must be checked by modular exponentiation, and repetitions or suitable multiples may be needed. The four-control-qubit example has , so recognizing its histogram is not a general guarantee of successful continued-fraction recovery. The precision and postprocessing argument is developed in Shor's order-finding analysis, Section 5.
In this small example, direct arithmetic checks the candidate six:
No earlier power is one, so the order is exactly six. For large inputs, the point of the quantum subroutine is to avoid a linear search through all these powers.
7. Why base five fails to factor 21
Before order finding, compute . A nontrivial gcd already gives a factor; otherwise proceed with a coprime base. If its order is odd, the usual factoring step cannot use , so choose another base.
For even ,
Compute the two gcds with . A nontrivial result between one and is a factor, though not necessarily a prime factor for a general composite input.
For , ,
so
Neither is a nontrivial factor. An even order alone is insufficient: this base's half-order power is minus one modulo the whole input.
8. Retry with base two and finish
For , the order is also six:
Now is neither one nor minus one modulo 21. The gcds are
Therefore
The workflow is: choose a base, check its gcd, find and verify an order, try the half-order gcds, and retry when they are unhelpful. The quantum component supplies information about a period through interference; the final factor extraction is ordinary integer arithmetic.
Related articles
- Equating rational and irrational parts: proof and worked problems
- How to simplify nested square roots, with three worked examples
- Conditional probability: the formula, information protocols, and worked examples
- Integration by parts: formulas, proof, and four useful patterns
- Triple-angle identities: remember, derive, and apply them
About the author
Koki Saito
Physician and graduate of the University of Tokyo Faculty of Medicine. Drawing on his entrance-exam experience, he explains how to choose mathematical methods and construct complete solutions.
Full profile →Have a question or spotted an error? Contact us.