|q⟩ Bad Qubits

advanced · Programming · Capstone Projects

Project: End-to-End Shor

Shor's algorithm is the headline result of quantum computing: it factors an nn-bit integer in time polynomial in nn, breaking RSA in principle. Yet most of the algorithm is classical. The only quantum step is order finding — and everything around it is number theory you can run on a laptop. This capstone assembles the full pipeline and asks you to write the classical glue that turns a measured period into a factor.

The reduction: factoring to order finding

Pick an integer 1<a<N1 < a < N coprime to NN (if gcd(a,N)1\gcd(a, N) \neq 1 you already have a factor). Define the order rr as the smallest positive integer with

ar1(modN).a^r \equiv 1 \pmod{N}.

If rr is even, then ar/2a^{r/2} is a square root of 1modN1 \bmod N. Provided ar/2≢1(modN)a^{r/2} \not\equiv -1 \pmod N, it is a nontrivial square root, and

(ar/21)(ar/2+1)=ar10(modN),(a^{r/2} - 1)(a^{r/2} + 1) = a^r - 1 \equiv 0 \pmod N,

so NN divides the product but neither factor alone. Therefore gcd(ar/2±1,N)\gcd(a^{r/2} \pm 1, N) gives a nontrivial factor of NN.

What the quantum part contributes

The order rr is the period of the function f(x)=axmodNf(x) = a^x \bmod N. Quantum phase estimation applied to the modular-multiplication unitary Uay=aymodNU_a|y\rangle = |ay \bmod N\rangle measures a phase s/rs/r for a random ss, and continued fractions recover rr from that estimate. This is the only piece that needs a quantum computer; for a full register of axmod15a^x \bmod 15 the simulator could run it, but at the scale of cryptographic NN it is classically intractable — which is the whole point.

The worked instance N=15N = 15, a=7a = 7

The order of 77 modulo 1515 is r=4r = 4, because

71=7,72=494,732813,74911(mod15).7^1 = 7,\quad 7^2 = 49 \equiv 4,\quad 7^3 \equiv 28 \equiv 13,\quad 7^4 \equiv 91 \equiv 1 \pmod{15}.

Since r=4r = 4 is even, compute ar/2=72=494(mod15)a^{r/2} = 7^2 = 49 \equiv 4 \pmod{15}. As 414=N14 \neq 14 = N - 1, this run succeeds, and

gcd(41,15)=gcd(3,15)=3,gcd(4+1,15)=gcd(5,15)=5.\gcd(4 - 1, 15) = \gcd(3, 15) = 3, \qquad \gcd(4 + 1, 15) = \gcd(5, 15) = 5.

We have factored 15=3×515 = 3 \times 5.

Try it

Implement factorFromPeriod(N, a, r) for the worked instance. Handle the two failure conditions by returning 0, otherwise return the smaller recovered factor. The grader checks you return 33 for N=15N = 15, a=7a = 7, r=4r = 4.

Run your code to see the quantum state.

Sign in on the full site to ask questions and join the discussion.