intermediate · Programming · Shor's Algorithm & Period Finding
Modular Exponentiation
Shor's algorithm factors an integer N by finding the period of the function
f(x)=axmodN for a randomly chosen base a. Before the quantum part can shine,
a classical circuit must evaluate f(x) for every x in superposition. That building block is
called modular exponentiation.
What modular arithmetic means
The expression axmodN asks: raise a to the power x, then take the remainder on
dividing by N. For example,
Because there are only N possible remainders (0,1,…,N−1), the sequence of values
f(0),f(1),f(2),… must eventually repeat. The length of that repeating block is the
periodr, defined by
ar≡1(modN).
For a=7, N=15 you can check that 74=2401=160×15+1, so r=4.
Repeated squaring
Computing axmodN directly by multiplying a together x times is far too slow for
large x. Repeated squaring (also called fast modular exponentiation) reduces the cost to
O(logx) multiplications by exploiting the binary representation of x:
a13=a8+4+1=a8⋅a4⋅a1.
The algorithm squares the running base and takes its remainder mod N at each step, multiplying
it into the running result whenever the current low bit of the exponent is 1:
In the full Shor algorithm the quantum register holds a superposition
∑x=02n−1∣x⟩∣0⟩. A controlled unitary then maps this to
∑x∣x⟩∣axmodN⟩ in one step — but the gate that performs this mapping
is exactly the quantum version of modular exponentiation. Understanding the classical algorithm
is the first step to understanding how that controlled unitary is constructed.
Try it
Implement the classical modpow(a, x, N) function using repeated squaring and return
74mod15. The grader checks that your answer equals 1.
Run your code to see the quantum state.
Sign in on the full site to ask questions and join the discussion.