intermediate · Programming · The Quantum Fourier Transform
The General QFT Circuit
Previous lessons built the 2- and 3-qubit QFT one step at a time. Now we write down the
general pattern that scales to any number of qubits n.
The general circuit rule
Label the qubits q0,q1,…,qn−1 with q0 being the most significant bit. The
QFT circuit without bit-reversal SWAPs is constructed by the following loop:
For k=0,1,…,n−1:
Apply H to qubit k.
For j=1,2,…,n−1−k: apply CP(2jπ) with control qubit k
and target qubit k+j.
That is all. For n=3 this expands to:
k=0: H(q0), CP(π/2,q0→q1), CP(π/4,q0→q2).
k=1: H(q1), CP(π/2,q1→q2).
k=2: H(q2) — no controlled-phase gates because no later qubits exist.
Why it works
Recall the product representation of the QFT:
QFTn∣j⟩=2n1k=0⨂n−1(∣0⟩+e2πi0.jn−1−k⋯j0∣1⟩),
where j=jn−12n−1+⋯+j0 in binary and 0.jn−1⋯j0=j/2n is a binary
fraction. Output qubit k must carry the phase e2πi0.jn−1−k⋯j0.
The Hadamard on qk creates the superposition ∣0⟩+eiπjn−1−k∣1⟩, which
supplies the most-significant bit of the required binary fraction. Each subsequent
CP(π/2j) gate — triggered only when both qk and qk+j are ∣1⟩ — adds the phase
eiπjn−1−k−j/2j, contributing the next binary fraction digit. After all n−1−k controlled
rotations, the output qubit k carries exactly the right phase.
Gate count
The loop runs n Hadamards and
∑k=0n−1(n−1−k)=2n(n−1)
controlled-phase gates, for a total of 2n(n+1) gates. This is O(n2),
whereas the classical FFT on the same N=2n-point input costs O(NlogN)=O(n⋅2n)
operations — an exponential improvement in the Fourier subroutine itself.
Try it
The starter code completes qubits 0 and 1. Add the missing Hadamard for qubit 2 to finish the
3-qubit QFT. The grader checks the full unitary matrix, so an incomplete circuit will fail.
Run your code to see the quantum state.
Sign in on the full site to ask questions and join the discussion.