intermediate · Programming · Shor's Algorithm & Period Finding
Factoring 15
Shor's algorithm is the clearest demonstration that quantum computers can break the hardest
problems in classical cryptography. Factoring N=15 is the smallest non-trivial example: it
is small enough to trace by hand yet rich enough to expose every component of the algorithm.
The full Shor pipeline
Shor's algorithm combines classical number theory with a single quantum subroutine. For N=15
the five-step outline is:
Choose a random basea with 1<a<N and gcd(a,N)=1. We pick a=7.
Detect a lucky shortcut. If gcd(a,N)=1 you already have a factor — but with a
composite N that is not a prime power this happens with negligible probability.
Run the quantum period-finding subroutine to find the order r of a modulo N, i.e.
the smallest positive r with ar≡1(modN).
Classical post-processing: from r extract a factor using gcd(ar/2±1,N).
Verify. If the GCD step fails (rare), restart with a different a.
Step 3 in detail: the quantum subroutine
The quantum subroutine uses quantum phase estimation (QPE) applied to the unitary
Ua defined by Ua∣y⟩=∣aymodN⟩. Its eigenstates are the states
∣us⟩=r1∑k=0r−1e−2πisk/r∣akmodN⟩,s=0,1,…,r−1,
with eigenvalue e2πis/r. QPE estimates the phase s/r, and the continued-fraction
algorithm extracts the denominator r from that rational approximation.
For N=15 with a=7 the period is r=4. You can verify this directly:
71≡7,72≡4,73≡13,74≡1(mod15).
A practical QPE circuit for N=15 uses n=⌈log215⌉=4 work qubits in the
target register and t=2n=8 counting qubits for sufficient precision. The full circuit has
hundreds of gates; in this lesson we focus on the classical bookkeeping around the quantum call.
Step 4 in detail: classical post-processing
With the period r=4 in hand, the factoring step is pure arithmetic.
Check applicability. Is r even? Yes, 4 is even. Is ar/2≡−1(modN)?
Compute 72mod15=49mod15=4. Since 4=14≡−1(mod15), the
condition is satisfied.
Apply the difference-of-squares identity. Since ar≡1(modN), we have
Both 3 and 5 are proper factors of 15, and indeed 15=3×5.
Why no classical algorithm matches this
The best classical factoring algorithm for a general integer N is the general number field
sieve (GNFS), which runs in time exp(O((logN)1/3(loglogN)2/3)) — super-polynomial.
Shor's quantum algorithm runs in O((logN)3) gate operations, an exponential improvement.
For N=15 the difference is invisible; for a 2048-bit RSA modulus it means the difference
between a few hours on a fault-tolerant quantum computer and the age of the universe on any
classical machine.
Try it
The quantum subroutine has already run and returned period r=4 for a=7, N=15.
Your task is to complete the classical post-processing step: compute
gcd(ar/2−1,N) using the provided helpers and return the factor.
Run your code to see the quantum state.
Sign in on the full site to ask questions and join the discussion.