I want to implement two Toffoli gates with 4 qubits: 3 serving as control qubits (the 2 hadamard coins and one other qubit) and the last one as target qubit and 3 qubits (2 coins 1 target qubits) as shown below :

enter image description here

Is there a way of achieving this with qiskit's ccx function ? I tried :

qnodes = QuantumRegister(2) qsubnodes = QuantumRegister(2) qc.ccx(subnode[0], subnode[1], q[1]) if (q[1] ==1) : qc.x(q[0]) qc.x(q[1]) qc.ccx(subnode[0], subnode[1], q[1])

  • $\begingroup$ Hi and welcome to Quantum Computing SC. You can use one Toffoli to "add" two qubits and "save" the result in an ancilla qubit, then apply another Toffoli "adding" result in the ancilla with third qubit. After that do not forget to uncompute ancilla by application of third Toffoli on first and second qubit and the ancilla. $\endgroup$ – Martin Vesely Feb 16 at 9:45
  • 1
    $\begingroup$ Thank you, but could you explain further with a circuit and some code ? $\endgroup$ – Django Ace Feb 16 at 10:01

You can implement three-input Toffoli gate with three two-input Toffoli gates and one ancilla qubit as shown below.


Assume that qubits $q_0$, $q_1$ and $q_2$ are three inputs and qubit $q_4$ is a target. Qubit $q_3$ is ancilla qubit. The first gate implements function $q_0~ \mathrm{AND}~ q_1$ and saves results of this operation to $q_3$. The second gate implements function $q_2~ \mathrm{AND}~ q_3 = q_2~\mathrm{AND}~(q_0~ \mathrm{AND}~ q_1) = q_0~\mathrm{AND}~q_1~ \mathrm{AND}~ q_2$. Eventually, qubits $q_0$, $q_1$ and $q_2$ control qubit $q_4$. The last gate is used for uncomputation ancilla qubit $q_3$ back to state $|0\rangle$ (this is necessary because ancilla qubits entangled with other qubits can cause interference and increase error rate, note that inverse gate for Toffoli is again Toffoli).

Here is a code in QASM (sorry, I am not experienced in Qiskit)

include "qelib1.inc";

qreg q[5];
creg c[5];

ccx q[0],q[1],q[3];
ccx q[2],q[3],q[4];
ccx q[0],q[1],q[3];
|improve this answer|||||
  • $\begingroup$ Thanks ! i am going to try this using Qiskit and let you know the result ! $\endgroup$ – Django Ace Feb 16 at 11:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.