|q⟩ Bad Qubits

advanced · Programming · Advanced Circuit Construction & Transpilation

Synthesizing Multi-Qubit Gates

The Toffoli (CCX) gate is the quantum AND: it flips its target only when both controls are 1|1\rangle. It is indispensable for oracles, arithmetic, and error correction — yet no superconducting or trapped-ion device implements a native three-qubit gate. Every Toffoli that runs on hardware has first been synthesized out of one- and two-qubit gates.

From CCX to CCZ

The first move is a conjugation identity you met earlier:

CCX=(IIH)CCZ(IIH).\mathrm{CCX} = (I\otimes I\otimes H)\,\mathrm{CCZ}\,(I\otimes I\otimes H).

Sandwiching the target between Hadamards converts the doubly-controlled XX into a doubly-controlled ZZ. CCZ is symmetric and phase-only: it applies a 1-1 exactly to 111|111\rangle. That phase can be distributed among the three qubits as controlled ±π/4\pm\pi/4 rotations, which is where the TT gates enter.

The seven-T construction

The textbook decomposition realizes the interior CCZ with six CNOTs and seven π/4\pi/4-phase gates (TT and its inverse TT^\dagger):

H2open  [CNOT/T ladder]  H2close  [CNOT/T phase-correction].\underbrace{H_2}_{\text{open}}\; \big[\,\text{CNOT/T ladder}\,\big]\; \underbrace{H_2}_{\text{close}}\; \big[\,\text{CNOT/T phase-correction}\,\big].

The alternating CNOT ladder routes the parity of the two controls onto the target, the TT and TT^\dagger gates imprint the ±π/4\pm\pi/4 phases so they constructively combine only on 111|111\rangle, and the final CNOT\mathrm{CNOT}TT/TT^\daggerCNOT\mathrm{CNOT} block cancels the unwanted relative phase between the two control qubits.

Why the order is delicate

Unlike a uniform superposition, this circuit cannot be reordered freely: the CNOTs and TT gates share qubits, so adjacent operations do not commute. Each TT must land between the right pair of CNOTs for the phases to interfere correctly. Get one gate out of place and the circuit still produces some unitary — just not the Toffoli. This is exactly why the grader checks the full 8×88\times 8 matrix rather than a single output state.

Try it

Synthesize CCX\mathrm{CCX} with controls 0, 1 and target 2 using only h, t, tdg, and cx. The grader compares the complete three-qubit unitary up to global phase.

Run your code to see the quantum state.

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