Skip to content

Shor's algorithm

Multiplying two large prime numbers is easy. Recovering the primes from their product is, as far as anyone knows, extremely hard for a classical computer: the best known methods take a time that grows faster than any polynomial in the number of digits. Much of the cryptography in use today relies on that gap.

In 1994 Peter Shor showed that a quantum computer could factor in polynomial time. This lesson explains how. Most of the algorithm is classical number theory. The quantum part is one subroutine, and you have already met it: phase estimation.

Let NN be the number to factor. Arithmetic modulo NN means keeping only the remainder after dividing by NN. We write a≡b(modN)a \equiv b \pmod N when aa and bb leave the same remainder.

Pick a number aa between 2 and N−2N - 2 that shares no factor with NN. (If it does share one, the greatest common divisor gcd⁡(a,N)\gcd(a, N) is already a factor, and you are finished.) Now look at the powers of aa modulo NN. For N=15N = 15 and a=7a = 7:

70,71,72,73,74,…  ≡  1, 7, 4, 13, 1, 7, 4, 13, …7^0, 7^1, 7^2, 7^3, 7^4, \dots \;\equiv\; 1,\ 7,\ 4,\ 13,\ 1,\ 7,\ 4,\ 13,\ \dots

The sequence repeats. The smallest r>0r > 0 with ar≡1(modN)a^r \equiv 1 \pmod N is called the order of aa, and it is the period of the sequence. Here r=4r = 4.

The order gives the factors, by a piece of school algebra. Suppose rr is even. Then

ar−1=(ar/2−1)(ar/2+1)≡0(modN).a^r - 1 = \bigl(a^{r/2} - 1\bigr)\bigl(a^{r/2} + 1\bigr) \equiv 0 \pmod N.

So NN divides the product of two numbers. It cannot divide the first, because then ar/2≡1a^{r/2} \equiv 1 and the order would be r/2r/2. If it does not divide the second either, then the prime factors of NN must be split between the two, and

gcd⁡(ar/2−1, N)andgcd⁡(ar/2+1, N)\gcd\bigl(a^{r/2} - 1,\ N\bigr) \quad\text{and}\quad \gcd\bigl(a^{r/2} + 1,\ N\bigr)

are proper factors of NN. Greatest common divisors are quick to compute, by Euclid’s algorithm.

For N=15N = 15 and a=7a = 7: 72≡47^2 \equiv 4, and gcd⁡(3,15)=3\gcd(3, 15) = 3, gcd⁡(5,15)=5\gcd(5, 15) = 5.

The method fails if rr is odd, or if ar/2≡−1a^{r/2} \equiv -1. Then you pick another aa. For an odd NN that is not a power of a prime, at least half of all choices of aa work.

Check

For N=21N = 21 and a=2a = 2 the powers are 1,2,4,8,16,11,1,…1, 2, 4, 8, 16, 11, 1, \dots Which pair of numbers gives the factors?

Everything so far is classical and fast, except for one step: finding rr. The order can be nearly as large as NN itself. For a number with hundreds of digits, stepping through the sequence until it repeats is hopeless, and no efficient classical method for finding the order is known. This is the step given to the quantum computer.

Consider the operation “multiply by aa modulo NN”, acting on a register that holds a number yy:

U∣y⟩=∣a y mod N⟩.U\ket{y} = \ket{a\,y \bmod N}.

Because aa shares no factor with NN, this operation can be undone, by multiplying by the inverse of aa. It shuffles the numbers below NN among themselves, and a reversible shuffle of basis states is a unitary gate.

Multiplying by 2 modulo 15 happens to be especially simple. On four bits it moves every bit one place to the left, and the top bit wraps around to the bottom, because 2×8=16≡12 \times 8 = 16 \equiv 1.

PuzzleMultiply by 2 modulo 15

The wires hold the bits of a number, with place values 8, 4, 2 and 1. The register starts at 1. Build a circuit that doubles it modulo 15, giving 2. Your circuit is also tested on 2, 4, 8 and 7, which should become 4, 8, 1 and 14.

This puzzle needs JavaScript.

Hint

Each wire must end up holding what the wire below it held, and the bottom wire must receive what was on the top one. Start with a swap of the top two wires.

Apply that circuit four times and every number comes back to where it started: U4=IU^4 = I. That is the statement that 2 has order 4 modulo 15. The order of aa is hidden in the gate UU, and specifically in its eigenvalues.

For a general aa and NN, the gate UU is not a few swaps. It is a full circuit for modular multiplication, built from quantum versions of adders. Those circuits account for nearly all the cost of Shor’s algorithm.

Since applying UU exactly rr times does nothing, every eigenvalue of UU is an rr-th root of 1. The eigenstates are superpositions of the numbers in the sequence 1,a,a2,…1, a, a^2, \dots with steadily winding phases:

∣us⟩=1r∑k=0r−1e−2πi sk/r∣ak mod N⟩,U∣us⟩=e2πi s/r∣us⟩,\ket{u_s} = \frac{1}{\sqrt r}\sum_{k=0}^{r-1} e^{-2\pi i\,sk/r}\ket{a^k \bmod N}, \qquad U\ket{u_s} = e^{2\pi i\,s/r}\ket{u_s},

for s=0,1,…,r−1s = 0, 1, \dots, r - 1. You can check the eigenvalue by applying UU, which shifts every term along the sequence by one place.

