# How to make Toffoli gate using matrix form in multi qubits system?

I wonder that there is generalized form to make Toffoli gate in multi-qubits system even if the two control qubits and one target qubit are not adjacent. In Wikipedia there is one way to make Toffoli gate with Hadamard, T gate and CNOTs, but I want to know how to make it for any case (i.e generalized version).

• Can you specify what you mean by a generalised way? – vasjain Aug 2 at 12:49
• If control qubits are 1st,2nd and target qubit is 4th then how I can make toffoli gate in matrix form? – 김동민 Aug 2 at 12:51
• are you asking how to find the matrix representation of a Toffoli between an arbitrary triple of qubits, or something else? – glS Aug 3 at 12:19

My understanding of the OP's question is that there is some restriction imposed that a gates can only act on Adjacent Qubits. While this isn't necessary, we can still work with this restriction using SWAP gates to make non-adjacent qubit adjacent.

If the Control qubits are $$i$$ and $$j$$; and target qubit is $$k$$. Such that $$i+1 and $$j+1. Then we can use SWAP gates to bring these qubits closer.

If there is a distance between $$i$$ and $$j$$ i.e $$j-i-1>0$$, then we can use $$j-i-1$$ SWAP gates to bring the states of these qubits closer and apply the gate. Then another $$j-i-1$$ SWAP gate can be used to transfer the state back to its original position. This system is described for 2 qubits but can work for 3 qubits in case of a Toffoli Gate.

Example: We have 7 qubits $$q_i$$, $$i\in \{0,1,2,3,4,5,6\}$$. We need to apply a $$Toffoli$$ Gate to $$q_5$$ with $$q_0$$ and $$q_3$$ as control.

Then the original state of the system is $$q_0q_1q_2q_3q_4q_5q_6$$.

We can apply the $$CCNOT$$ gate as follows

1. We apply SWAP gate to $$q_0$$ and $$q_1$$ resulting in state $$q_1q_0q_2q_3q_4q_5q_6$$.
2. We apply SWAP gate to $$q_0$$ and $$q_2$$ resulting in state $$q_1q_2q_0q_3q_4q_5q_6$$.
3. We apply SWAP gate to $$q_4$$ and $$q_5$$ resulting in state $$q_1q_2q_0q_3q_5q_4q_6$$.
4. We apply CCNOT gate on $$q_0,q_3,q_5$$ and now $$q_5 \rightarrow q_5'$$ resulting in state $$q_1q_2q_0q_3q_5'q_4q_6$$.
5. We apply SWAP gate to $$q_5'$$ and $$q_4$$ resulting in state $$q_1q_2q_0q_3q_4q_5'q_6$$.
6. We apply SWAP gate to $$q_0$$ and $$q_2$$ resulting in state $$q_1q_0q_2q_3q_4q_5'q_6$$.
7. We apply SWAP gate to $$q_0$$ and $$q_1$$ resulting in state $$q_0q_1q_2q_3q_4q_5'q_6$$.

In this manner you can apply $$CCNOT$$ gate to non-adjacent qubits using $$SWAP$$ gates.

Note: Just to be clear SWAP gates do not switch qubits but they are unitaries whose effect is that the state of the 2 qubits is swapped. To know more about SWAP Gates see this