|q⟩ Bad Qubits

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 nn.

The general circuit rule

Label the qubits q0,q1,,qn1q_0, q_1, \ldots, q_{n-1} with q0q_0 being the most significant bit. The QFT circuit without bit-reversal SWAPs is constructed by the following loop:

For k=0,1,,n1k = 0, 1, \ldots, n-1:

  1. Apply HH to qubit kk.
  2. For j=1,2,,n1kj = 1, 2, \ldots, n-1-k: apply CP ⁣(π2j)CP\!\left(\dfrac{\pi}{2^j}\right) with control qubit kk and target qubit k+jk + j.

That is all. For n=3n = 3 this expands to:

Why it works

Recall the product representation of the QFT:

QFTnj=12nk=0n1(0+e2πi0.jn1kj01),\mathrm{QFT}_n |j\rangle = \frac{1}{\sqrt{2^n}} \bigotimes_{k=0}^{n-1} \Bigl(|0\rangle + e^{2\pi i\, 0.j_{n-1-k}\cdots j_0}\,|1\rangle\Bigr),

where j=jn12n1++j0j = j_{n-1} 2^{n-1} + \cdots + j_0 in binary and 0.jn1j0=j/2n0.j_{n-1}\cdots j_0 = j/2^n is a binary fraction. Output qubit kk must carry the phase e2πi0.jn1kj0e^{2\pi i\, 0.j_{n-1-k}\cdots j_0}.

The Hadamard on qkq_k creates the superposition 0+eiπjn1k1|0\rangle + e^{i\pi j_{n-1-k}}|1\rangle, which supplies the most-significant bit of the required binary fraction. Each subsequent CP(π/2j)CP(\pi/2^j) gate — triggered only when both qkq_k and qk+jq_{k+j} are 1|1\rangle — adds the phase eiπjn1kj/2je^{i\pi j_{n-1-k-j}/2^j}, contributing the next binary fraction digit. After all n1kn-1-k controlled rotations, the output qubit kk carries exactly the right phase.

Gate count

The loop runs nn Hadamards and

k=0n1(n1k)=n(n1)2\sum_{k=0}^{n-1}(n-1-k) = \frac{n(n-1)}{2}

controlled-phase gates, for a total of n(n+1)2\dfrac{n(n+1)}{2} gates. This is O(n2)O(n^2), whereas the classical FFT on the same N=2nN = 2^n-point input costs O(NlogN)=O(n2n)O(N \log N) = O(n \cdot 2^n) 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.