intermediate · Programming · Shor's Algorithm & Period Finding
Continued Fractions
After the quantum period-finding circuit runs and you measure the ancilla register, you do not read
off the period r directly. What you get is an integer m close to a multiple of Q/r, where Q
is the size of the ancilla register. Recovering r from m is a classical step that relies on the
continued-fraction algorithm.
What the measurement tells you
Suppose the ancilla has n qubits, so Q=2n. The QFT concentrates probability near the
multiples kQ/r for k=0,1,…,r−1. A single measurement gives some integer m that
satisfies
Qm−rk≤2Q1
for some unknown integer k with 0≤k<r. Dividing both sides shows that m/Q is
within 1/(2Q) of the rational number k/r. Because r≤N and we choose Q≥N2,
this bound is tight enough to uniquely identify k/r from m/Q via continued fractions.
Continued fractions in one paragraph
Every real number x has a continued-fraction expansion
x=a0+a1+a2+⋱111
where a0=⌊x⌋ and the process repeats on the fractional part. The truncated
expansions pj/qj (called convergents) are the best rational approximations to x with
denominator at most qj. The classical algorithm computes them in O(logQ) steps using the
Euclidean algorithm.
The algorithm step by step
Given integer m and register size Q, proceed as follows:
Set the working fraction to m/Q (track numerator and denominator as integers).
Compute partial quotients ai=⌊num/den⌋ and update via
(num,den)←(den,num−ai⋅den).
Build convergent denominators with the recurrence
qi=aiqi−1+qi−2,q−1=0,q0=1.
Stop at the first qi that exceeds N; the previous qi−1 is the candidate period.
Verify classically that aqi−1≡1(modN); if not, re-run the circuit.
A concrete example
Take N=15, a=7, and n=8 qubits so Q=256. The true period is r=4 (since
74=2401≡1(mod15)). The QFT peaks near multiples of Q/r=64.
For the measurement m=63: the fraction is 63/256. Step by step:
We return q1=4. Indeed 74mod15=1, so r=4 is confirmed.
Try it
Implement the continued-fraction convergent finder: given m, Q, and bound N, return the
denominator of the best convergent of m/Q whose denominator does not exceed N.
Run your code to see the quantum state.
The grader checks that your function returns 4 for the example above (m=63, Q=256, N=15),
which is the period r=4 of 7xmod15.
Sign in on the full site to ask questions and join the discussion.