The phase of ∣us⟩\ket{u_s} is φ=s/r\varphi = s/r. Phase estimation on UU would read out a fraction whose denominator is the order we want.

Two problems remain, and both have neat answers.

We cannot prepare ∣us⟩\ket{u_s}. Writing it down requires knowing rr. But add all rr of these eigenstates together and the phases cancel on every term except k=0k = 0:

1r∑s=0r−1∣us⟩=∣1⟩.\frac{1}{\sqrt r}\sum_{s=0}^{r-1}\ket{u_s} = \ket{1}.

The plain basis state ∣1⟩\ket{1} is an equal superposition of all the eigenstates. And as the last lesson showed, phase estimation on a superposition of eigenstates returns the phase of one of them at random. So we start the register in ∣1⟩\ket{1} and get back s/rs/r for a random ss.

Phase estimation needs high powers of UU. With tt counting qubits it needs U2t−1U^{2^{t-1}}, and applying UU that many times would take exponentially long. But U2kU^{2^k} is just multiplication by the number a2k mod Na^{2^k} \bmod N, and a classical computer finds that number with kk squarings. Each controlled power costs one modular multiplication, however high the power. This is the shortcut that makes the whole algorithm efficient.

Check

Why does the algorithm start the lower register in the state ∣1⟩\ket{1}?

There is a second way to see the same circuit. The controlled powers compute ∣x⟩∣ax mod N⟩\ket{x}\ket{a^x \bmod N} for every xx in superposition. The values xx that share the same axa^x form a comb with period rr and an unknown offset. The Fourier transform turns that comb into peaks at the multiples of Q/rQ/r, where QQ is the size of the counting register, and removes the offset. This is the picture from the Fourier transform lesson, and it describes the same computation.

The counting register has Q=2tQ = 2^t values. Measuring it gives a number yy with

yQ≈sr.\frac{y}{Q} \approx \frac{s}{r}.

We know yy and QQ and want rr. The tool is the continued fraction expansion, a classical method that lists the best approximations to a number by fractions with small denominators. Take QQ to be at least N2N^2. Then whenever yy is the whole number nearest to a multiple of Q/rQ/r, which is the likely case, the closest fraction to y/Qy/Q with denominator below NN is s/rs/r itself. Its denominator is the order.

One catch: fractions come out in lowest terms. If ss and rr share a factor, as in 2/4=1/22/4 = 1/2, the denominator is only a divisor of rr. A quick check that ar≡1a^r \equiv 1 catches this, and trying small multiples or running the circuit again fixes it.

The simulator below does not simulate the gates. It computes the outcome probabilities directly from the period, which is what a classical computer can afford to do for numbers this small, and then follows the classical steps exactly as the real algorithm would.

SimulatorFactoring by period finding
Each press is one run of the quantum circuit.

Things to try:

  1. With N=15N = 15 and a=7a = 7, press Measure once several times. Which outcomes occur, and which of them reveal the period?
  2. Choose N=21N = 21 and a=2a = 2. The period 6 does not divide Q=512Q = 512. Look at the peaks, and check that the continued fraction still finds 6.
  3. Choose N=21N = 21 and a=5a = 5, then a=4a = 4. Why does each of these fail?
  4. Try N=55N = 55. How often does a single run succeed?
  1. Pick a random aa. If gcd⁡(a,N)>1\gcd(a, N) > 1, you have a factor.
  2. Quantum step. Run phase estimation on multiplication by aa, starting from ∣1⟩\ket{1}, and measure yy.
  3. Use continued fractions on y/Qy/Q to get a candidate for the order rr. Check it, and repeat step 2 if needed.
  4. If rr is odd or ar/2≡−1a^{r/2} \equiv -1, go back to step 1.
  5. Compute gcd⁡(ar/2±1,N)\gcd(a^{r/2} \pm 1, N).

For an nn-bit number the circuit uses on the order of n3n^3 gates with schoolbook arithmetic, and a few repetitions suffice. The best known classical algorithm takes a time that grows faster than any polynomial in nn. Nobody has proved that factoring is hard classically, so the speedup is over the best known method. Even so, it was the first large quantum speedup for a problem people already cared about, and it launched the field.

Not close yet, and it is worth being exact about why.

What has been done. Quantum hardware has factored numbers such as 15 and 21. Those demonstrations used circuits that were simplified with knowledge of the answer, so they show the principle and are not evidence of a useful capability.

What is needed. Factoring a 2048-bit RSA modulus takes thousands of error-corrected logical qubits running billions of gates. Each logical qubit is built from many physical ones (see the error correction track). Published estimates of the total have fallen sharply as the methods improved, from around twenty million physical qubits in 2019 to under a million in 2025, under assumptions about hardware quality that have not yet been met at scale. Present machines have from hundreds to a few thousand physical qubits and cannot yet sustain computations of that length.

What it would break. A variant of the same algorithm solves the discrete logarithm problem, so it breaks RSA, Diffie–Hellman and elliptic-curve cryptography together: almost all public-key cryptography deployed before the 2020s. It does not break symmetric ciphers or hash functions, which face only the much weaker quadratic speedup of Grover’s search.

What is being done about it. Data encrypted today can be recorded and decrypted later, so the migration to post-quantum cryptography, which rests on problems with no known quantum shortcut, is already under way.

Shor’s algorithm works because factoring has hidden periodic structure for interference to find. Most problems have no such structure. The next lesson looks at what a quantum computer can do for a problem with no structure at all.

RecallAnswer from memory, then check
LessonFinish this lesson