|q⟩ Bad Qubits

intermediate · Programming · Shor's Algorithm & Period Finding

From Period to Factors

Shor's algorithm has two parts: a quantum subroutine that finds the period rr of the function f(x)=axmodNf(x) = a^x \bmod N, and a classical post-processing step that converts that period into a factor of NN. This lesson is about the classical step, which relies on a beautiful theorem from number theory.

Why the period gives factors

Suppose gcd(a,N)=1\gcd(a, N) = 1 (otherwise aa itself or N/aN/a is already a factor). The period rr is the smallest positive integer satisfying

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

If rr is even we can write

ar1=(ar/21)(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 the two factors on the right. Unless ar/21(modN)a^{r/2} \equiv -1 \pmod{N} (a failure case), at least one of those factors shares a non-trivial common divisor with NN. The Euclidean algorithm extracts it:

p=gcd ⁣(ar/21,  N).p = \gcd\!\bigl(a^{r/2} - 1,\; N\bigr).

If p1p \neq 1 and pNp \neq N then pp is a proper factor of NN, and we are done. The other factor follows immediately as q=N/pq = N / p.

A worked example: factoring 21

Let N=21N = 21 and a=2a = 2. The quantum period-finding circuit would measure the period r=6r = 6 (since 26=641(mod21)2^6 = 64 \equiv 1 \pmod{21}). Check: 641=63=3×2164 - 1 = 63 = 3 \times 21.

Post-processing:

  1. r=6r = 6 is even, so we proceed.
  2. ar/2=23=8a^{r/2} = 2^3 = 8. Since 8≢120(mod21)8 \not\equiv -1 \equiv 20 \pmod{21}, the condition is satisfied.
  3. gcd(81,  21)=gcd(7,21)=7\gcd(8 - 1,\; 21) = \gcd(7, 21) = 7.
  4. The two factors are 77 and 21/7=321/7 = 3.

Indeed 21=3×721 = 3 \times 7.

Euclidean gcd in JavaScript

The Euclidean algorithm is iterative and takes only a few lines:

function gcd(x, y) {
  while (y !== 0) {
    const t = y;
    y = x % y;
    x = t;
  }
  return x;
}

Each step replaces (x,y)(x, y) with (y,xmody)(y, x \bmod y); when yy reaches zero, xx holds the answer.

Try it

The quantum subroutine has already done the hard work and returned r=6r = 6 for N=21N = 21, a=2a = 2. Implement the classical post-processing and return the non-trivial factor.

Run your code to see the quantum state.

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